Skip to content
Draft
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion src/sharpit/ui/static/index.html
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
<meta name="viewport" content="width=device-width, initial-scale=1" />
<meta name="color-scheme" content="light dark" />
<title>sharpit</title>
<script type="module" crossorigin src="./assets/index-D5RafmH4.js"></script>
<script type="module" crossorigin src="./assets/index-BRGlidtG.js"></script>
<link rel="stylesheet" crossorigin href="./assets/index-pfmFdM9Q.css">
</head>
<body>
Expand Down
4 changes: 2 additions & 2 deletions tests/engine/advisors/test_advisor_rules.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,9 @@ def test_severity_order():
assert severity_rank("UNKNOWN") == 5 # unknown sorts after every known severity (SeverityOrder.rank)


def test_rule_definition_is_frozen():
def test_rule_definition_is_frozen(monkeypatch: pytest.MonkeyPatch):
with pytest.raises(dataclasses.FrozenInstanceError):
RULE.severity = "LOW" # type: ignore[misc]
monkeypatch.setattr(RULE, "severity", "LOW")


def test_failed_result_keeps_first_ten_samples():
Expand Down
3 changes: 2 additions & 1 deletion tests/engine/capture/test_exceptions.py
Original file line number Diff line number Diff line change
Expand Up @@ -199,8 +199,9 @@ def test_set_status_known_and_unknown():
@pytest.mark.parametrize("value", [None, "", " ", "CLOSED"])
def test_invalid_status_checked_before_the_group(value: str | None):
# ported: ExceptionsService.parseStatus / updateStatus (a bad status is a 400 even for an unknown id)
store = _store()
with pytest.raises(ValueError, match=r"^Invalid status '.*'; expected one of OPEN, ACKNOWLEDGED, RESOLVED$"):
_store().set_status("does-not-exist", value)
store.set_status("does-not-exist", value)


def test_acknowledged_does_not_auto_transition():
Expand Down
2 changes: 1 addition & 1 deletion tests/engine/capture/test_logtail.py
Original file line number Diff line number Diff line change
Expand Up @@ -105,7 +105,7 @@ def test_handler_level_notset_changes_no_level(isolated: logging.Logger):
assert levels[2] == logging.WARNING
isolated.info("not enabled") # the app's levels decide, sharpit lowers nothing
isolated.warning("seen")
assert (root.level, isolated.level, isolated.getEffectiveLevel()) == levels
assert levels == (root.level, isolated.level, isolated.getEffectiveLevel())
assert _messages(buffer) == ["seen"]


Expand Down
9 changes: 6 additions & 3 deletions tests/engine/test_sqla.py
Original file line number Diff line number Diff line change
Expand Up @@ -559,12 +559,13 @@ def boom(*_args: object, **_kwargs: object) -> None:
raise RuntimeError("recorder broke")

monkeypatch.setattr(_recorder(handle), "record", boom)
duplicate = sa.text("insert into t (id) values (1)")
with caplog.at_level(logging.WARNING, logger="sharpit"), engine.begin() as conn:
conn.execute(sa.text("create table t (id integer primary key)"))
conn.execute(sa.text("insert into t (id) values (1)"))
assert conn.execute(sa.text("select id from t")).scalars().all() == [1]
with pytest.raises(sa.exc.IntegrityError):
conn.execute(sa.text("insert into t (id) values (1)"))
conn.execute(duplicate)
warnings = [r.getMessage() for r in caplog.records if r.name == "sharpit"]
assert len(warnings) == 1, warnings
assert "sql statement" in warnings[0], warnings
Expand All @@ -574,8 +575,9 @@ def boom(*_args: object, **_kwargs: object) -> None:
def test_failed_statement_recorded_with_error():
engine = sa.create_engine("sqlite://")
handle = _install(engines=[engine])
missing = sa.text("select * from missing_table")
with engine.connect() as conn, pytest.raises(sa.exc.OperationalError):
conn.execute(sa.text("select * from missing_table"))
conn.execute(missing)
entry = _entries(handle)[0]
assert (entry["success"], entry["affectedRows"]) == (False, None)
# owner ruling 2026-11-07, structured driver codes: the class and its code, never the driver's text
Expand Down Expand Up @@ -625,8 +627,9 @@ def slow(_conn: Any) -> None:
async def main() -> None:
await sqla.run_db_read(engine, slow, 0.05)

running = main()
with pytest.raises(TimeoutError):
asyncio.run(main())
asyncio.run(running)


def test_run_db_read_done_once_the_worker_thread_really_returns(tmp_path: Path):
Expand Down
44 changes: 30 additions & 14 deletions tests/engine/test_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -285,8 +285,9 @@ def test_every_action_tool_references_an_action_capable_panel():

def test_mcp_call_action_tool_unknown_32602():
# new: BootUI actions other than pentest_scan remain CLI-only
request = _call(_ctx())
with pytest.raises(RpcError) as exc:
call_tool(_call(_ctx()), "vulnerabilities_scan", {}, via="mcp")
call_tool(request, "vulnerabilities_scan", {}, via="mcp")
assert (exc.value.code, exc.value.message) == (INVALID_PARAMS, "Unknown tool: vulnerabilities_scan")


Expand Down Expand Up @@ -336,32 +337,36 @@ def test_bootui_pentest_scan_is_the_mcp_action_tool():
],
)
def test_invalid_params(name: Any, args: Any, message: str):
request = _call(_ctx())
with pytest.raises(RpcError) as exc:
call_tool(_call(_ctx()), name, args, via="mcp")
call_tool(request, name, args, via="mcp")
assert (exc.value.code, exc.value.message) == (INVALID_PARAMS, message)


def test_disabled_panel_is_an_in_band_refusal():
# ported: BootUiMcpServiceTests.toolsCallOnDisabledPanelReturnsInBandError
ctx = _ctx(panels={"overview": PanelSettings(enabled=False)})
request = _call(ctx)
with pytest.raises(ToolCallError) as exc:
call_tool(_call(ctx), "get_overview", {}, via="mcp")
call_tool(request, "get_overview", {}, via="mcp")
assert (exc.value.message, exc.value.status) == ("Panel is disabled via SHARPIT_PANELS_OVERVIEW_ENABLED=false", 403)


def test_action_tool_on_read_only_panel_is_refused():
# ported: BootUiMcpServiceTests.actionToolOnReadOnlyPanelIsRefused
ctx = _ctx(panels={"vulnerabilities": PanelSettings(read_only=True)})
request = _call(ctx)
with pytest.raises(ToolCallError) as exc:
call_tool(_call(ctx), "vulnerabilities_scan", {}, via="cli")
call_tool(request, "vulnerabilities_scan", {}, via="cli")
assert exc.value.message == "Panel is read-only via SHARPIT_PANELS_VULNERABILITIES_READ_ONLY=true"
assert exc.value.status == 403


def test_action_tool_refused_under_global_read_only():
# adapted: BootUiMcpServiceTests.actionToolOnReadOnlyPanelIsRefused (global SHARPIT_READ_ONLY)
request = _call(_ctx(read_only=True))
with pytest.raises(ToolCallError) as exc:
call_tool(_call(_ctx(read_only=True)), "vulnerabilities_scan", {}, via="cli")
call_tool(request, "vulnerabilities_scan", {}, via="cli")
assert exc.value.message == "sharpit is read-only via SHARPIT_READ_ONLY=true"


Expand Down Expand Up @@ -411,8 +416,9 @@ def busy(_c: CallContext, _a: dict[str, Any]) -> dict[str, Any]:
raise ActionBusy("vulnerabilities-scan", "vulnerabilities-scan")

tool = _tool("scan_x", busy, panel="vulnerabilities", action=True)
request = _call(_ctx())
with pytest.raises(ToolCallError) as exc:
call_tool(_call(_ctx()), "scan_x", {}, via="cli", tools=(tool,))
call_tool(request, "scan_x", {}, via="cli", tools=(tool,))
assert exc.value.status == 409
assert exc.value.message == str(ActionBusy("vulnerabilities-scan", "vulnerabilities-scan"))

Expand All @@ -423,8 +429,10 @@ def test_tool_client_error_is_in_band():
def bad(_c: CallContext, _a: dict[str, Any]) -> dict[str, Any]:
raise BadRequest("exception does-not-exist not found")

request = _call(_ctx())
handler_tool = _tool("get_x", bad)
with pytest.raises(ToolCallError) as exc:
call_tool(_call(_ctx()), "get_x", {}, via="mcp", tools=(_tool("get_x", bad),))
call_tool(request, "get_x", {}, via="mcp", tools=(handler_tool,))
assert (exc.value.message, exc.value.status) == ("exception does-not-exist not found", 400)


Expand All @@ -435,8 +443,10 @@ def test_unexpected_failure_is_internal_error_without_details(caplog: pytest.Log
def boom(_c: CallContext, _a: dict[str, Any]) -> dict[str, Any]:
raise failure

request = _call(_ctx())
handler_tool = _tool("get_x", boom)
with pytest.raises(RpcError) as exc:
call_tool(_call(_ctx()), "get_x", {}, via="mcp", tools=(_tool("get_x", boom),))
call_tool(request, "get_x", {}, via="mcp", tools=(handler_tool,))
assert (exc.value.code, exc.value.message) == (INTERNAL_ERROR, "Internal error")
reported = [r for r in caplog.records if r.exc_info and r.exc_info[1] is failure]
assert len(reported) == 1
Expand All @@ -461,8 +471,9 @@ def test_capacity_refusal_32001():
try:
while not workers:
threading.Event().wait(0.01)
request = _call(ctx)
with pytest.raises(RpcError) as exc:
call_tool(_call(ctx), "get_fast", {}, via="mcp", tools=tools)
call_tool(request, "get_fast", {}, via="mcp", tools=tools)
assert (exc.value.code, exc.value.message) == (
SERVER_AT_CAPACITY,
"MCP server is at capacity; try again shortly.",
Expand All @@ -484,8 +495,9 @@ def test_timeout_releases_semaphore():
tools = (_blocking_tool(release, workers), _tool("get_fast", lambda _c, _a: {"fast": True}))
ctx = _ctx(mcp_max_concurrent_calls=2, mcp_execution_timeout="50ms")
try:
request = _call(ctx)
with pytest.raises(RpcError) as exc:
call_tool(_call(ctx), "get_slow", {}, via="mcp", tools=tools)
call_tool(request, "get_slow", {}, via="mcp", tools=tools)
assert (exc.value.code, exc.value.message) == (TOOL_TIMEOUT, "MCP tool execution timed out")
assert workers[0].is_alive() # the abandoned worker still runs and holds one of the two slots
assert call_tool(_call(ctx), "get_fast", {}, via="mcp", tools=tools) == {"fast": True}
Expand All @@ -505,11 +517,13 @@ def test_abandoned_workers_bound_capacity():
ctx = _ctx(mcp_max_concurrent_calls=2, mcp_execution_timeout="50ms")
try:
for _ in range(2):
request = _call(ctx)
with pytest.raises(RpcError) as timed_out:
call_tool(_call(ctx), "get_slow", {}, via="mcp", tools=tools)
call_tool(request, "get_slow", {}, via="mcp", tools=tools)
assert timed_out.value.code == TOOL_TIMEOUT
request = _call(ctx)
with pytest.raises(RpcError) as refused:
call_tool(_call(ctx), "get_fast", {}, via="mcp", tools=tools)
call_tool(request, "get_fast", {}, via="mcp", tools=tools)
assert (refused.value.code, refused.value.message) == (
SERVER_AT_CAPACITY,
"MCP server is at capacity; try again shortly.",
Expand All @@ -530,13 +544,15 @@ def test_cap_counts_running_and_abandoned_together():
ctx = _ctx(mcp_max_concurrent_calls=2, mcp_execution_timeout="300ms")
running = threading.Thread(target=lambda: call_tool(_call(ctx), "get_slow", {}, via="mcp", tools=tools))
try:
request = _call(ctx)
with pytest.raises(RpcError):
call_tool(_call(ctx), "get_slow", {}, via="mcp", tools=tools) # times out: abandoned
call_tool(request, "get_slow", {}, via="mcp", tools=tools) # times out: abandoned
running.start()
while len(workers) < 2:
threading.Event().wait(0.01)
request = _call(ctx)
with pytest.raises(RpcError) as refused:
call_tool(_call(ctx), "get_fast", {}, via="mcp", tools=tools)
call_tool(request, "get_fast", {}, via="mcp", tools=tools)
assert refused.value.code == SERVER_AT_CAPACITY
finally:
release.set()
Expand Down
4 changes: 2 additions & 2 deletions tests/engine/vulns/test_interpreter.py
Original file line number Diff line number Diff line change
Expand Up @@ -469,7 +469,7 @@ def test_explicit_versions_and_ranges_union(matches_explicit: bool):
f = interpret(doc, pkg(), ID)
assert f is not None
assert f.score == 5.4
assert (f.fixed_versions, f.fix_available) == (([], False) if matches_explicit else (["1.1"], True))
assert (([], False) if matches_explicit else (["1.1"], True)) == (f.fixed_versions, f.fix_available)


# ported: OsvVulnerabilityScannerTests.unsupportedRangesRetainQueryFindingWithoutBorrowingPackageClaims
Expand All @@ -486,7 +486,7 @@ def test_unsupported_ranges_retain_finding(global_severity: bool):
f = interpret(doc, pkg(), ID)
assert f is not None
assert f.id == ID
assert (f.severity, f.score) == (("MEDIUM", 5.4) if global_severity else ("UNKNOWN", None))
assert (("MEDIUM", 5.4) if global_severity else ("UNKNOWN", None)) == (f.severity, f.score)
assert (f.fixed_versions, f.fix_available, f.unresolved) == ([], False, True)


Expand Down
21 changes: 14 additions & 7 deletions tests/engine/vulns/test_osv.py
Original file line number Diff line number Diff line change
Expand Up @@ -182,35 +182,40 @@ def test_empty_input_sends_nothing(no_side_effects):
# ported: OsvVulnerabilityScanner.queryBatch (transport failure on the first page is an error)
@pytest.mark.parametrize("error", [TimeoutError("timed out"), urllib.error.URLError("refused"), OSError("reset")])
def test_timeout_raises_osv_error(no_side_effects, error: BaseException):
scanner = client(replies(error))
with pytest.raises(OsvError):
client(replies(error)).querybatch([WIDGET])
scanner.querybatch([WIDGET])


# ported: OsvVulnerabilityScannerTests.initialPaginationFailureIsErrorWithoutCompletedQueries
@pytest.mark.parametrize("kind", FAILURES)
def test_initial_failure_raises(no_side_effects, kind: str):
scanner = client(replies(failure(kind)))
with pytest.raises(OsvError) as raised:
client(replies(failure(kind))).querybatch([WIDGET])
scanner.querybatch([WIDGET])
if kind == "body-cap":
assert "Response body exceeds 5242880 bytes" in str(raised.value)


# ported: OsvVulnerabilityScannerTests.reportsErrorWithoutDroppingDependencyInventory
def test_http_500_raises(no_side_effects):
scanner = client(replies((500, "{}")))
with pytest.raises(OsvError, match="OSV query returned HTTP 500"):
client(replies((500, "{}"))).querybatch([WIDGET])
scanner.querybatch([WIDGET])


# ported: OsvVulnerabilityScannerTests.reportsErrorWhenQuerybatchResultsDoNotMatchTheQueries
def test_result_cardinality_mismatch_raises(no_side_effects):
scanner = client(replies((200, '{"results":[{}]}')))
with pytest.raises(OsvError, match="1 results for 2 queries"):
client(replies((200, '{"results":[{}]}'))).querybatch([COMPLETE, WIDGET])
scanner.querybatch([COMPLETE, WIDGET])


# ported: OsvVulnerabilityScannerTests.reportsErrorWhenQuerybatchContainsAVulnerabilityWithoutAnId
def test_vulnerability_without_id_raises(no_side_effects):
scanner = client(replies((200, '{"results":[{"vulns":[{}]}]}')))
with pytest.raises(OsvError, match="vulnerability without a non-blank id"):
client(replies((200, '{"results":[{"vulns":[{}]}]}'))).querybatch([WIDGET])
scanner.querybatch([WIDGET])


# ported: OsvVulnerabilityScanner.queryBatchRequest (each response validation branch)
Expand All @@ -227,8 +232,9 @@ def test_vulnerability_without_id_raises(no_side_effects):
],
)
def test_invalid_response_shapes_raise(no_side_effects, body: str, message: str):
scanner = client(replies((200, body)))
with pytest.raises(OsvError, match=message):
client(replies((200, body))).querybatch([WIDGET])
scanner.querybatch([WIDGET])


# ported: OsvVulnerabilityScanner.queryBatchRequest (blank next_page_token is absent)
Expand Down Expand Up @@ -399,8 +405,9 @@ def test_vuln_id_is_url_encoded(no_side_effects):
],
)
def test_vuln_failures_raise_osv_error(no_side_effects, reply: Any):
scanner = client(replies(reply))
with pytest.raises(OsvError):
client(replies(reply)).vuln("V-FAIL")
scanner.vuln("V-FAIL")


# new: opener=None builds urllib's opener on first use, not at definition time
Expand Down
6 changes: 4 additions & 2 deletions tests/fastapi/test_capture_wiring.py
Original file line number Diff line number Diff line change
Expand Up @@ -150,8 +150,9 @@ async def app(_scope: Scope, _receive: Receive, send: Send) -> None:
await send(_start(201))
raise ValueError("boom")

running = _run(handle.context, app)
with pytest.raises(ValueError, match="boom"):
asyncio.run(_run(handle.context, app))
asyncio.run(running)
row = _rows(handle)[0]
assert row["status"] == 201
assert _buffer(handle).get(row["id"])["error"] is True # pyright: ignore[reportOptionalSubscript]
Expand All @@ -163,8 +164,9 @@ def test_unhandled_exception_500_and_reraised():
async def app(_scope: Scope, _receive: Receive, _send: Send) -> None:
raise ValueError("boom")

running = _run(handle.context, app)
with pytest.raises(ValueError, match="boom"):
asyncio.run(_run(handle.context, app))
asyncio.run(running)
assert _rows(handle)[0]["status"] == 500
# through a real app: Starlette's ServerErrorMiddleware sends the 500 after us
app = FastAPI()
Expand Down
4 changes: 2 additions & 2 deletions tests/test_fixtures.py
Original file line number Diff line number Diff line change
Expand Up @@ -23,8 +23,8 @@ def test_golden_shapes_load() -> None:


def test_no_side_effects_blocks_socket(no_side_effects: SideEffectGuard) -> None:
with pytest.raises(AssertionError, match="socket.connect"):
socket.socket().connect(("127.0.0.1", 9))
with socket.socket() as sock, pytest.raises(AssertionError, match="socket.connect"):
sock.connect(("127.0.0.1", 9))
with pytest.raises(AssertionError, match="create_connection"):
socket.create_connection(("127.0.0.1", 9))
no_side_effects.rebaseline()
Expand Down
4 changes: 3 additions & 1 deletion tests/test_ui_no_html.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,12 +2,14 @@

from pathlib import Path

import pytest

UI_SRC = Path(__file__).parents[1] / "ui" / "src"


def test_no_raw_html_in_views() -> None:
if not UI_SRC.is_dir(): # the sdist ships no ui/
return
pytest.skip("the sdist ships no ui/")
files = sorted(UI_SRC.rglob("*.svelte"))
assert files, "no .svelte files found: the path is wrong"
assert [str(f.relative_to(UI_SRC)) for f in files if "{@html" in f.read_text(encoding="utf-8")] == []
3 changes: 2 additions & 1 deletion ui/src/lib/api.ts
Original file line number Diff line number Diff line change
Expand Up @@ -57,7 +57,8 @@ function url(path: string, params: Params = {}): string {
if (value !== null && value !== undefined && value !== '') query.set(key, String(value));
}
const qs = query.toString();
return `api/${path}${qs ? `?${qs}` : ''}`;
const suffix = qs ? `?${qs}` : '';
return `api/${path}${suffix}`;
}

async function request<T>(
Expand Down
7 changes: 5 additions & 2 deletions ui/src/lib/palette.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,7 +22,7 @@ export function search(index: readonly Entry[], query: string, limit = 50): Hit[
const q = query.trim().toLowerCase();
if (!q) return index.slice(0, limit).map((entry) => ({ entry, score: 0 }));
// a word starts after a separator common in logger names, config keys and titles
const wordStart = new RegExp(`[\\s._\\-/:]${q.replace(/[.*+?^${}()|[\]\\]/g, '\\$&')}`);
const wordStart = new RegExp(String.raw`[\s._\-/:]${q.replace(/[.*+?^${}()|[\]\\]/g, String.raw`\$&`)}`);
const hits: Hit[] = [];
for (const entry of index) {
const score = scoreOf(entry.label.toLowerCase(), q, wordStart);
Expand All @@ -33,7 +33,10 @@ export function search(index: readonly Entry[], query: string, limit = 50): Hit[
}

// the same order in every browser locale
const byCodeUnit = (a: string, b: string) => (a < b ? -1 : a > b ? 1 : 0);
const byCodeUnit = (a: string, b: string) => {
if (a < b) return -1;
return a > b ? 1 : 0;
};

function scoreOf(label: string, q: string, wordStart: RegExp): number {
if (label === q) return EXACT;
Expand Down
3 changes: 2 additions & 1 deletion ui/src/lib/route.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ function decode(text: string): string {
}

export function href(panel: string, q = ''): string {
return `#/${encodeURIComponent(panel)}${q ? `?${new URLSearchParams({ q })}` : ''}`;
const search = q ? `?${new URLSearchParams({ q })}` : '';
return `#/${encodeURIComponent(panel)}${search}`;
}

export const route = readable(parse(location.hash), (set) => {
Expand Down
Loading
Loading