diff --git a/AGENTS.md b/AGENTS.md index b74409aa..1d85a4ca 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -6,7 +6,7 @@ Single source of truth for every agent working in this repo (Claude Code, Codex, ## What sharpit is An embedded, local-only developer console for Python web apps: a Python port of BootUI (Spring Boot). It is at -**0.9.0.** It targets FastAPI. One call mounts it: +**0.10.0.** It targets FastAPI. One call mounts it: ```python import sharpit diff --git a/CHANGELOG.md b/CHANGELOG.md index c4981eb0..2b067da4 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -5,6 +5,8 @@ and the project uses [Semantic Versioning](https://semver.org/). ## [Unreleased] +## [0.10.0] - 2026-11-29 + ### Added - Baseline entries record a digest of their test (`owner`); reports list `inconclusive` and `inconclusiveFindings`. Inconclusive entries are listed and kept on rewrite also while an advisor entry is carried. A max-queries entry is checked against the queries of all phases of its test summed, so queries moved into or split across fixtures are inconclusive, not fixed; a fixture that seeds rows keeps a fixed max-queries entry inconclusive until it is cleared. Max-queries, N+1 and unbounded-read entries are inconclusive when the run used a sqlite3 connection factory or cursor class that sharpit does not trace. Known limits: SQL sent through a raw driver cursor beside SQLAlchemy is not traced, and unbounded reads are recorded only in the call phase, so such a change can read fixed. @@ -37,6 +39,13 @@ and the project uses [Semantic Versioning](https://semver.org/). from its environment. A github.com token is no longer sent to an Enterprise host. A setup that relied on `GITHUB_TOKEN` for an Enterprise host sets `GH_HOST` and `GH_ENTERPRISE_TOKEN`, or runs `gh auth login --hostname `. +- The pytest plugin masks node ids, and the targets and messages of gate findings, in the JSON report, the JUnit + report, the written baseline and sharpit's own terminal summary lines, as the SARIF report already did: a + secret-shaped parametrize value is no longer stored in clear. pytest's own lines (`FAILED`, `-v` output) still print + the clear node id. Baseline entries still match by fingerprint, so an existing baseline keeps matching. Known limit: + the masker treats a file, class or parameter name that contains a sensitive word (`auth`, `token`, `key`, `secret`) + as a key, so `tests/test_auth.py::test_login` is written as `tests/test_auth.py:******` and a secret-shaped + parameter blanks the whole identifier; counts and test owners still use the clear id. ## [0.9.0] - 2026-11-23 @@ -571,7 +580,8 @@ Listed in section 14 of the design spec. The main ones: - Behind a TLS-terminating proxy, uvicorn needs `--proxy-headers` for the Origin check to pass. - Masking is name- and shape-based: vendor-prefixed tokens under harmless names (`sk_live_...`, `ghp_...`) can show. -[Unreleased]: https://github.com/ffroliva/sharpit/compare/v0.9.0...HEAD +[Unreleased]: https://github.com/ffroliva/sharpit/compare/v0.10.0...HEAD +[0.10.0]: https://github.com/ffroliva/sharpit/releases/tag/v0.10.0 [0.9.0]: https://github.com/ffroliva/sharpit/releases/tag/v0.9.0 [0.8.0]: https://github.com/ffroliva/sharpit/releases/tag/v0.8.0 [0.7.0]: https://github.com/ffroliva/sharpit/releases/tag/v0.7.0 diff --git a/README.md b/README.md index 020fd850..03982102 100644 --- a/README.md +++ b/README.md @@ -84,7 +84,7 @@ installed packages for known vulnerabilities when you ask for it. Every panel in swallows an exception, and runs the REST API advisor over your routes. When capture cannot see enough to judge, the run fails closed. -> **Status: alpha (0.9.0, FastAPI and Starlette console; Flask supported for test gates).** Django is not supported. See [CHANGELOG.md](https://github.com/ffroliva/sharpit/blob/main/CHANGELOG.md). +> **Status: alpha (0.10.0, FastAPI and Starlette console; Flask supported for test gates).** Django is not supported. See [CHANGELOG.md](https://github.com/ffroliva/sharpit/blob/main/CHANGELOG.md). ## Security @@ -334,7 +334,7 @@ sharpit ports BootUI feature by feature: 0.6.0 targets BootUI 2.3.0, 0.7.0 targe | Runtime insight kinds that evaluate | none | 8 of 28 registered | 10 of 28 registered | 11 of 29 registered | 11 of 29 registered | 11 of 29 registered | 28 | 28 | 29 | | Applicable BootUI GET fixture cases served | not measured | 33 (5 shape-identical, 28 partial) | 33 (5 shape-identical, 28 partial) | 33 (5 shape-identical, 28 partial) | 33 (5 shape-identical, 28 partial) | 41 across 38 routes (5 shape-identical, 36 partial) | 65 | not captured | 56 | -The sharpit 0.10.0 column describes the unreleased `main` branch. The increase from 33 to 41 reflects an inventory +The sharpit 0.10.0 column describes the 0.10.0 release. The increase from 33 to 41 reflects an inventory correction for existing routes. Most cases marked `n-a` are served with fixtures that cannot establish parity. How each row is counted, the insight kinds that evaluate, and what comes next: [ROADMAP.md](ROADMAP.md). diff --git a/README.zh-CN.md b/README.zh-CN.md index 5e406f63..00b74ac4 100644 --- a/README.zh-CN.md +++ b/README.zh-CN.md @@ -72,7 +72,7 @@ sharpit 默认关闭,只有检测到开发模式时才会启用:`fastapi dev **功能概览:** 共 47 个面板。可以在应用运行时调整日志级别、按路由发现 N+1 查询,并按需扫描已安装依赖包中的已知漏洞。 全部面板的浅色和深色截图见 [截图目录](docs/screenshots.md)。 -> **状态:alpha(0.9.0;控制台支持 FastAPI 与 Starlette,Flask 支持测试门禁)。** 不支持 Django。更新记录见 [CHANGELOG.md](CHANGELOG.md)。 +> **状态:alpha(0.10.0;控制台支持 FastAPI 与 Starlette,Flask 支持测试门禁)。** 不支持 Django。更新记录见 [CHANGELOG.md](CHANGELOG.md)。 ## 安全 diff --git a/ROADMAP.md b/ROADMAP.md index 3d691032..dc8c07c2 100644 --- a/ROADMAP.md +++ b/ROADMAP.md @@ -110,15 +110,16 @@ sharpit 0.9.0 stays on BootUI 2.5.0 and closes part of the gaps recorded against - **Accepted findings:** the pytest accept marker takes a `reason=`, and `--sharpit-require-reason` makes it mandatory ([#253](https://github.com/ffroliva/sharpit/issues/253) item 2). An invalid `SHARPIT_EMAIL_MASK_CONTENT` keeps email content masked. - **Offline documentation:** `sharpit docs` lists, reads and searches the documentation bundled with the package; the site publishes `llms.txt`. -## What is next (0.10.0) +## What is next (0.11.0) -Deferred from 0.9.0, each with a follow-up issue: +Deferred from 0.10.0, each with a follow-up issue on the 0.11.0 milestone (`docs/reports/2026-11-28-0.10.0-decisions.md`): -- **Flask console** ([#260](https://github.com/ffroliva/sharpit/issues/260)): the console contract is in `engine/console` (0.9.0, not wired); next come the response corpus that guards the handler move, the handler extraction one panel group at a time, `sharpit.install(app)` for Flask, request correlation and an example app. +- **Flask console** ([#348](https://github.com/ffroliva/sharpit/issues/348)): the console contract slice shipped in 0.10.0; next come the handler move, `sharpit.install(app)` for Flask, request correlation and an example app. +- **API route parity** ([#347](https://github.com/ffroliva/sharpit/issues/347)): missing routes, same-route baselines and partial route differences after the 0.10.0 route inventory. - **Journal sources and insight kinds** ([#299](https://github.com/ffroliva/sharpit/issues/299)): transaction boundaries, transaction and ORM journal sources, authorization dependencies and the remaining kinds, within the 30 µs transaction budget. -- **API route parity** ([#300](https://github.com/ffroliva/sharpit/issues/300)): missing routes, same-route baselines and partial route differences from the 2.5.0 inventory. -- **`paged-without-order`** ([#301](https://github.com/ffroliva/sharpit/issues/301)): needs SQL row-limit and shape analysis that holds under masking. -- **Masking follow-ups:** the masked exception message in swallowed-exception findings ([#253](https://github.com/ffroliva/sharpit/issues/253) item 1) and trace and journal masking on the matrix path ([#302](https://github.com/ffroliva/sharpit/issues/302)). +- **Masking follow-ups:** the masked exception message in swallowed-exception findings ([#253](https://github.com/ffroliva/sharpit/issues/253) item 1), trace and journal masking on the matrix path ([#302](https://github.com/ffroliva/sharpit/issues/302)), and masking only the secret in a test identifier rather than the rest of the name. +- **Security sinks** for SQL statements and outbound URLs, and the **BootUI 2.6.0 port**. +- **`paged-without-order`** ([#301](https://github.com/ffroliva/sharpit/issues/301)) stays open: it needs SQL row-limit and shape analysis that holds under masking. ## After 0.7.0: Flask @@ -129,6 +130,6 @@ were delivered in 0.8.0 ([#75](https://github.com/ffroliva/sharpit/issues/75), [ the pytest plugin discovers Flask applications through adapter lookup, inspects routes over `url_map` for the REST API advisor, and enables N+1 and query-budget checks on Flask-SQLAlchemy. -The console moves to 0.10.0 ([#260](https://github.com/ffroliva/sharpit/issues/260)): moving the console request +The console contract moved into the engine in 0.10.0 ([#260](https://github.com/ffroliva/sharpit/issues/260)); the rest moves to 0.11.0 ([#348](https://github.com/ffroliva/sharpit/issues/348)): moving the console request pipeline into the framework-free engine, providing `sharpit.install(app)` for Flask, request building and response translation in `sharpit.flask`, and a `flask` extra. diff --git a/SECURITY.md b/SECURITY.md index 5b290f57..ba4bd6fb 100644 --- a/SECURITY.md +++ b/SECURITY.md @@ -8,7 +8,7 @@ Security updates are provided only for the latest release on PyPI: | Version | Supported | Notes | |---|---|---| -| Latest release on PyPI (0.9.x) | Yes | Verifiable support boundary | +| Latest release on PyPI (0.10.x) | Yes | Verifiable support boundary | | Prior versions | No | Unsupported | ## Reporting a Vulnerability diff --git a/docs/reports/2026-11-28-0.10.0-decisions.md b/docs/reports/2026-11-28-0.10.0-decisions.md new file mode 100644 index 00000000..0619ac4a --- /dev/null +++ b/docs/reports/2026-11-28-0.10.0-decisions.md @@ -0,0 +1,41 @@ +# sharpit 0.10.0: decisions record + +0.10.0 stays on BootUI 2.5.0 for its ported panels and takes one security change from BootUI 2.6.0 (GitHub credentials +bound to the repository host). This file records the maintainer's rulings and the defaults taken during the 0.10.0 +lanes (2026-11-24 to 2026-11-28), so they outlive the working notes. + +## Owner rulings + +| Date | Ruling | Where it lives | +|---|---|---| +| 2026-11-24 | #304 closes with a documentation PR recording that its Task 7 is dropped. | #321 | +| 2026-11-24 | #303: a classic branch protection rule covers `release/*`; the release pull request may be scanned while it is a draft. | `skills/release/SKILL.md`, `scripts/ci/ship_scan.py` | +| 2026-11-25 | #300 ships phases 1 to 4 of the route inventory, with no `n-a` rows for the 0.9.0 column and no public cache API. | #336 | +| 2026-11-25 | HTTP exchange capture reads the request user as plain data only. | #339 | +| 2026-11-26 | Text-less statements follow BootUI: a statement with no text, including one the stdlib `sqlite3` driver refuses, counts once with empty text, raises no hook failure and keeps the run known. Fail-closed covers lost capture only. | #345, `CHANGELOG.md` | +| 2026-11-26 | Writing a baseline after an `unknown` run is refused; BootUI has no findings baseline, so this is an `n-a` deviation row. | #345 | +| 2026-11-26 | Baseline `owner` digests (#329) ship with their deviation rows (BootUI has no baseline); `inconclusive` follows BootUI's not-exercised semantics. | #352, `docs/decisions/baseline-owner.md` | +| 2026-11-26 | #334 keeps a source-rule finding as one sanitized string beginning with the file and line, as BootUI's advisor violation does. Masking, targets and fingerprints are unchanged. | #350 | +| 2026-11-27 | GitHub credentials are bound to the repository host, ported from BootUI 2.6.0 ahead of the 2.6.0 port. | #354, `CHANGELOG.md` (Security) | + +## Moved to the next release + +The release is accepted with these gaps; each has an issue on the 0.11.0 milestone. + +- **Flask console after slice 1** (#348). #260 closed for the console contract slice (#331). +- **API route parity after phase 1** (#347). #300 closed for the inventory phase (#336). +- **Journal sources and insight kinds** (#299), **masked exception message in swallowed-exception findings** (#253) and + **trace and journal masking on the matrix path** (#302): nothing of these shipped, so each issue moved whole. +- **Security sinks for SQL statements and outbound URLs.** 0.10.0 checks commands and file paths only; the later plans + of the sinks lane are not in this release. +- **Masking of whole test names.** The masker can blank a whole test identifier rather than only the secret in it; the + change touches a safety path and goes through prediction and council review first. +- **The BootUI 2.6.0 port.** The 2.6.0 delta is recorded; its remaining items, including a stricter cross-site check, + are planned for 0.11.0. + +## Defaults taken (reversible) + +- The files-sensor overhead budget is not raised after three Windows CI measurements above it (6.07 to 6.53 against + 6.0 µs per event); a performance audit follows in 0.11.0. +- In-process plugin tests collect pending garbage before the run, so an earlier test's unclosed connection is not + counted as opened before capture (#355). diff --git a/plugins/sharpit/.claude-plugin/plugin.json b/plugins/sharpit/.claude-plugin/plugin.json index 9296135b..2b5c00d8 100644 --- a/plugins/sharpit/.claude-plugin/plugin.json +++ b/plugins/sharpit/.claude-plugin/plugin.json @@ -1,6 +1,6 @@ { "name": "sharpit", - "version": "0.9.0", + "version": "0.10.0", "displayName": "sharpit", "description": "Ask a running FastAPI app about itself: routes, configuration, SQL, exceptions, health and advisors, over sharpit's read-only local MCP server.", "author": { diff --git a/plugins/sharpit/plugin.json b/plugins/sharpit/plugin.json index ae1f27ec..78941fc8 100644 --- a/plugins/sharpit/plugin.json +++ b/plugins/sharpit/plugin.json @@ -1,7 +1,7 @@ { "$schema": "https://agent-plugins.org/schemas/1.0.0/plugin.schema.json", "name": "sharpit", - "version": "0.9.0", + "version": "0.10.0", "description": "Ask a running FastAPI app about itself: routes, configuration, SQL, exceptions, health and advisors, over sharpit's read-only local MCP server.", "author": { "name": "Flavio Oliva", diff --git a/plugins/sharpit/skills/sharpit/SKILL.md b/plugins/sharpit/skills/sharpit/SKILL.md index 4cc74be3..48c3820e 100644 --- a/plugins/sharpit/skills/sharpit/SKILL.md +++ b/plugins/sharpit/skills/sharpit/SKILL.md @@ -9,7 +9,7 @@ description: > # sharpit: the local developer console for FastAPI apps -> **0.9.0.** APIs, panels and settings can still change before 1.0. +> **0.10.0.** APIs, panels and settings can still change before 1.0. > The design source is `docs/superpowers/specs/2026-10-30-sharpit-mvp-design.md`; when this file and the code > disagree, the code wins. diff --git a/skills/sharpit/SKILL.md b/skills/sharpit/SKILL.md index 4cc74be3..48c3820e 100644 --- a/skills/sharpit/SKILL.md +++ b/skills/sharpit/SKILL.md @@ -9,7 +9,7 @@ description: > # sharpit: the local developer console for FastAPI apps -> **0.9.0.** APIs, panels and settings can still change before 1.0. +> **0.10.0.** APIs, panels and settings can still change before 1.0. > The design source is `docs/superpowers/specs/2026-10-30-sharpit-mvp-design.md`; when this file and the code > disagree, the code wins. diff --git a/src/sharpit/__init__.py b/src/sharpit/__init__.py index 4848dd9c..017ace7f 100644 --- a/src/sharpit/__init__.py +++ b/src/sharpit/__init__.py @@ -1,6 +1,6 @@ """sharpit is a local developer console and pytest gate for FastAPI apps, a Python port of BootUI by Julien Dubois.""" -__version__ = "0.9.0" +__version__ = "0.10.0" from typing import TYPE_CHECKING # noqa: E402 # after __version__, the only version site diff --git a/src/sharpit/engine/testsession/baseline.py b/src/sharpit/engine/testsession/baseline.py index bf9bb7c5..0362b2fd 100644 --- a/src/sharpit/engine/testsession/baseline.py +++ b/src/sharpit/engine/testsession/baseline.py @@ -15,6 +15,7 @@ from sharpit.engine.testsession.facts import PhaseFacts, TestFacts from sharpit.engine.testsession.outcome import deciding from sharpit.engine.testsession.report import clean_text +from sharpit.engine.testsession.sink import report_masker SCHEMA = "sharpit-baseline/1" TEST_RUNTIME_PREFIX = "test-runtime:" @@ -221,7 +222,7 @@ def compare( def write(path: Path, findings: Sequence[Finding], keep: Sequence[Entry] = ()) -> None: - """Write stable, sorted baseline bytes. Findings arrive masked from the capture sink.""" + """Write stable, sorted baseline bytes. Targets and messages are masked here, node ids included.""" rows: dict[str, dict[str, Any]] = { e.fingerprint: { "fingerprint": e.fingerprint, @@ -246,6 +247,10 @@ def write(path: Path, findings: Sequence[Finding], keep: Sequence[Entry] = ()) - "observed": finding.observed, "owner": owner_of(finding.test_node_id), } + masker = report_masker() # a gate finding's target and message can hold its node id, which carries parametrize text + for row in rows.values(): + row["target"] = masker.mask_text(row["target"]) or "" + row["message"] = masker.mask_text(row["message"]) or "" payload = {"schema": SCHEMA, "findings": [rows[key] for key in sorted(rows)]} text = clean_text(json.dumps(payload, indent=2, ensure_ascii=False) + "\n") # same cleaning as the report path.parent.mkdir(parents=True, exist_ok=True) diff --git a/src/sharpit/engine/testsession/finish.py b/src/sharpit/engine/testsession/finish.py index 3465bf89..65345e31 100644 --- a/src/sharpit/engine/testsession/finish.py +++ b/src/sharpit/engine/testsession/finish.py @@ -119,3 +119,25 @@ def finish( unknown_reasons=session.unknown_reasons, ) return data, status, reasons + + +# `reason` is masked in memory in finish on purpose; node text is masked only at write time, so counts see clear ids +_NODE_TEXT = ("target", "message", "testNodeId") # a gate finding's target and message can hold its node id + + +def masked_report(data: dict[str, Any]) -> dict[str, Any]: + """A copy of the report for a file, with node ids masked as the SARIF writer masks them: a node id carries + parametrize values. The report in memory keeps the clear ids, which tell apart tests whose masked ids are equal.""" + masker = report_masker() + + def finding(dto: dict[str, Any]) -> dict[str, Any]: + return {**dto, **{key: masker.mask_text(dto[key]) or "" for key in _NODE_TEXT if dto.get(key)}} + + return { + **data, + "tests": [{**test, "nodeId": masker.mask_text(test["nodeId"]) or ""} for test in data["tests"]], + "findings": [finding(dto) for dto in data["findings"]], + "advisors": [ + {**advisor, "findings": [finding(dto) for dto in advisor["findings"]]} for advisor in data["advisors"] + ], + } diff --git a/src/sharpit/pytest_plugin/__init__.py b/src/sharpit/pytest_plugin/__init__.py index f960ff77..4fa7d7e3 100644 --- a/src/sharpit/pytest_plugin/__init__.py +++ b/src/sharpit/pytest_plugin/__init__.py @@ -29,7 +29,7 @@ from sharpit.engine.sources import dispatch, sqlite from sharpit.engine.sqltext import load_key from sharpit.engine.testsession import gates as gates -from sharpit.engine.testsession import outcome, report +from sharpit.engine.testsession import outcome from sharpit.engine.testsession.facts import SessionFacts from sharpit.engine.testsession.sink import TestSessionSink, report_masker_warnings from sharpit.pytest_plugin.apps import ( @@ -47,6 +47,7 @@ from sharpit.pytest_plugin.options import pytest_addoption as pytest_addoption from sharpit.pytest_plugin.options import resolve as resolve from sharpit.pytest_plugin.report_io import write_report as _write_report # noqa: F401 - compatibility re-export +from sharpit.pytest_plugin.report_io import write_report_files from sharpit.pytest_plugin.session import MARKER_USAGE_ERROR from sharpit.pytest_plugin.session import pytest_collection_finish as pytest_collection_finish from sharpit.pytest_plugin.session import pytest_deselected as pytest_deselected @@ -585,9 +586,7 @@ def _refresh_report_after_hook_failure(state: _State, config: Any, warning: str) if warning not in data["warnings"]: data["warnings"].append(warning) try: - report.write_json(state.options.report, data) - if state.options.junit: - report.write_junit(state.options.junit, data, allow_unknown=state.options.allow_unknown) + write_report_files(state, data) except Exception as write_exc: # noqa: BLE001 _record_hook_failure(state.sink, write_exc) diff --git a/src/sharpit/pytest_plugin/report_io.py b/src/sharpit/pytest_plugin/report_io.py index e7092e22..826d4819 100644 --- a/src/sharpit/pytest_plugin/report_io.py +++ b/src/sharpit/pytest_plugin/report_io.py @@ -15,7 +15,7 @@ from sharpit.engine.testsession import baseline as baseline_io from sharpit.engine.testsession import gates, outcome, report, sarif from sharpit.engine.testsession.facts import TestFacts, finding_from -from sharpit.engine.testsession.finish import HOOK_FAILURE_PREFIX, GateOptions, finish +from sharpit.engine.testsession.finish import HOOK_FAILURE_PREFIX, GateOptions, finish, masked_report def write_report(state: Any, session: Any, exitstatus: int) -> None: @@ -62,9 +62,7 @@ def write_report(state: Any, session: Any, exitstatus: int) -> None: if not refusal: _write_baseline(state, data) # before the report, so a write failure is in it _write_sarif(state, data, sink.masker) # likewise - report.write_json(state.options.report, data) - if state.options.junit: - report.write_junit(state.options.junit, data, allow_unknown=state.options.allow_unknown) + write_report_files(state, data) if refusal: raise pytest.UsageError(refusal) if exitstatus == 0 and outcome.exit_fails( @@ -84,6 +82,14 @@ def write_report(state: Any, session: Any, exitstatus: int) -> None: session.exitstatus = 1 +def write_report_files(state: Any, data: dict[str, Any]) -> None: + """The JSON and JUnit reports, written from one masked copy: every report file goes through here.""" + written = masked_report(data) + report.write_json(state.options.report, written) + if state.options.junit: + report.write_junit(state.options.junit, written, allow_unknown=state.options.allow_unknown) + + def _report_parts(plugin: Any, session: Any, state: Any, facts: Any) -> list[Any]: if plugin._xdist_controller(session.config, state): return state.parts diff --git a/src/sharpit/pytest_plugin/terminal.py b/src/sharpit/pytest_plugin/terminal.py index a76ac7e8..270c91db 100644 --- a/src/sharpit/pytest_plugin/terminal.py +++ b/src/sharpit/pytest_plugin/terminal.py @@ -9,6 +9,7 @@ from sharpit.engine.testsession.gates import ADVISOR as TEST_RUNTIME_GATES from sharpit.engine.testsession.gates import GATE_IDS, SWALLOWED, TEST_DOUBLE_NOTE from sharpit.engine.testsession.report import TEST_RUNTIME, finding_fails +from sharpit.engine.testsession.sink import report_masker from sharpit.pytest_plugin.apps import AUTODETECT, DETECTED_BY, advisor_assessors, skip_reason from sharpit.pytest_plugin.swallowed import SOURCE as SWALLOWED_SOURCE @@ -50,8 +51,9 @@ def _write_summary(terminalreporter: Any, config: Any, state: Any, plugin: Any, (test for test in data["tests"] if test["findings"]), key=lambda test: (-len(test["findings"]), test["nodeId"]), )[:5] + masker = report_masker() # counts above use the clear ids; a printed node id is masked like the report's for test in worst: - terminalreporter.write_line(f" {test['nodeId']}: {len(test['findings'])} finding(s)") + terminalreporter.write_line(f" {masker.mask_text(test['nodeId'])}: {len(test['findings'])} finding(s)") if not worst: terminalreporter.write_line(" (none)") swallowed_to_show = ( diff --git a/tests/pytest_plugin/test_plugin_masked_node_ids.py b/tests/pytest_plugin/test_plugin_masked_node_ids.py new file mode 100644 index 00000000..86ead973 --- /dev/null +++ b/tests/pytest_plugin/test_plugin_masked_node_ids.py @@ -0,0 +1,153 @@ +"""A pytest node id is test-author text: a parametrize value in it is masked in the report and the baseline. + +A baseline written with masked node ids still matches the same tests on the next run, and a released baseline that +stores the clear node id as a target keeps matching: entries match by fingerprint, which masking does not change. +""" + +from __future__ import annotations + +import json +from typing import Any + +import pytest +from tests.pytest_plugin.inprocess import without_driver_modules + +from sharpit.engine.testsession.gates import MAX_QUERIES +from sharpit.engine.testsession.sink import report_masker +from test_masking_corpus import AWS_KEY, GITHUB_TOKEN + +PASSWORD = "hunter2secret" +SECRETS = [f"password={PASSWORD}", AWS_KEY] +NODE_IDS = [f"test_a.py::test_q[{secret}]" for secret in SECRETS] +DID_NOT_RUN = "its test did not run" +_RUN = ["--sharpit", "--sharpit-no-advisors", "--sharpit-allow-unknown", "--sharpit-max-queries=2", "-q"] + + +@pytest.fixture(autouse=True) +def _isolated(monkeypatch: pytest.MonkeyPatch) -> None: + """The in-process runs below share this process's modules.""" + without_driver_modules(monkeypatch) + monkeypatch.setenv("SHARPIT_IDENTITY_KEY", "0123456789abcdef" * 4) + + +def _source(queries: int, secrets: list[str] | None = None, name: str = "test_q") -> str: + return ( + f"import pytest, sqlite3\n@pytest.mark.parametrize('secret', {secrets or SECRETS!r})\ndef {name}(secret):\n" + f" c=sqlite3.connect(':memory:')\n for _ in range({queries}): c.execute('SELECT 1').fetchone()\n" + ) + + +def _write_baseline(pytester: pytest.Pytester) -> list[dict[str, Any]]: + pytester.makepyfile(test_a=_source(3)) + pytester.runpytest_inprocess(*_RUN, "--sharpit-write-baseline=baseline.json", "--sharpit-report=first.json") + return json.loads((pytester.path / "baseline.json").read_text(encoding="utf-8"))["findings"] + + +def _rerun(pytester: pytest.Pytester, source: str) -> dict[str, Any]: + """A run against the baseline in its own process, so no leftover connection makes the SQL verdict incomplete.""" + pytester.makepyfile(test_a=source) + pytester.runpytest_subprocess(*_RUN, "--sharpit-baseline=baseline.json", "--sharpit-report=report.json") + return json.loads((pytester.path / "report.json").read_text(encoding="utf-8"))["baseline"] + + +def _as_released(pytester: pytest.Pytester, rows: list[dict[str, Any]]) -> list[dict[str, Any]]: + """Rewrite the baseline as a released version wrote it: clear node ids in targets and messages, no ``owner``.""" + masker = report_masker() + clear = {masker.mask_text(node): node for node in NODE_IDS} + for row in rows: + row.pop("owner", None) + if row["ruleId"] == MAX_QUERIES: + row["target"] = clear.get(row["target"], row["target"]) + row["message"] = f"{row['target']}: {row['message']}" + payload = {"schema": "sharpit-baseline/1", "findings": rows} + (pytester.path / "baseline.json").write_text(json.dumps(payload), encoding="utf-8") + assert any(row["target"] in NODE_IDS for row in rows), "the released baseline must hold a clear node id" + return rows + + +def test_report_json_holds_no_parametrize_secret(pytester: pytest.Pytester) -> None: + _write_baseline(pytester) + text = (pytester.path / "first.json").read_text(encoding="utf-8") + assert "test_q[" in text, "the run must report the parametrized tests" + assert PASSWORD not in text + assert AWS_KEY not in text + + +def test_written_baseline_holds_no_parametrize_secret(pytester: pytest.Pytester) -> None: + rows = _write_baseline(pytester) + text = (pytester.path / "baseline.json").read_text(encoding="utf-8") + assert any(row["ruleId"] == MAX_QUERIES for row in rows), "the run must baseline max-queries" + assert PASSWORD not in text + assert AWS_KEY not in text + + +def test_masked_baseline_matches_the_same_tests_next_run(pytester: pytest.Pytester) -> None: + rows = _write_baseline(pytester) + result = _rerun(pytester, _source(3)) + assert result["existing"] == len(rows) + assert result["new"] == 0 + + +def test_masked_baseline_proves_a_real_fix(pytester: pytest.Pytester) -> None: + rows = _write_baseline(pytester) + result = _rerun(pytester, _source(1)) + assert result["inconclusive"] == 0 + assert result["fixed"] == len(rows) + + +def test_released_unmasked_baseline_keeps_matching(pytester: pytest.Pytester) -> None: + rows = _as_released(pytester, _write_baseline(pytester)) + result = _rerun(pytester, _source(3)) + assert result["existing"] == len(rows) + assert result["new"] == 0 + + +def _sharpit_section(output: str) -> str: + """sharpit's own terminal summary; pytest's own lines are not sharpit's to mask.""" + return output[output.index("= sharpit:") :] + + +def test_junit_report_holds_no_parametrize_secret(pytester: pytest.Pytester) -> None: + pytester.makepyfile(test_a=_source(3)) + pytester.runpytest_inprocess(*_RUN, "--sharpit-junit=junit.xml") + text = (pytester.path / "junit.xml").read_text(encoding="utf-8") + assert MAX_QUERIES in text, "the run must report the max-queries findings" + assert PASSWORD not in text + assert AWS_KEY not in text + + +def test_terminal_summary_holds_no_parametrize_secret(pytester: pytest.Pytester) -> None: + pytester.makepyfile(test_a=_source(3)) + section = _sharpit_section(pytester.runpytest_inprocess(*_RUN, "--sharpit-report-only").stdout.str()) + assert "worst tests:" in section, "the summary must list the worst tests" + assert PASSWORD not in section + assert AWS_KEY not in section + + +def test_deleted_test_is_not_fixed_by_a_test_whose_masked_id_is_the_same(pytester: pytest.Pytester) -> None: + # both ids mask to the same text: the owner is the clear id's digest, so the other test cannot stand in for it + pytester.makepyfile(test_a=_source(3, [AWS_KEY])) + pytester.runpytest_inprocess(*_RUN, "--sharpit-write-baseline=baseline.json") + (pytester.path / "test_a.py").unlink() + pytester.makepyfile(test_b=_source(1, [GITHUB_TOKEN], "test_other")) + pytester.runpytest_subprocess(*_RUN, "--sharpit-baseline=baseline.json", "--sharpit-report=report.json") + result = json.loads((pytester.path / "report.json").read_text(encoding="utf-8"))["baseline"] + assert result["fixed"] == 0 + assert {item["reason"] for item in result["inconclusiveFindings"]} == {DID_NOT_RUN} + + +def test_report_only_counts_each_test_whose_masked_id_is_the_same(pytester: pytest.Pytester) -> None: + pytester.makepyfile(test_a=_source(3, [AWS_KEY, AWS_KEY[:-1] + "Q"])) + output = pytester.runpytest_inprocess(*_RUN, "--sharpit-report-only").stdout.str() + assert "sharpit report-only: 2 tests would fail" in output + + +def test_rewriting_a_released_baseline_of_deleted_tests_keeps_its_rows_masked(pytester: pytest.Pytester) -> None: + rows = _as_released(pytester, _write_baseline(pytester)) + pytester.makepyfile(test_a="def test_other(): pass\n") + pytester.runpytest_inprocess(*_RUN, "--sharpit-baseline=baseline.json", "--sharpit-write-baseline=baseline.json") + text = (pytester.path / "baseline.json").read_text(encoding="utf-8") + kept = json.loads(text)["findings"] + assert [row["fingerprint"] for row in kept] == sorted(row["fingerprint"] for row in rows) + assert PASSWORD not in text + assert AWS_KEY not in text diff --git a/tests/test_packaging.py b/tests/test_packaging.py index e3816b90..7e320840 100644 --- a/tests/test_packaging.py +++ b/tests/test_packaging.py @@ -5,14 +5,29 @@ import tomllib from pathlib import Path +import pytest + import sharpit PYPROJECT = tomllib.loads((Path(__file__).resolve().parents[1] / "pyproject.toml").read_text(encoding="utf-8")) PROJECT = PYPROJECT["project"] -def test_version_is_0_9_0() -> None: - assert sharpit.__version__ == "0.9.0" +def test_version_is_0_10_0() -> None: + assert sharpit.__version__ == "0.10.0" + + +@pytest.mark.parametrize( + ("page", "status"), + [ + ("README.md", "**Status: alpha ("), + ("README.zh-CN.md", "**状态:alpha("), + ("website/docs/index.md", "**Status: alpha ("), + ], +) +def test_status_line_names_the_current_version(page: str, status: str) -> None: + text = (Path(__file__).resolve().parents[1] / page).read_text(encoding="utf-8") + assert f"{status}{sharpit.__version__}" in text def test_record_security_event_is_public_api() -> None: diff --git a/website/docs/index.md b/website/docs/index.md index 76d64a5e..4a1acdf8 100644 --- a/website/docs/index.md +++ b/website/docs/index.md @@ -10,7 +10,7 @@ Spring Boot developer console. It ports BootUI's design goals, JSON contract and ![sharpit overview](https://raw.githubusercontent.com/ffroliva/sharpit/main/ui/tests/e2e/screenshots/overview-light.png) -> **Status: alpha (0.9.0, FastAPI console; Flask supported for test gates).** Django is not supported. See [CHANGELOG.md](https://github.com/ffroliva/sharpit/blob/main/CHANGELOG.md). +> **Status: alpha (0.10.0, FastAPI console; Flask supported for test gates).** Django is not supported. See [CHANGELOG.md](https://github.com/ffroliva/sharpit/blob/main/CHANGELOG.md). ## Start here