Files
Open_Ultra_SAST/tests/test_shell_wrapper.py
Marius Ciepluch efa311a112 fix(shell): the wrapper passes the retention days into the image (item 5b)
The maintainer's second decision on answer 7, taken on 2026-11-27 while the scan path
change (312c09b) was reviewed. Put with the question tool, in this question: "Answer 7
... is built, measured and reviewed, with one consequence the decision does not cover.
The wrapper passes only OPENULTRASAST_RUNS_DIR into the image, never
OPENULTRASAST_RUNS_RETENTION_DAYS. ... How should the retention reach the image?" The
option chosen, in full: "Pass it through (Recommended)": "The wrappers pass
OPENULTRASAST_RUNS_RETENTION_DAYS into the container: one more -e in
ops/shell/ousast.sh and ops/shell/ousast.ps1, a test first. The scan in the image then
honours the host's setting, 0 included. Measured: compose passes a variable named
without a value only when the host sets it. This commit stays the scan path alone; the
wrapper is the next commit." Not chosen: "Document it", "Hold answer 7".

What changed.
- ops/shell/ousast.sh: the compose run passes -e OPENULTRASAST_RUNS_RETENTION_DAYS,
  without a value, beside the runs directory's override; the comment above it says why.
- ops/shell/ousast.ps1: the same option, edited by reading: no PowerShell is installed
  here.
- tests/test_shell_wrapper.py: test_the_container_path_passes_the_retention_into_the_image.
- tests/test_run_pruning.py: the guard test of 312c09b pinned one text,
  "-e OPENULTRASAST_RUNS_DIR=/reports ousast". With the new option between the two it
  now pins the word OPENULTRASAST_RUNS_DIR=<WRAPPER_RUNS_MOUNT> wherever it stands in
  the wrapper's text.

Measured, through the wrapper function itself. The script is /tmp/opencode/s10_c8_probe.sh
and its files are under /tmp/opencode/s10_c8_probe/, one per measurement; those of the
wrapper runs start with the command and then with the line that ran. bash sources the
working tree's ops/shell/ousast.sh and runs `ousast scan examples --mode quick` with
HOME at a scratch directory, so the runs directory the wrapper mounts at /reports is a
scratch one; the real ~/.cache/openultrasast/runs was not touched
(/tmp/opencode/s10_c8_real_runs.out). The image is openultrasast:dev (3f959b31f2f2) with
the working tree's package copied over it, under a tag that OUSAST_VERSION gives to
compose, so the wrapper finds an image and does not build. Network off. No key is in the
shell's environment; compose reads the checkout's .env by default, and that file names
both keys, which docker-compose.yml:44-45 pass on, so the containers may have had them:
not looked at, and no measurement depends on it (quick mode, network none). Compose
5.5.1. Each scratch runs directory held a run of 40 days ago, a run of 5 days ago and a
directory called notes. The stamps run from 18:54:48Z to 18:54:58Z.
- Retention unset on the host (10_changed_unset.out): "notice: removed 1 run older
  than 30 days from /reports"; the expired run is gone, the run of 5 days ago, the new
  run and notes remain (11_changed_unset_after.out).
- Retention 0 on the host (20_changed_zero.out, 21_changed_zero_after.out): no notice;
  the expired run stays, with the run of 5 days ago, the new run and notes.
- Retention 3 on the host (30_changed_three.out): "notice: removed 2 runs older
  than 3 days from /reports"; both old runs are gone (31_changed_three_after.out).
- The control: HEAD's wrapper (312c09b) with retention 0 on the host (40_head_zero.out):
  "notice: removed 1 run older than 30 days from /reports". That is the gap this
  commit closes (41_head_zero_after.out).
- What the container sees of the variable under the wrapper's two options, asked of the
  image's Python (50_variable_unset.out, 51_variable_zero.out, 52_variable_empty.out):
  unset, "set to 0" and empty, as on the host. An empty value reads as not set
  (config.py, _runs_retention_days).
- The wrapper the probe ran is the tree's, and the package it was built from equals the
  tree's (03_probe_sources.out is a bare list of digests).
- The probe image is removed (90_remove_probe.out); no container remains
  (91_containers_after.out), and openultrasast:dev alone is left (92_images_after.out).

Tests. RED: an archive of HEAD (src, ops, tests, pyproject.toml) with the new test, the
package imported from the archive and the wrapper HEAD's (s10_c8_red2.out: 1 failed,
6 passed, at "ValueError: 'OPENULTRASAST_RUNS_RETENTION_DAYS' is not in list").
GREEN on the final tree: 78 passed over tests/test_shell_wrapper.py,
tests/test_run_pruning.py, tests/test_task_images.py, tests/test_docs_site.py and
tests/test_removed_plane_references.py (s10_c8_green4.out; the command is not in the
file). Mutants, the tree with one line changed, run on the two wrapper and pruning
test files (the copies are /tmp/opencode/s10_c8_mutB and s10_c8_mutD):
- WRAPPER_RUNS_MOUNT = "/reports2" fails the guard and the first test of 312c09b
  (s10_c8_mutB2.out: 2 failed, 41 passed);
- the wrapper's word changed to OPENULTRASAST_RUNS_DIR=/reports2 fails the guard and
  the wrapper test of d1f61fb (s10_c8_mutD2.out: 2 failed, 41 passed).
Two earlier GREEN runs failed on the guard as it was (s10_c8_green.out,
s10_c8_green2.out): that is the change to tests/test_run_pruning.py.

Checks on the final tree: ruff format, ruff check, mypy, compileall and the three gates
pass, and the gates print what they printed before the change (s10_c8b_exits.txt);
bash -n on ops/shell/ousast.sh exits 0.

- Review: two rounds by a reviewer subagent, reading and re-running, no docker. Round one
  approved the four files and conditioned the commit on the message: "Network off, no
  key" was unsupported, since compose reads the checkout's .env, which names both keys,
  and the review line was a placeholder. Round two checked the tree after the optional
  remarks were taken (the guard takes the word exactly; the shell command is on two
  lines) and found the code right: GREEN 78 passed again, both mutants 2 failed and 41
  passed, the probe's second run read as stated. One condition remained: the stamps at
  line 39, 18:54:48Z to 18:54:58Z.

By reading, not measured.
- ops/shell/ousast.ps1: no PowerShell is installed here.
- No page says what the wrapper passes into the image, so none needed a change:
  README.md and docs/examples.md say that OPENULTRASAST_RUNS_RETENTION_DAYS sets the
  days and that 0 keeps every run, and through the wrapper that is now true.
- A value the host sets that is not a whole number of days now stops the scan in the
  image with the message a native scan gives (config.py, _runs_retention_days); before
  it did not reach the image.

Not checked: the whole test suite; Windows and ops/shell/ousast.ps1; whether the keys
of the checkout's .env reached the probe's containers.
2026-11-27 19:59:50 +01:00

106 lines
5.3 KiB
Python

"""The shell wrapper, `ops/shell/ousast.sh`, run by bash against stubs: no Joern, no venv, no Docker."""
import shlex
import subprocess
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
WRAPPER = ROOT / "ops/shell/ousast.sh"
STUB = """#!/bin/sh
echo "{name} cwd=$PWD args=$*${{OUSAST_REPORTS:+ reports=$OUSAST_REPORTS}}"
"""
def ousast(tmp_path, executables, *arguments, without_home=False):
"""`ousast <arguments>` in tmp_path/project, with tmp_path as HOME unless `without_home` is passed. OUSAST_HOME is
a checkout that holds only what the wrapper looks for, the interpreter under its .venv is a stub, and so is each
executable named, and docker, on PATH."""
checkout = tmp_path / "checkout"
checkout.mkdir()
(checkout / "docker-compose.yml").write_text("services: {}\n")
python = checkout / ".venv" / "bin" / "python"
python.parent.mkdir(parents=True)
python.write_text(STUB.format(name="python"))
python.chmod(0o755)
bin_dir = tmp_path / "bin"
bin_dir.mkdir()
for name in ("docker", *executables):
stub = STUB.format(name=name)
if name == "docker":
# `image inspect` fails, as for an image that is not built, so the wrapper takes its build branch.
shebang, body = stub.split("\n", 1)
stub = f'{shebang}\n[ "$1" = image ] && exit 1\n{body}'
(bin_dir / name).write_text(stub)
(bin_dir / name).chmod(0o755)
project = tmp_path / "project"
project.mkdir()
script = f'source "{WRAPPER}" && ousast {" ".join(shlex.quote(a) for a in arguments)}'
environment = {"PATH": f"{bin_dir}:/usr/bin:/bin", "OUSAST_HOME": str(checkout), "HOME": str(tmp_path)}
if without_home:
del environment["HOME"]
return subprocess.run(["bash", "-c", script], cwd=project, env=environment, capture_output=True, text=True)
def test_a_native_scan_runs_in_the_callers_directory(tmp_path):
"""The native path changed into the checkout first, so `ousast scan .` scanned the checkout, not the caller.
`-P` is passed because `-m` alone puts the working directory first on the interpreter's path, where a file
of the scanned tree could stand in for a module the CLI imports."""
result = ousast(tmp_path, ["joern", "joern-parse"], "scan", ".")
assert result.returncode == 0, result.stderr
assert result.stdout.splitlines() == [f"python cwd={tmp_path / 'project'} args=-P -m openultrasast.cli scan ."]
def test_the_native_path_needs_joern_as_well_as_joern_parse(tmp_path):
"""The batch queries run `joern`; with `joern-parse` alone every one fails, and the scan still exits 0."""
result = ousast(tmp_path, ["joern-parse"], "scan", ".")
assert result.returncode == 0, result.stderr
calls = [line.split()[0] for line in result.stdout.splitlines()]
assert "python" not in calls and "docker" in calls
def test_the_container_writes_its_runs_to_the_users_cache(tmp_path):
"""The wrapper wrote its runs to ./.ousast, inside the repository it was scanning."""
result = ousast(tmp_path, "scan", ".")
runs = tmp_path / ".cache" / "openultrasast" / "runs"
assert result.returncode == 0, result.stderr
assert runs.is_dir() and not any((tmp_path / "project").iterdir())
words = result.stdout.splitlines()[-1].split()
assert words[0] == "docker" and words[-1] == f"reports={runs}"
# Without the override the run lands under runs/runs, where no pruning looks.
assert words.index("OPENULTRASAST_RUNS_DIR=/reports") < words.index("ousast")
def test_the_container_path_passes_the_retention_into_the_image(tmp_path):
"""The wrapper passed the runs directory alone. A scan in the image prunes that directory with the retention
its own environment names, 30 days when the host's does not reach it: a host keeping every run with 0 would
lose the old ones through the wrapper."""
result = ousast(tmp_path, (), "scan", ".")
assert result.returncode == 0, result.stderr
words = result.stdout.splitlines()[-1].split()
# Without a value: compose passes the variable on only when the host has it.
assert words.index("OPENULTRASAST_RUNS_RETENTION_DAYS") < words.index("ousast")
assert not any(word.startswith("OPENULTRASAST_RUNS_RETENTION_DAYS=") for word in words)
def test_the_container_path_stops_when_home_is_not_set(tmp_path):
"""With HOME unset, `$HOME/.cache` became `/.cache`: the wrapper went on to the container just the same."""
result = ousast(tmp_path, (), "scan", ".", without_home=True)
message = "ousast: HOME is not set, so there is no ~/.cache/openultrasast/runs to write the runs to"
assert result.returncode == 1, result.stderr
assert result.stderr.splitlines() == [message]
# Neither the build nor the container is started.
assert result.stdout == ""
def test_a_runs_directory_that_cannot_be_made_stops_the_wrapper(tmp_path):
"""`mkdir -p` was not checked: the wrapper went on to the container with a runs directory that did not exist."""
(tmp_path / ".cache").write_text("")
result = ousast(tmp_path, (), "scan", ".")
runs = tmp_path / ".cache" / "openultrasast" / "runs"
assert result.returncode == 1, result.stderr
# mkdir says why first; the wrapper's line is the last.
assert result.stderr.splitlines()[-1] == f"ousast: cannot create {runs}, where the runs are written"
assert result.stdout == ""