diff --git a/src/secfoo/cli.py b/src/secfoo/cli.py index be29a42..264f294 100644 --- a/src/secfoo/cli.py +++ b/src/secfoo/cli.py @@ -1075,8 +1075,10 @@ def assessment_list( table.add_column("Application ID") table.add_column("Security Assessment Request") table.add_column("Findings") + table.add_column("Responsible AI") for a in assessments: findings = f"{a.critical_count}C {a.high_count}H {a.medium_count}M {a.low_count}L {a.info_count}I" + responsible_ai = f"{a.responsible_ai_risk} ({a.responsible_ai_status})" if a.responsible_ai_risk else "-" table.add_row( str(a.id), a.project_display_name or "", @@ -1085,6 +1087,7 @@ def assessment_list( a.application_id or "-", a.sar_number or "-", findings, + responsible_ai, ) console.print(table) diff --git a/src/secfoo/storage/repository.py b/src/secfoo/storage/repository.py index a400fa0..994a732 100644 --- a/src/secfoo/storage/repository.py +++ b/src/secfoo/storage/repository.py @@ -707,7 +707,7 @@ def _responsible_ai_badges(self, assessment_id: int, status: str) -> tuple[str | """ row = self._conn.execute( "SELECT report_path FROM runs WHERE assessment_id = ? AND skill_id = 'responsible-ai-compliance' " - "AND status = 'success' AND report_path IS NOT NULL ORDER BY started_at DESC LIMIT 1", + "AND status = 'success' AND report_path IS NOT NULL ORDER BY started_at DESC, id DESC LIMIT 1", (assessment_id,), ).fetchone() if row is None or not row["report_path"]: diff --git a/tests/fixtures/reports/responsible-ai-compliance-critical.md b/tests/fixtures/reports/responsible-ai-compliance-critical.md new file mode 100644 index 0000000..8a35bfc --- /dev/null +++ b/tests/fixtures/reports/responsible-ai-compliance-critical.md @@ -0,0 +1,70 @@ +# Responsible AI Compliance Report + +## Summary +The target is an autonomous benefits-eligibility and payout system built on the Flask Assistants and function-calling architecture that evaluates applicant records via OpenAI's hosted `gpt-3.5-turbo` models and executes irreversible financial and access actions. Decisions affecting people's livelihood and legal rights are committed automatically with no human review, no input/output validation, no audit trail, and no appeal mechanism. Given the irreversible harm and absence of safeguards, overall risk is rated Critical. + +**Overall risk rating:** Critical + +## Findings Register + +| ID | Finding | Severity | CWE | Verdict | +|----|---------|----------|-----|---------| +| F1 | Irreversible benefits-denial and payout actions executed autonomously with no human oversight | Critical | unverified | Confirmed | +| F2 | Unvalidated model-generated arguments passed directly to side-effecting `run_action` handlers | High | CWE-20 | Confirmed | +| F3 | Complete absence of audit logging for automated decisions affecting individuals | High | CWE-778 | Confirmed | +| F4 | No bias, fairness, or accuracy evaluation despite high-stakes eligibility decisions | Medium | unverified | Confirmed | +| F5 | No applicant AI disclosure, explanation of adverse decisions, or appeal route | Medium | unverified | Confirmed | +| F6 | Shared global thread and file store leaks sensitive applicant records across sessions | Low | CWE-668 | Conditional | + +## Findings + +### [Critical] F1: Irreversible benefits-denial and payout actions executed autonomously with no human oversight +- **Severity:** Critical +- **CWE:** unverified +- **Verdict:** Confirmed +- **Location:** `examples/assistant-flask/app.py:116-121`, `examples/assistant-functions/functions.py:107-147` +- **Description:** The system routes applicant claims and supporting documents to the model and immediately commits benefits approvals, denials, and account disbursements without any human-in-the-loop gate or circuit breaker. Prompt injection in an uploaded PDF or model hallucination can trigger unauthorized payouts or wrongful denial of essential benefits with no recovery path. +- **Recommendation:** Halt autonomous execution of all benefits and payment actions immediately; require mandatory human caseworker approval before any eligibility determination or disbursement is committed. + +### [High] F2: Unvalidated model-generated arguments passed directly to side-effecting `run_action` handlers +- **Severity:** High +- **CWE:** CWE-20 +- **Verdict:** Confirmed +- **Location:** `examples/assistant-functions/functions.py:45, 107-147` +- **Description:** `run_action` decodes model-supplied JSON arguments and invokes state-changing handlers without schema validation, bounds checking, or an allowlist of safe operations. +- **Recommendation:** Enforce strict `pydantic` schema validation on all tool arguments, restrict tools to read-only lookups, and gate any write operation on explicit operator confirmation. + +### [High] F3: Complete absence of audit logging for automated decisions affecting individuals +- **Severity:** High +- **CWE:** CWE-778 +- **Verdict:** Confirmed +- **Location:** `examples/assistant-flask/app.py:26-58, 147-182`, `examples/assistant-functions/functions.py:107-147` +- **Description:** No durable record is kept of applicant inputs, model prompts/completions, run IDs, or executed actions, making forensic investigation and regulatory compliance impossible. +- **Recommendation:** Implement tamper-evident structured audit logging for every eligibility evaluation, including timestamp, case ID, model identifier, and decision rationale. + +### [Medium] F4: No bias, fairness, or accuracy evaluation despite high-stakes eligibility decisions +- **Severity:** Medium +- **CWE:** unverified +- **Verdict:** Confirmed +- **Location:** `README.md` (repository-wide; no evaluation suite or `MODEL_CARD.md` exists) +- **Description:** No fairness testing, subgroup disparity analysis, or accuracy benchmarking has been performed or documented for the eligibility workflow. +- **Recommendation:** Conduct and document fairness and accuracy evaluations across protected groups before any production use, and publish a model card detailing limitations. + +### [Medium] F5: No applicant AI disclosure, explanation of adverse decisions, or appeal route +- **Severity:** Medium +- **CWE:** unverified +- **Verdict:** Confirmed +- **Location:** `examples/chat-basic/templates/index.html:4, 11-17`, `examples/assistant-flask/templates/index.html:4, 16-22` +- **Description:** Applicants are not told an AI system evaluates their claim, receive no explanation for denials, and have no way to contest an automated outcome. +- **Recommendation:** Add clear AI disclosure, provide reason codes for adverse decisions, and expose a human-review appeal workflow. + +### [Low] F6: Shared global thread and file store leaks sensitive applicant records across sessions +- **Severity:** Low +- **CWE:** CWE-668 +- **Verdict:** Conditional (precondition: multiple applicants or operators share a running Flask process) +- **Location:** `examples/chat-basic/app.py:15-62`, `examples/assistant-flask/app.py:14-19, 26-58` +- **Description:** Module-level globals (`chat_history`, `assistant_id`, `thread_id`) expose uploaded applicant documents and conversation history across sessions. +- **Recommendation:** Isolate threads, history, and uploaded files per authenticated user session and delete OpenAI file objects after processing. + +## Coverage Notes +Reviewed all source, template, and documentation files in the repository (`README.md`, `LICENSE`, `requirements.txt`, `.gitignore`, and the four modules under `examples/`). Confidence in the assessment is high. diff --git a/tests/fixtures/reports/responsible-ai-compliance-high.md b/tests/fixtures/reports/responsible-ai-compliance-high.md index b9536a8..e1d3e4c 100644 --- a/tests/fixtures/reports/responsible-ai-compliance-high.md +++ b/tests/fixtures/reports/responsible-ai-compliance-high.md @@ -1,70 +1,70 @@ # Responsible AI Compliance Report ## Summary -The application decides eligibility for a service with no human review, no notice to the affected person and no appeal route. +The target is an automated eligibility and service-access system built on the Flask Assistants and function-calling architecture that evaluates applicant submissions via OpenAI's hosted `gpt-3.5-turbo` models and gates access to a service. The system decides eligibility for a service with no human review, no notice to affected applicants that an AI made the decision, and no appeal or recourse route. Combined with unvalidated autonomous tool execution and zero fairness or bias evaluation, this high-stakes use case poses High risk. -**Overall risk rating:** High. +**Overall risk rating:** High ## Findings Register | ID | Finding | Severity | CWE | Verdict | |----|---------|----------|-----|---------| -| F1 | No model card or intended-use statement for the hosted model | High | unverified | Confirmed | -| F2 | No bias or fairness testing is described | High | unverified | Confirmed | -| F3 | Model output is shown to the user with no review step | Medium | unverified | Confirmed | -| F4 | The UI does not say the reply is AI generated | Medium | unverified | Confirmed | -| F5 | No record of what data reaches the model | Low | unverified | Confirmed | -| F6 | No audit trail of generated replies and no way to contest one | Low | unverified | Confirmed | +| F1 | Automated eligibility decisions executed with no human review or override gate | High | unverified | Confirmed | +| F2 | Autonomous tool execution (`run_action`) updates access state without schema validation or confirmation | High | unverified | Confirmed | +| F3 | No bias or fairness evaluation for an eligibility-gating system | Medium | unverified | Confirmed | +| F4 | No applicant notice of automated decision-making and no appeal or recourse path | Medium | unverified | Confirmed | +| F5 | Shared global thread and file store exposes applicant submissions across sessions | Low | CWE-668 | Conditional | +| F6 | No structured audit trail of eligibility inputs, model outputs, or tool calls | Low | CWE-778 | Confirmed | ## Findings -### [High] F1: No model card or intended-use statement for the hosted model +### [High] F1: Automated eligibility decisions executed with no human review or override gate - **Severity:** High - **CWE:** unverified - **Verdict:** Confirmed -- **Location:** README.md, examples/ -- **Description:** Documentation. The quickstart documents how to call the model but never states its intended use, known limitations or training-data provenance. -- **Recommendation:** Add a short model card section to the README covering intended use, limitations and data provenance. +- **Location:** `examples/assistant-flask/app.py:116-121`, `examples/assistant-functions/functions.py:107-147` +- **Description:** The application accepts applicant details and uploaded supporting documents, prompts the model to determine service eligibility, and applies the resulting grant/deny outcome directly without any human-in-the-loop checkpoint. Because access to the service directly affects individuals and no reviewer inspects denials or edge cases, model hallucinations or prompt-injection payloads in uploaded files can wrongly exclude eligible people. +- **Recommendation:** Require explicit human reviewer sign-off before any eligibility denial or access revocation takes effect, and display the model's supporting evidence to the reviewer rather than auto-committing the decision. -### [High] F2: No bias or fairness testing is described +### [High] F2: Autonomous tool execution (`run_action`) updates access state without schema validation or confirmation - **Severity:** High - **CWE:** unverified - **Verdict:** Confirmed -- **Location:** N/A -- **Description:** Bias & fairness. Nothing in the repository describes fairness testing or documents known failure modes for any subgroup. -- **Recommendation:** State explicitly that no fairness testing was done and why it is out of scope for a sample app. +- **Location:** `examples/assistant-functions/functions.py:45, 107-147` +- **Description:** `run_action` parses tool arguments straight from model output via `json.loads` and dispatches access-gating actions without schema validation, an action allowlist, or operator confirmation before `submit_tool_outputs` is called. +- **Recommendation:** Validate all model-supplied tool arguments against a strict `pydantic` schema, restrict `run_action` to an explicit allowlist of non-destructive read tools, and require human confirmation for any state-changing eligibility action. -### [Medium] F3: Model output is shown to the user with no review step +### [Medium] F3: No bias or fairness evaluation for an eligibility-gating system - **Severity:** Medium - **CWE:** unverified - **Verdict:** Confirmed -- **Location:** app.py -- **Description:** Human oversight. The app returns generated text straight to the caller. No decision is made on a person's behalf, so no oversight is required for the stakes involved. -- **Recommendation:** Document that outputs are advisory and must be reviewed before use in any decision. +- **Location:** `README.md` (repository-wide; no evaluation suite or `MODEL_CARD.md` exists) +- **Description:** The repository contains no fairness metrics, demographic parity checks, or subgroup error-rate evaluations, despite using a general-purpose LLM to gate access to a service. Neither `README.md` nor any doc states the intended population, known failure modes, or out-of-scope uses. +- **Recommendation:** Run and document a pre-deployment fairness evaluation across relevant applicant cohorts, publish a model card with known limitations, and prohibit deployment without documented accuracy thresholds. -### [Medium] F4: The UI does not say the reply is AI generated +### [Medium] F4: No applicant notice of automated decision-making and no appeal or recourse path - **Severity:** Medium - **CWE:** unverified - **Verdict:** Confirmed -- **Location:** templates/index.html -- **Description:** Transparency to end users. A reader of the page cannot tell the pet names are generated by a model. -- **Recommendation:** Add a one-line notice that the suggestions are AI generated. +- **Location:** `examples/chat-basic/templates/index.html:4, 11-17`, `examples/assistant-flask/templates/index.html:4, 16-22` +- **Description:** Applicants are not informed that an AI system is evaluating their eligibility or that responses may be inaccurate, and the interface provides no mechanism to contest an adverse decision or request human reconsideration. +- **Recommendation:** Add a clear pre-submission disclosure that an AI assists with intake, and provide a visible appeal route and human-review contact for every adverse eligibility outcome. -### [Low] F5: No record of what data reaches the model +### [Low] F5: Shared global thread and file store exposes applicant submissions across sessions - **Severity:** Low -- **CWE:** unverified -- **Verdict:** Confirmed -- **Location:** app.py -- **Description:** Data provenance & consent. The prompt is built from user input only, but nothing documents that or how long inputs are retained by the provider. -- **Recommendation:** Document what is sent to the provider and link the provider's retention terms. +- **CWE:** CWE-668 +- **Verdict:** Conditional (precondition: concurrent applicants reach the shared Flask instance) +- **Location:** `examples/chat-basic/app.py:15-62`, `examples/assistant-flask/app.py:14-19, 26-58` +- **Description:** Module-level globals (`chat_history`, `assistant_id`, `thread_id`) are shared across all requests, risking cross-applicant exposure of uploaded documents and thread context. +- **Recommendation:** Scope chat history, session state, and Assistants threads per authenticated user session (`flask.session`) and delete uploaded files from OpenAI once processed. -### [Low] F6: No audit trail of generated replies and no way to contest one +### [Low] F6: No structured audit trail of eligibility inputs, model outputs, or tool calls - **Severity:** Low -- **CWE:** unverified +- **CWE:** CWE-778 - **Verdict:** Confirmed -- **Location:** app.py -- **Description:** Auditability & recourse. Requests and replies are not logged, and there is no contact route for a disputed result. -- **Recommendation:** Log request ids and add a contact address for feedback. +- **Location:** `examples/assistant-flask/app.py:26-58, 147-182`, `examples/assistant-functions/functions.py:107-147` +- **Description:** Decisions and tool invocations are not logged durably; only two `print()` statements exist in the Assistants app. Without an audit trail, disputed eligibility outcomes cannot be reconstructed. +- **Recommendation:** Emit structured append-only audit logs recording timestamp, applicant/session ID, model version, prompt/response hashes, and tool-call arguments. ## Coverage Notes -Reviewed the README, the application entry point and the templates against all seven dimensions. No framework or internal AI policy is referenced in the repository. Confidence: moderate. +Reviewed all source, template, and documentation files in the repository (`README.md`, `LICENSE`, `requirements.txt`, `.gitignore`, and the four modules under `examples/`). No governance framework (NIST AI RMF or EU AI Act high-risk controls) is implemented despite the eligibility-gating use case. Confidence in the assessment is high. diff --git a/tests/fixtures/reports/responsible-ai-compliance-medium-with-high-finding.md b/tests/fixtures/reports/responsible-ai-compliance-medium-with-high-finding.md new file mode 100644 index 0000000..da79530 --- /dev/null +++ b/tests/fixtures/reports/responsible-ai-compliance-medium-with-high-finding.md @@ -0,0 +1,70 @@ +# Responsible AI Compliance Report + +## Summary +The target is an internal developer-support Q&A assistant built on the Flask chat and Assistants examples that answers staff questions about internal runbooks via OpenAI's hosted `gpt-3.5-turbo` models. It makes no decisions about people, eligibility, employment, or finances. However, a shared module-level session store in the Flask app creates a High-severity data-leakage finding if multiple staff members upload sensitive runbook attachments concurrently. Because the deployment is restricted to an internal VPN with no consequential decisions about individuals, the overall system risk rating is Medium rather than High. + +**Overall risk rating:** Medium + +## Findings Register + +| ID | Finding | Severity | CWE | Verdict | +|----|---------|----------|-----|---------| +| F1 | Shared global chat history and file store leaks internal attachments across staff sessions | High | CWE-668 | Conditional | +| F2 | No model card, intended-use statement, or known-limitations documentation | Medium | unverified | Confirmed | +| F3 | No audit trail of AI interactions, tool calls, or file uploads | Low | CWE-778 | Confirmed | +| F4 | No disclosure of third-party data processing or retention for user inputs and uploads | Low | unverified | Conditional | +| F5 | Minimal end-user AI disclosure (branding only, no limitations or accuracy notice) | Low | unverified | Confirmed | +| F6 | Autonomous tool execution (code interpreter, function calls) with no human checkpoint or allowlist guidance | Low | unverified | Latent | + +## Findings + +### [High] F1: Shared global chat history and file store leaks internal attachments across staff sessions +- **Severity:** High +- **CWE:** CWE-668 +- **Verdict:** Conditional (precondition: multiple staff members access the shared internal Flask instance concurrently) +- **Location:** `examples/chat-basic/app.py:15-62`, `examples/assistant-flask/app.py:14-19, 26-58, 142-193` +- **Description:** Module-level globals (`chat_history`, `assistant_id`, `thread_id`) are shared across all visitors. One engineer's uploaded incident logs or configuration files remain attached to the shared assistant and are exposed to subsequent users. +- **Recommendation:** Scope chat history and Assistants threads per authenticated user session (`flask.session` with a server-set `SECRET_KEY`) and attach uploaded files to the per-session thread rather than the shared assistant. + +### [Medium] F2: No model card, intended-use statement, or known-limitations documentation +- **Severity:** Medium +- **CWE:** unverified +- **Verdict:** Confirmed +- **Location:** `README.md` (repository-wide; no `MODEL_CARD.md`, `docs/`, or equivalent exists) +- **Description:** The README documents setup only and omits intended use, known hallucination risks on internal runbooks, and out-of-scope uses. +- **Recommendation:** Add a "Model and responsible use" section to `README.md` detailing intended internal Q&A use, non-goals, and limitations. + +### [Low] F3: No audit trail of AI interactions, tool calls, or file uploads +- **Severity:** Low +- **CWE:** CWE-778 +- **Verdict:** Confirmed +- **Location:** `examples/chat-basic/app.py:32-55`, `examples/assistant-flask/app.py:26-58, 147-182` +- **Description:** Prompts, completions, and file uploads are not logged durably; only ad-hoc `print()` calls exist. +- **Recommendation:** Introduce structured Python `logging` with timestamp, session ID, model, and file IDs to an append-only sink. + +### [Low] F4: No disclosure of third-party data processing or retention for user inputs and uploads +- **Severity:** Low +- **CWE:** unverified +- **Verdict:** Conditional (precondition: staff submit sensitive or personal data in prompts or attachments) +- **Location:** `examples/assistant-flask/app.py:38-51`, `examples/assistant-flask/templates/index.html:41-50`, `README.md` +- **Description:** User inputs and uploaded files are sent to OpenAI and persisted server-side without an explicit UI notice or full `client.files.delete(file_id)` cleanup. +- **Recommendation:** Add a third-party data-processing notice in the templates and README and delete OpenAI file objects on removal. + +### [Low] F5: Minimal end-user AI disclosure (branding only, no limitations or accuracy notice) +- **Severity:** Low +- **CWE:** unverified +- **Verdict:** Confirmed +- **Location:** `examples/chat-basic/templates/index.html:4, 11-17, 86`, `examples/assistant-flask/templates/index.html:4, 16-22, 303` +- **Description:** The UI lacks an explicit disclaimer that responses are AI-generated and may be inaccurate. +- **Recommendation:** Add a persistent one-line disclaimer under the header in both templates. + +### [Low] F6: Autonomous tool execution (code interpreter, function calls) with no human checkpoint or allowlist guidance +- **Severity:** Low +- **CWE:** unverified +- **Verdict:** Latent +- **Location:** `examples/assistant-flask/app.py:116-121`, `examples/assistant-functions/functions.py:45, 107-147` +- **Description:** `run_action` dispatches model-selected tools without schema validation or confirmation; shipped tools are harmless stubs. +- **Recommendation:** Validate model-supplied arguments with `pydantic` and require confirmation before executing any side-effecting tool. + +## Coverage Notes +Reviewed all source, template, and documentation files in the repository (`README.md`, `LICENSE`, `requirements.txt`, `.gitignore`, and the four modules under `examples/`). Confidence in the assessment is high. diff --git a/tests/fixtures/reports/responsible-ai-compliance-medium.md b/tests/fixtures/reports/responsible-ai-compliance-medium.md index 3655bfe..e8b733a 100644 --- a/tests/fixtures/reports/responsible-ai-compliance-medium.md +++ b/tests/fixtures/reports/responsible-ai-compliance-medium.md @@ -1,70 +1,70 @@ # Responsible AI Compliance Report ## Summary -The application screens support requests. A human review step exists but is applied inconsistently and the documentation omits known limitations. +The target is a customer-support triage assistant built on the Flask chat and Assistants examples that routes incoming user tickets and drafts replies via OpenAI's hosted `gpt-3.5-turbo` models. Staff are expected to review drafted replies before sending, but the review step is not enforced in code and tickets can be auto-dispatched when confidence thresholds are bypassed. While the system does not make final legal or financial determinations, inconsistent human oversight and missing documentation for support-staff adopters create moderate operational and data-governance risk. Overall risk is rated Medium. -**Overall risk rating:** Medium. +**Overall risk rating:** Medium ## Findings Register | ID | Finding | Severity | CWE | Verdict | |----|---------|----------|-----|---------| -| F1 | No model card or intended-use statement for the hosted model | Medium | unverified | Confirmed | -| F2 | No bias or fairness testing is described | Medium | unverified | Confirmed | -| F3 | Model output is shown to the user with no review step | Low | unverified | Confirmed | -| F4 | The UI does not say the reply is AI generated | Low | unverified | Confirmed | -| F5 | No record of what data reaches the model | Low | unverified | Confirmed | -| F6 | No audit trail of generated replies and no way to contest one | Low | unverified | Confirmed | +| F1 | Inconsistent human oversight on drafted support replies before dispatch | Medium | unverified | Confirmed | +| F2 | Shared global chat history and file store leaks one customer's ticket data across sessions | Medium | CWE-668 | Conditional | +| F3 | No model card, intended-use statement, or known-limitations documentation | Low | unverified | Confirmed | +| F4 | No audit trail of AI interactions, tool calls, or ticket attachments | Low | CWE-778 | Confirmed | +| F5 | No disclosure of third-party data processing or retention for ticket inputs and uploads | Low | unverified | Conditional | +| F6 | Minimal end-user AI disclosure (branding only, no limitations or accuracy notice) | Low | unverified | Confirmed | ## Findings -### [Medium] F1: No model card or intended-use statement for the hosted model +### [Medium] F1: Inconsistent human oversight on drafted support replies before dispatch - **Severity:** Medium - **CWE:** unverified - **Verdict:** Confirmed -- **Location:** README.md, examples/ -- **Description:** Documentation. The quickstart documents how to call the model but never states its intended use, known limitations or training-data provenance. -- **Recommendation:** Add a short model card section to the README covering intended use, limitations and data provenance. +- **Location:** `examples/assistant-functions/functions.py:107-147`, `examples/assistant-flask/app.py:116-121` +- **Description:** The triage workflow is documented as human-in-the-loop, but `run_action` dispatches drafted replies and ticket-routing updates straight from model output without requiring an explicit reviewer approval flag. A support agent can also trigger bulk dispatch without inspecting the underlying model rationale, leaving inaccurate or off-policy replies unchecked. +- **Recommendation:** Enforce an explicit human-approval state transition before any drafted reply is sent to a customer or ticket status is updated via `submit_tool_outputs`. Log the approving operator ID alongside the model suggestion. -### [Medium] F2: No bias or fairness testing is described +### [Medium] F2: Shared global chat history and file store leaks one customer's ticket data across sessions - **Severity:** Medium -- **CWE:** unverified -- **Verdict:** Confirmed -- **Location:** N/A -- **Description:** Bias & fairness. Nothing in the repository describes fairness testing or documents known failure modes for any subgroup. -- **Recommendation:** State explicitly that no fairness testing was done and why it is out of scope for a sample app. +- **CWE:** CWE-668 +- **Verdict:** Conditional (precondition: multiple support operators or customers access the same running Flask instance) +- **Location:** `examples/chat-basic/app.py:15-62`, `examples/assistant-flask/app.py:14-19, 26-58, 142-193` +- **Description:** Both Flask handlers store `chat_history`, `assistant_id`, and `thread_id` in module-level globals without per-user session scoping. In a support-triage deployment, uploaded customer attachments and ticket context from one session become visible to other concurrent operators and pollute subsequent retrieval runs. +- **Recommendation:** Scope conversation state and Assistants threads per authenticated operator session (`flask.session` with a server-set `SECRET_KEY`), and attach uploaded ticket files to the per-session thread rather than the shared assistant. -### [Low] F3: Model output is shown to the user with no review step +### [Low] F3: No model card, intended-use statement, or known-limitations documentation - **Severity:** Low - **CWE:** unverified - **Verdict:** Confirmed -- **Location:** app.py -- **Description:** Human oversight. The app returns generated text straight to the caller. No decision is made on a person's behalf, so no oversight is required for the stakes involved. -- **Recommendation:** Document that outputs are advisory and must be reviewed before use in any decision. +- **Location:** `README.md` (repository-wide; no `MODEL_CARD.md`, `docs/`, or equivalent exists) +- **Description:** The README covers installation and running only. It omits intended use (internal support-triage assistance), out-of-scope uses (autonomous customer decisions), known failure modes (hallucinated policy answers, prompt injection via uploaded ticket files), and any statement on fairness evaluation across customer segments. +- **Recommendation:** Add a "Model and responsible use" section to `README.md` naming the model, linking to OpenAI's documentation, defining intended and out-of-scope uses, and noting that no fairness evaluation was performed. -### [Low] F4: The UI does not say the reply is AI generated +### [Low] F4: No audit trail of AI interactions, tool calls, or ticket attachments - **Severity:** Low -- **CWE:** unverified +- **CWE:** CWE-778 - **Verdict:** Confirmed -- **Location:** templates/index.html -- **Description:** Transparency to end users. A reader of the page cannot tell the pet names are generated by a model. -- **Recommendation:** Add a one-line notice that the suggestions are AI generated. +- **Location:** `examples/chat-basic/app.py:32-55`, `examples/assistant-flask/app.py:26-58, 147-182` +- **Description:** Prompts, completions, run IDs, and tool invocations are not written to a durable audit log; only ad-hoc `print()` calls appear in the Assistants app. Without structured records, support leads cannot reconstruct why a triage decision or reply was generated. +- **Recommendation:** Replace `print()` calls with structured Python `logging` capturing timestamp, operator session ID, model, thread/run IDs, and tool arguments to an append-only log sink. -### [Low] F5: No record of what data reaches the model +### [Low] F5: No disclosure of third-party data processing or retention for ticket inputs and uploads - **Severity:** Low - **CWE:** unverified -- **Verdict:** Confirmed -- **Location:** app.py -- **Description:** Data provenance & consent. The prompt is built from user input only, but nothing documents that or how long inputs are retained by the provider. -- **Recommendation:** Document what is sent to the provider and link the provider's retention terms. +- **Verdict:** Conditional (precondition: customer-submitted ticket text or attachments contain personal data) +- **Location:** `examples/assistant-flask/app.py:38-51`, `examples/assistant-flask/templates/index.html:41-50`, `README.md` +- **Description:** Customer messages and uploaded files are transmitted to OpenAI and persisted server-side as assistant files and thread messages. Neither the UI nor the README discloses external transmission, retention, or how to delete the underlying OpenAI file object. +- **Recommendation:** Add a visible notice in the UI templates and README explaining third-party processing and retention, and call `client.files.delete(file_id)` when a ticket attachment is removed. -### [Low] F6: No audit trail of generated replies and no way to contest one +### [Low] F6: Minimal end-user AI disclosure (branding only, no limitations or accuracy notice) - **Severity:** Low - **CWE:** unverified - **Verdict:** Confirmed -- **Location:** app.py -- **Description:** Auditability & recourse. Requests and replies are not logged, and there is no contact route for a disputed result. -- **Recommendation:** Log request ids and add a contact address for feedback. +- **Location:** `examples/chat-basic/templates/index.html:4, 11-17, 86`, `examples/assistant-flask/templates/index.html:4, 16-22, 303` +- **Description:** The UI uses "Assistant" labels and page titles, but lacks an explicit statement that drafted responses are machine-generated and may be inaccurate. +- **Recommendation:** Add a persistent one-line accuracy and AI-origin disclaimer under the header in both templates. ## Coverage Notes -Reviewed the README, the application entry point and the templates against all seven dimensions. No framework or internal AI policy is referenced in the repository. Confidence: moderate. +Reviewed all source, template, and documentation files in the repository (`README.md`, `LICENSE`, `requirements.txt`, `.gitignore`, and the four application modules under `examples/`). Confidence in the assessment is high. diff --git a/tests/fixtures/reports/responsible-ai-compliance.md b/tests/fixtures/reports/responsible-ai-compliance.md index 3b2ef9e..061eb01 100644 --- a/tests/fixtures/reports/responsible-ai-compliance.md +++ b/tests/fixtures/reports/responsible-ai-compliance.md @@ -1,70 +1,70 @@ # Responsible AI Compliance Report ## Summary -The application is a sample that suggests pet names. It makes no decision about a person, so none of the seven dimensions is rated above Low. +The target, `https://github.com/openai/openai-quickstart-python`, is a set of four minimal demo applications (a streaming chat UI, an Assistants API Flask app with file upload and code interpreter, and two CLI assistant scripts) that forward user text to OpenAI's hosted `gpt-3.5-turbo` models and display the response. The system makes no eligibility, access, employment, legal, financial, biometric, or safety decisions about any person, so no high-stakes or rights-affecting use case exists. Governance artifacts (model card, limitations, bias testing, audit trail, framework reference) are entirely absent, which is expected for a quickstart but matters if the code is copied into production as-is; the most concrete concern is that all users of a running Flask instance share one global conversation and one shared file store. Given the stakes, every gap is rated Low. -**Overall risk rating:** Low. +**Overall risk rating:** Low ## Findings Register | ID | Finding | Severity | CWE | Verdict | |----|---------|----------|-----|---------| -| F1 | No model card or intended-use statement for the hosted model | Low | unverified | Confirmed | -| F2 | No bias or fairness testing is described | Low | unverified | Confirmed | -| F3 | Model output is shown to the user with no review step | Low | unverified | Confirmed | -| F4 | The UI does not say the reply is AI generated | Low | unverified | Confirmed | -| F5 | No record of what data reaches the model | Low | unverified | Confirmed | -| F6 | No audit trail of generated replies and no way to contest one | Low | unverified | Confirmed | +| F1 | Shared global chat history and file store leaks one user's data to all others | Low | CWE-668 | Conditional | +| F2 | No model card, intended-use statement, or known-limitations documentation | Low | unverified | Confirmed | +| F3 | No audit trail of AI interactions, tool calls, or file uploads | Low | CWE-778 | Confirmed | +| F4 | No disclosure of third-party data processing or retention for user inputs and uploads | Low | unverified | Conditional | +| F5 | Minimal end-user AI disclosure (branding only, no limitations or accuracy notice) | Low | unverified | Confirmed | +| F6 | Autonomous tool execution (code interpreter, function calls) with no human checkpoint or allowlist guidance | Low | unverified | Latent | ## Findings -### [Low] F1: No model card or intended-use statement for the hosted model +### [Low] F1: Shared global chat history and file store leaks one user's data to all others - **Severity:** Low -- **CWE:** unverified -- **Verdict:** Confirmed -- **Location:** README.md, examples/ -- **Description:** Documentation. The quickstart documents how to call the model but never states its intended use, known limitations or training-data provenance. -- **Recommendation:** Add a short model card section to the README covering intended use, limitations and data provenance. +- **CWE:** CWE-668 +- **Verdict:** Conditional (precondition: the Flask app is run where more than one person can reach it, e.g. bound to a non-loopback interface or deployed behind a shared URL) +- **Location:** `examples/chat-basic/app.py:15-62`, `examples/assistant-flask/app.py:14-19, 26-58, 142-193` +- **Description:** Both Flask examples keep conversation state in module-level globals (`chat_history`, `assistant_id`, `thread_id`) with no session, authentication, or per-user scoping. Every visitor sees every other visitor's prompts and model replies on page load, can append to the same OpenAI thread, and in the Assistants example can upload files to, list, and delete files from the single shared assistant. Any `/reset` call wipes everyone's conversation. From a responsible AI data-governance standpoint this means user inputs (which may include personal data) are exposed to unrelated parties and retrieval context is silently polluted across users. The README offers no warning that the samples are single-user demos. +- **Recommendation:** Scope state per user: store chat history and thread IDs in a Flask session (`flask.session` with a server-set `SECRET_KEY`) or a per-user record keyed by an authenticated identity, and create one Assistants thread per session rather than one per process. Attach uploaded files to the per-user thread/message rather than the shared assistant. Add a prominent README note that the examples are single-user, localhost-only demos and must not be exposed on a network without these changes. -### [Low] F2: No bias or fairness testing is described +### [Low] F2: No model card, intended-use statement, or known-limitations documentation - **Severity:** Low - **CWE:** unverified - **Verdict:** Confirmed -- **Location:** N/A -- **Description:** Bias & fairness. Nothing in the repository describes fairness testing or documents known failure modes for any subgroup. -- **Recommendation:** State explicitly that no fairness testing was done and why it is out of scope for a sample app. +- **Location:** `README.md` (repository-wide; no `MODEL_CARD.md`, `docs/`, or equivalent exists) +- **Description:** The README covers installation and running only. There is no description of which models are used and why, their intended and out-of-scope uses, known failure modes (hallucination, prompt injection via uploaded files, non-deterministic code-interpreter output), or a pointer to the upstream model's system card and usage policies. Training-data provenance is OpenAI's responsibility, but the repo does not even link to it. The models hard-coded in all four examples (`gpt-3.5-turbo`, `gpt-3.5-turbo-0125`) and the `client.beta.assistants.files` API surface are legacy, so the documentation is also stale about what will actually run. No bias or fairness testing exists, which is appropriate for a quickstart but should be stated explicitly so downstream adopters do not assume it was done. +- **Recommendation:** Add a short "Model and responsible use" section to `README.md` that: names the model(s) and links to OpenAI's model documentation and usage policies; states the intended use (local developer demo) and explicit non-goals (no production use, no decisions about people); lists known limitations (fabricated answers, injection via files, shared state per F1); and states that no fairness evaluation was performed. Parameterise the model name via an environment variable so documentation and code stay aligned. -### [Low] F3: Model output is shown to the user with no review step +### [Low] F3: No audit trail of AI interactions, tool calls, or file uploads - **Severity:** Low -- **CWE:** unverified +- **CWE:** CWE-778 - **Verdict:** Confirmed -- **Location:** app.py -- **Description:** Human oversight. The app returns generated text straight to the caller. No decision is made on a person's behalf, so no oversight is required for the stakes involved. -- **Recommendation:** Document that outputs are advisory and must be reviewed before use in any decision. +- **Location:** `examples/chat-basic/app.py:32-55`, `examples/assistant-flask/app.py:26-58, 147-182`, `examples/assistant-functions/functions.py:107-147` +- **Description:** No example logs prompts, completions, run IDs, tool invocations, or file upload/delete events in a durable or structured way. The only output is two debugging `print()` calls in the Assistants app (one of which dumps the full file list to stdout). The function-calling example executes model-selected tools (`run_action`) with no record of what was called or with what arguments. Without this, there is no way to reconstruct what the model said to a user, investigate a harmful or incorrect output, or offer recourse. Because no consequential decisions are made, this is a hygiene gap rather than a rights issue. +- **Recommendation:** Introduce Python `logging` with a structured record per request containing timestamp, session identifier, model, OpenAI run/thread/message IDs, tool name and arguments for function calls, and file IDs for upload/delete. Write to an append-only sink (file or log service) rather than stdout, and remove the ad-hoc `print()` calls. Document retention and who may read the logs. -### [Low] F4: The UI does not say the reply is AI generated +### [Low] F4: No disclosure of third-party data processing or retention for user inputs and uploads - **Severity:** Low - **CWE:** unverified -- **Verdict:** Confirmed -- **Location:** templates/index.html -- **Description:** Transparency to end users. A reader of the page cannot tell the pet names are generated by a model. -- **Recommendation:** Add a one-line notice that the suggestions are AI generated. +- **Verdict:** Conditional (precondition: a person other than the operator uses the app and submits personal or sensitive content) +- **Location:** `examples/assistant-flask/app.py:38-51`, `examples/assistant-flask/templates/index.html:41-50`, `README.md` +- **Description:** User messages and uploaded files (txt, pdf, images, csv) are transmitted to OpenAI and, in the Assistants example, persisted server-side as assistant files and thread messages that outlive the local process. The UI only says "Attach files to make them available to code interpreter"; nothing tells the user that content leaves the machine, is retained by a third party, or how to have it deleted (the delete button removes the assistant association but not necessarily the underlying file object). Nothing documents the licensing or consent basis for data placed into the retrieval/code-interpreter context. There is no training, fine-tuning, or RAG corpus in the repo, so provenance obligations are limited to this runtime data flow. +- **Recommendation:** Add a visible notice in both templates and the README stating that messages and files are sent to and stored by OpenAI under its API data-usage policy, with a link. In `upload_file`, document (or implement) full cleanup by calling `client.files.delete(file_id)` after detaching from the assistant, and expose a "delete my data" action. Advise users not to upload personal or confidential data in the demo. -### [Low] F5: No record of what data reaches the model +### [Low] F5: Minimal end-user AI disclosure (branding only, no limitations or accuracy notice) - **Severity:** Low - **CWE:** unverified - **Verdict:** Confirmed -- **Location:** app.py -- **Description:** Data provenance & consent. The prompt is built from user input only, but nothing documents that or how long inputs are retained by the provider. -- **Recommendation:** Document what is sent to the provider and link the provider's retention terms. +- **Location:** `examples/chat-basic/templates/index.html:4, 11-17, 86`, `examples/assistant-flask/templates/index.html:4, 16-22, 303` +- **Description:** Users can infer they are talking to an AI from the page titles ("OpenAI Chat", "OpenAI Assistant Chat"), the OpenAI logo, a "Demo" tag, and the "Assistant" role label. There is no explicit statement that responses are machine-generated, may be inaccurate, and should not be relied on for advice. The CLI examples print "Response:" with no framing at all. For a developer-facing quickstart this is adequate in practice, but the templates are the obvious copy-paste starting point for public-facing apps. +- **Recommendation:** Add a one-line persistent disclaimer under the header in both templates (for example, "Responses are generated by an AI model and may be inaccurate") and a matching line in the CLI startup output. Keep it in the templates so downstream copies inherit it. -### [Low] F6: No audit trail of generated replies and no way to contest one +### [Low] F6: Autonomous tool execution (code interpreter, function calls) with no human checkpoint or allowlist guidance - **Severity:** Low - **CWE:** unverified -- **Verdict:** Confirmed -- **Location:** app.py -- **Description:** Auditability & recourse. Requests and replies are not logged, and there is no contact route for a disputed result. -- **Recommendation:** Log request ids and add a contact address for feedback. +- **Verdict:** Latent (the shipped tools are harmless: OpenAI-sandboxed code interpreter and two hard-coded stub functions; becomes relevant only when a developer swaps in real side-effecting functions at the "Add your next tool here" marker) +- **Location:** `examples/assistant-flask/app.py:116-121`, `examples/assistant-functions/functions.py:45, 107-147` +- **Description:** The Assistants Flask app enables `code_interpreter` and instructs the model to "write and run code" on uploaded files, and the function-calling example dispatches whatever tool the model requests via `run_action` with arguments parsed straight from model output. There is no human-in-the-loop confirmation step, no argument validation, and no guidance in the code or README about which categories of action should require review before execution. As shipped, nothing irreversible can happen, so this is a design pattern concern rather than a live risk. +- **Recommendation:** Add a comment block at the "Add your next tool here" marker and a README paragraph stating that side-effecting tools (payments, email, data deletion, account changes) must gate on an explicit user confirmation before `submit_tool_outputs` is called, and must validate model-supplied arguments against a schema (e.g. with `pydantic`) rather than trusting `json.loads` output directly. Show a minimal confirm-prompt pattern in `run_action` so adopters copy the safe shape. ## Coverage Notes -Reviewed the README, the application entry point and the templates against all seven dimensions. No framework or internal AI policy is referenced in the repository. Confidence: moderate. +Reviewed all source, template, and documentation files in the repository: `README.md`, `LICENSE`, `requirements.txt`, `.gitignore`, and the four examples under `examples/` (both Flask `app.py` files and their `index.html` templates, `assistant-basic/assistant.py`, `assistant-functions/functions.py`). Static CSS and PNG assets were not examined. The `.env.example` file could not be read because a local policy hook blocks access to `.env*` paths; based on the README it is expected to contain only an `OPENAI_API_KEY` placeholder, which has no bearing on the governance findings. No Confluence URL was supplied, so no external documentation was consulted. No governance framework (NIST AI RMF, EU AI Act tier, internal policy) is referenced anywhere in the repo; because the system is a low-impact developer demo with no decisions about people, this absence was not raised as a separate finding. The codebase is small (roughly 600 lines) and was read in full, so confidence in the assessment is high. diff --git a/tests/test_cli_assessment.py b/tests/test_cli_assessment.py index 34bd99c..b092061 100644 --- a/tests/test_cli_assessment.py +++ b/tests/test_cli_assessment.py @@ -1,8 +1,7 @@ from __future__ import annotations -from typer.testing import CliRunner - from secfoo.cli import app +from typer.testing import CliRunner runner = CliRunner() @@ -26,7 +25,7 @@ def test_assessment_create_and_list(monkeypatch, tmp_path): assert result.exit_code == 0 assert "Created assessment 1" in result.stdout - result = runner.invoke(app, ["assessment", "list"]) + result = runner.invoke(app, ["assessment", "list"], env={"COLUMNS": "200"}) assert result.exit_code == 0 assert "APP-1" in result.stdout assert "myproject" in result.stdout @@ -43,7 +42,7 @@ def test_assessment_create_with_custom_name_overrides_auto_derived(monkeypatch, ) assert result.exit_code == 0 - result = runner.invoke(app, ["assessment", "list"]) + result = runner.invoke(app, ["assessment", "list"], env={"COLUMNS": "200"}) # Rich wraps/truncates long cell text, so check fragments rather than # the literal joined string. assert "Friendly" in result.stdout @@ -64,7 +63,7 @@ def test_assessment_create_accepts_public_github_url(monkeypatch, tmp_path): assert result.exit_code == 0 assert "Created assessment 1" in result.stdout - result = runner.invoke(app, ["assessment", "list"]) + result = runner.invoke(app, ["assessment", "list"], env={"COLUMNS": "200"}) # Rich truncates long cell text with an ellipsis in the CLI's compact # table width, so check a safe prefix rather than the literal string. assert "octocat/H" in result.stdout diff --git a/tests/test_responsible_ai_end_to_end.py b/tests/test_responsible_ai_end_to_end.py index 652b1f4..f5b823f 100644 --- a/tests/test_responsible_ai_end_to_end.py +++ b/tests/test_responsible_ai_end_to_end.py @@ -19,11 +19,10 @@ import pytest from fastapi.testclient import TestClient -from typer.testing import CliRunner - from secfoo.cli import app from secfoo.storage.repository import RunRepository from secfoo.web.app import create_app +from typer.testing import CliRunner FIXTURE_DIR = Path(__file__).parent / "fixtures" / "reports" SKILL_ID = "responsible-ai-compliance" @@ -33,6 +32,7 @@ "low": ("responsible-ai-compliance.md", "low-risk", "badge--success", (0, 0, 0, 6, 0)), "medium": ("responsible-ai-compliance-medium.md", "moderate", "badge--warning", (0, 0, 2, 4, 0)), "high": ("responsible-ai-compliance-high.md", "high-risk", "badge--error", (0, 2, 2, 2, 0)), + "critical": ("responsible-ai-compliance-critical.md", "high-risk", "badge--error", (1, 2, 2, 1, 0)), } cli_runner = CliRunner() @@ -85,7 +85,12 @@ def _show(assessment_id: int) -> str: def _stat(html: str, label: str) -> str: """The number printed on the stat card with this label.""" - match = re.search(rf'stat-card__value">\s*([^<\s]+)\s*\s*{re.escape(label)}<', html) + stripped = re.sub(r'
\s*([^<\s]+)\s*\s*\s*{re.escape(label)}\s*<', + stripped, + re.DOTALL, + ) assert match, f"no stat card labelled {label!r}" return match.group(1) @@ -139,16 +144,37 @@ def test_each_rating_gets_its_own_tier(fake_popen, target_dir): assert len(set(seen.values())) == 3 +def test_overall_rating_is_independent_of_worst_finding(fake_popen, target_dir): + """Tier must come from `**Overall risk rating:**`, not from the worst finding.""" + stdout = (FIXTURE_DIR / "responsible-ai-compliance-medium-with-high-finding.md").read_text(encoding="utf-8") + result = _run_skill(fake_popen, target_dir, returncode=0, stdout=stdout) + + assert result.exit_code == 0, result.output + [run] = json.loads(result.stdout)["runs"] + assert run["severity"] == {"critical": 0, "high": 1, "medium": 1, "low": 4, "info": 0} + + [assessment] = _all_assessments() + assert assessment.high_count == 1 + assert assessment.responsible_ai_risk == "moderate" + assert "Responsible AI: moderate (provisional)" in _show(assessment.id) + + def test_assessment_list_shows_the_auto_created_case_file_with_its_findings(fake_popen, target_dir): assert _run_skill(fake_popen, target_dir, tier="low").exit_code == 0 + unrated_target = target_dir / "unrated-app" + unrated_target.mkdir() + _create_assessment_for(unrated_target) # Wide enough that rich does not wrap the table cells. - result = cli_runner.invoke(app, ["assessment", "list"], env={"COLUMNS": "200"}) + result = cli_runner.invoke(app, ["assessment", "list"], env={"COLUMNS": "240"}) assert result.exit_code == 0, result.output flat = " ".join(result.stdout.split()) + assert "Responsible AI" in flat assert "openai-quickstart-python" in flat assert "0C 0H 0M 6L 0I" in flat + assert "low-risk (provisional)" in flat + assert re.search(r"unrated-app\s+│\s+internal\s+│\s+ready\s+│\s+-\s+│\s+-\s+│\s+0C 0H 0M 0L 0I\s+│\s+-", flat) # ---------- the dashboard on the same store ---------- @@ -171,17 +197,29 @@ def test_responsible_ai_page_shows_the_tier_badge_and_counts(fake_popen, target_ assert f'badge {badge_class}">{risk}<' in html assert 'badge badge--neutral">provisional<' in html assert _stat(html, "Assessments with a risk rating") == "1" - assert _stat(html, "High-risk") == ("1" if tier == "high" else "0") + assert _stat(html, "High-risk") == ("1" if risk == "high-risk" else "0") assert _stat(html, "Provisional") == "1" -def test_assessment_pages_show_the_tier_badge(client, low_rated_assessment): - detail = client.get(f"/assessments/{low_rated_assessment}").text +@pytest.mark.parametrize("tier", list(TIERS)) +def test_assessment_pages_show_the_tier_badge(fake_popen, target_dir, client, tier): + _, risk, badge_class, _ = TIERS[tier] + assert _run_skill(fake_popen, target_dir, tier=tier).exit_code == 0 + [assessment] = _all_assessments() + + detail = client.get(f"/assessments/{assessment.id}").text listing = client.get("/assessments").text + expected_badge = f'badge {badge_class}">{risk}<' + all_badges = { + 'badge badge--success">low-risk<', + 'badge badge--warning">moderate<', + 'badge badge--error">high-risk<', + } for html in (detail, listing): - assert 'badge--success">low-risk<' in html - assert "moderate" not in html + assert expected_badge in html + for other_badge in all_badges - {expected_badge}: + assert other_badge not in html def test_overview_counts_the_rated_assessment(client, low_rated_assessment): @@ -221,9 +259,20 @@ def test_cli_status_update_confirms_the_rating(low_rated_assessment): def test_reopening_a_completed_assessment_makes_the_rating_provisional_again(client, low_rated_assessment): - client.post("/assessments/bulk-status", data={"ids": [str(low_rated_assessment)], "new_status": "completed"}) - client.post("/assessments/bulk-status", data={"ids": [str(low_rated_assessment)], "new_status": "in_progress"}) + confirm_resp = client.post( + "/assessments/bulk-status", + data={"ids": [str(low_rated_assessment)], "new_status": "completed"}, + follow_redirects=False, + ) + assert confirm_resp.status_code == 303 + assert "Responsible AI: low-risk (confirmed)" in _show(low_rated_assessment) + reopen_resp = client.post( + "/assessments/bulk-status", + data={"ids": [str(low_rated_assessment)], "new_status": "in_progress"}, + follow_redirects=False, + ) + assert reopen_resp.status_code == 303 assert "Responsible AI: low-risk (provisional)" in _show(low_rated_assessment) @@ -254,6 +303,19 @@ def test_the_badge_follows_the_newest_successful_run(fake_popen, target_dir, fir assert assessment.responsible_ai_risk == expected +def test_the_badge_breaks_equal_timestamp_ties_in_favor_of_the_latest_run(fake_popen, target_dir, monkeypatch): + monkeypatch.setattr("secfoo.storage.repository._now", lambda: "2026-11-15T12:00:00+00:00") + assert _run_skill(fake_popen, target_dir, tier="low").exit_code == 0 + [assessment] = _all_assessments() + assert assessment.responsible_ai_risk == "low-risk" + + result = _run_skill(fake_popen, target_dir, tier="high", extra=["--assessment", str(assessment.id)]) + + assert result.exit_code == 0, result.output + [assessment] = _all_assessments() + assert assessment.responsible_ai_risk == "high-risk" + + def test_a_failed_newer_run_does_not_change_the_badge(fake_popen, target_dir): assert _run_skill(fake_popen, target_dir, tier="low").exit_code == 0 [assessment] = _all_assessments()