Skip to content

Commit 217cdb7

Browse files
authored
Merge pull request #798 from NVIDIA/yashraj/fix-cli-report-output-race
fix: prevent report output symlink races
2 parents fa8043c + 7e48091 commit 217cdb7

9 files changed

Lines changed: 722 additions & 212 deletions

File tree

‎README.md‎

Lines changed: 12 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -116,7 +116,7 @@ docker run --rm \
116116
**Write a report to the host filesystem** by writing to the mounted directory:
117117

118118
```bash
119-
docker run --rm \
119+
docker run --rm --user "$(id -u):$(id -g)" \
120120
-v "$PWD:/scan" \
121121
skillspector scan ./my-skill/ --no-llm --format json --output report.json
122122
```
@@ -792,6 +792,17 @@ Options:
792792
skillspector baseline <path> [-o FILE] [--no-llm] [--reason TEXT]
793793
```
794794

795+
Report files and new baselines use private permissions (0600). Existing baselines
796+
retain their access metadata when safely replaced; updates requiring in-place
797+
writes are refused. All file output uses atomic replacement. The parent directory
798+
must be writable; symlinked
799+
parents and non-regular destinations such as devices are refused. On macOS,
800+
ancestor directories must also be readable. File output requires POSIX no-follow
801+
directory operations and is unavailable on Windows. Unsupported file output fails
802+
before analysis. Omit `--output` for scan/batch stdout, or use
803+
`skillspector baseline <path> -o -` for JSON on stdout, then redirect only to a
804+
trusted destination. Run Docker with your user ID as above so you can read its files.
805+
795806
## Integrating SkillSpector
796807

797808
SkillSpector is built to be driven by other tools (CI pipelines, install gates, editor integrations). Its exit code and JSON output are a stable contract.

‎contrib/batch_scan/batch_scan.py‎

Lines changed: 27 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -78,6 +78,7 @@
7878
from types import SimpleNamespace
7979
from uuid import uuid4
8080

81+
from skillspector.file_output import require_secure_file_output, write_text_no_follow
8182
from skillspector.logging_config import set_level
8283

8384
from .api_pool import create_api_key_pool_from_env
@@ -157,8 +158,10 @@ def _kill_worker_group(pid: int) -> None:
157158
try:
158159
subprocess.run(
159160
["taskkill", "/PID", str(pid), "/T", "/F"],
160-
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
161-
timeout=5, check=False,
161+
stdout=subprocess.DEVNULL,
162+
stderr=subprocess.DEVNULL,
163+
timeout=5,
164+
check=False,
162165
)
163166
except (OSError, subprocess.TimeoutExpired):
164167
pass
@@ -203,8 +206,13 @@ def _scan_skill_process(
203206

204207

205208
def _scan_skill_bounded(
206-
skill_dir: Path, root: Path, *, api_pool=None, timeout: float = 90,
207-
startup_timeout: float = 90, **options
209+
skill_dir: Path,
210+
root: Path,
211+
*,
212+
api_pool=None,
213+
timeout: float = 90,
214+
startup_timeout: float = 90,
215+
**options,
208216
) -> tuple[dict[str, object], str | None, str]:
209217
"""Enforce the wall-clock limit on actual work, including local analysis."""
210218
options["timeout"] = timeout
@@ -367,6 +375,13 @@ def _print(*args: object, **kwargs: object) -> None:
367375
else:
368376
print(" ".join(str(a) for a in args), file=file) # type: ignore[arg-type]
369377

378+
if args.output:
379+
try:
380+
require_secure_file_output()
381+
except ValueError as exc:
382+
_print(f"Error: {exc}", markup=False, file=sys.stderr)
383+
sys.exit(2)
384+
370385
if args.verbose:
371386
set_level("DEBUG")
372387

@@ -391,8 +406,7 @@ def _print(*args: object, **kwargs: object) -> None:
391406

392407
# -- Header --------------------------------------------------------------
393408
pool_note = (
394-
f", [green]{api_pool.keys_configured} keys "
395-
f"({api_pool.total_capacity} slots)[/green]"
409+
f", [green]{api_pool.keys_configured} keys ({api_pool.total_capacity} slots)[/green]"
396410
if api_pool
397411
else ""
398412
)
@@ -503,13 +517,10 @@ def _print(*args: object, **kwargs: object) -> None:
503517
f"{snap['total_requests_served']} requests served",
504518
]
505519
if snap.get("peak_active_requests", 0) > 0:
506-
_parts.append(
507-
f"peak {snap['peak_active_requests']}/{snap['total_capacity']} slots"
508-
)
520+
_parts.append(f"peak {snap['peak_active_requests']}/{snap['total_capacity']} slots")
509521
if snap.get("rate_limits_hit", 0) > 0:
510522
_parts.append(
511-
f"{snap['rate_limits_hit']} rate-limit(s), "
512-
f"{snap['retry_successes']} retried"
523+
f"{snap['rate_limits_hit']} rate-limit(s), {snap['retry_successes']} retried"
513524
)
514525
_parts.append(f"{snap['keys_configured']} keys")
515526
_print(f"\n[dim]API Pool: {', '.join(_parts)}[/dim]")
@@ -524,7 +535,11 @@ def _print(*args: object, **kwargs: object) -> None:
524535
report_body = format_markdown(results)
525536

526537
if args.output:
527-
args.output.write_text(report_body, encoding="utf-8")
538+
try:
539+
write_text_no_follow(args.output, report_body)
540+
except (OSError, ValueError) as exc:
541+
_print(f"Error: {exc}", markup=False, file=sys.stderr)
542+
sys.exit(2)
528543
_print(f"\n[green]Batch report saved to:[/green] {display(args.output)}")
529544
else:
530545
if fmt == "terminal":

‎docs/SUPPRESSION.md‎

Lines changed: 24 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,20 @@ prevents sensitive rule text from creating a finding against itself or entering
5555
regenerated fingerprints. Other baseline files and sibling YAML/JSON files
5656
remain in normal scan scope unless they are selected with `--baseline` or `-o`.
5757

58+
Use `skillspector baseline ./my-skill/ -o -` to emit JSON on stdout. This is
59+
available on Windows too. Redirect to a **new file outside the scan target**,
60+
then replace an existing baseline only after the command exits with code 0.
61+
Redirecting directly over the old file truncates it before the scan starts,
62+
even when scanning fails. On Windows PowerShell 5.1, use `cmd /c` for the
63+
redirection or `Out-File -Encoding utf8`; its default `>` encoding is UTF-16LE,
64+
which the baseline loader does not accept. Check `$LASTEXITCODE` before replacing
65+
the old baseline. File output
66+
requires POSIX no-follow directory operations and fails before analysis when
67+
unsupported. New baselines use mode 0600; existing baselines retain access metadata
68+
when safely replaced. Updates requiring in-place writes are refused. The parent
69+
must be writable, symlinked parents and non-regular files are refused, and macOS
70+
also requires readable ancestor directories.
71+
5872
## Baseline file format
5973

6074
YAML or JSON (the `.json` extension selects JSON output when generating). Two
@@ -124,18 +138,21 @@ Only identical exact fingerprints share an entry. A baseline generated by an
124138
affected version may omit these occurrences; regenerate it to include them.
125139
If the complete baseline exceeds the loader's size or record limits, generation
126140
fails before replacing the output file instead of writing a partial baseline.
127-
After validation, generation normally writes a complete temporary file beside the
141+
After validation, generation writes a complete temporary file beside the
128142
destination and atomically replaces the output. A failed write or replacement
129143
preserves the existing baseline. Existing destinations must be writable regular
130144
files; symlinks and special files are rejected. Replacement requires a writable
131145
parent directory. On POSIX, new files grant access only to their owner; existing
132146
ordinary permission bits and ownership are preserved, including group-write access.
133-
When a non-owner has write access to an existing file, or the owner cannot
134-
assign the file's group because it is not a member, generation updates its
135-
validated descriptor in place and preserves its ACLs. This shared-file fallback
136-
serializes cooperating writers, but readers can see a partial write and an I/O
137-
failure or interruption can leave a partial baseline. Use an owner-managed output
138-
when atomic replacement is required.
147+
Access ACLs are copied through validated descriptors before any content is written.
148+
A non-owner update, or an update that cannot preserve the destination's group,
149+
fails without changing the existing baseline. Use a new owner-managed output
150+
file or `--output -` redirected to a new file in those cases. Do not redirect
151+
over the shared baseline: that rewrites the inode in place and can change other
152+
hard-linked files. Generation does not fall back to in-place
153+
writes, which would lose the atomic replacement and hard-link safety guarantees.
154+
All path operations use the same no-follow parent descriptor so a directory swap
155+
cannot redirect the write.
139156

140157
Every v2 entry must be a mapping with a 64-hex-character `sha256:` hash and a
141158
non-empty `reason`. `rule_id` and `file` are informational fields for reviewers.

‎src/skillspector/cli.py‎

Lines changed: 28 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@
4646
from skillspector import __version__, transitive
4747
from skillspector.cleanup import TempDirTracker, cleanup_result
4848
from skillspector.constants import RISK_THRESHOLD
49+
from skillspector.file_output import require_secure_file_output, write_text_no_follow
4950
from skillspector.graph_proxy import graph
5051
from skillspector.input_handler import validate_local_input_path
5152
from skillspector.inspection_ledger import (
@@ -83,6 +84,7 @@
8384
dump_baseline,
8485
effective_findings,
8586
load_baseline,
87+
serialize_baseline,
8688
source_content_key,
8789
)
8890
from skillspector.terminal_text import visible_terminal_text as _visible_terminal_text
@@ -373,7 +375,7 @@ def _write_result(
373375
"""Write report_body to file or stdout. Uses sarif_report if report_body missing."""
374376
report_body = _result_body(result)
375377
if output:
376-
Path(output).write_text(report_body, encoding="utf-8")
378+
write_text_no_follow(output, report_body)
377379
if format == FormatChoice.terminal:
378380
console.print(f"\n[green]Report saved to:[/green] {output}")
379381
else:
@@ -690,6 +692,13 @@ def scan(
690692
)
691693
raise typer.Exit(code=2)
692694

695+
if output is not None:
696+
try:
697+
require_secure_file_output()
698+
except ValueError as exc:
699+
err_console.print(f"[red]Error:[/red] {exc}")
700+
raise typer.Exit(code=2) from exc
701+
693702
if mcp_registry:
694703
if (
695704
recursive
@@ -720,7 +729,7 @@ def scan(
720729
)
721730
report = json.dumps(result, indent=2)
722731
if output:
723-
output.write_text(report, encoding="utf-8")
732+
write_text_no_follow(output, report)
724733
console.print(f"Report saved to: {output}")
725734
else:
726735
print(report)
@@ -3276,7 +3285,7 @@ def _scan_multi_skill(
32763285
rendered = json.dumps(combined, indent=2)
32773286
_ensure_recursive_output_bound(rendered)
32783287
if output is not None:
3279-
Path(output).write_text(rendered, encoding="utf-8")
3288+
write_text_no_follow(output, rendered)
32803289
progress_console.print(f"[green]Combined report saved to:[/green] {output}")
32813290
else:
32823291
sys.stdout.write(rendered)
@@ -3304,7 +3313,7 @@ def _scan_multi_skill(
33043313
rendered = json.dumps(merged_sarif, indent=2)
33053314
_ensure_recursive_output_bound(rendered)
33063315
if output is not None:
3307-
Path(output).write_text(rendered, encoding="utf-8")
3316+
write_text_no_follow(output, rendered)
33083317
progress_console.print(f"[green]Combined report saved to:[/green] {output}")
33093318
else:
33103319
sys.stdout.write(rendered)
@@ -3337,7 +3346,7 @@ def _scan_multi_skill(
33373346
)
33383347
_ensure_recursive_output_bound(rendered)
33393348
if output is not None:
3340-
Path(output).write_text(rendered, encoding="utf-8")
3349+
write_text_no_follow(output, rendered)
33413350
progress_console.print(f"[green]Combined report saved to:[/green] {output}")
33423351
elif format is FormatChoice.terminal:
33433352
console.print(rendered, markup=False, emoji=False)
@@ -3418,7 +3427,7 @@ def baseline(
34183427
typer.Option(
34193428
"--output",
34203429
"-o",
3421-
help="Where to write the baseline file (YAML; .json extension writes JSON).",
3430+
help="Baseline file (YAML; .json writes JSON), or - for JSON on stdout.",
34223431
),
34233432
] = Path(".skillspector-baseline.yaml"),
34243433
no_llm: Annotated[
@@ -3455,12 +3464,16 @@ def baseline(
34553464
_exit_on_unsupported_llm_controls(no_llm)
34563465
result = None
34573466
try:
3467+
to_stdout = str(output) == "-"
3468+
if not to_stdout:
3469+
require_secure_file_output()
34583470
if verbose:
34593471
set_level("DEBUG")
3460-
console.print("[dim]Scanning to build baseline...[/dim]")
3472+
err_console.print("[dim]Scanning to build baseline...[/dim]")
34613473
# output_format is irrelevant here; we consume findings, not report_body.
34623474
state = _scan_state(input_path, FormatChoice.json, no_llm)
3463-
state["baseline_path"] = os.path.abspath(output.expanduser())
3475+
if not to_stdout:
3476+
state["baseline_path"] = os.path.abspath(output.expanduser())
34643477
result = graph.invoke(state)
34653478
completeness_value = result.get("analysis_completeness")
34663479
completeness = completeness_value if isinstance(completeness_value, dict) else {}
@@ -3491,10 +3504,13 @@ def baseline(
34913504
file_cache=result.get("local_file_cache") or result.get("file_cache") or {},
34923505
scanner_version=__version__,
34933506
)
3494-
dump_baseline(data, output)
3495-
console.print(
3496-
f"[green]Wrote baseline with {len(findings)} suppressed finding(s) to:[/green] {output}"
3497-
)
3507+
if to_stdout:
3508+
sys.stdout.write(serialize_baseline(data, json_output=True) + "\n")
3509+
else:
3510+
dump_baseline(data, output)
3511+
console.print(
3512+
f"[green]Wrote baseline with {len(findings)} suppressed finding(s) to:[/green] {output}"
3513+
)
34983514
except typer.Exit:
34993515
raise
35003516
except (FileNotFoundError, ValueError) as e:

0 commit comments

Comments
 (0)