Add native security service workbench and verified assessment flows
Browse filesFiles changed (20)
- .env.exampleAdded+9
- .gitignoreAdded+11
- DEPENDENCY-ADVISORIES.jsonAdded+320
- PROVENANCE.mdAdded+15
- README.md+76-7
- SECURITY.mdAdded+38
- SERVICE.mdAdded+43
- VERIFICATION.mdAdded+37
- app.pyAdded+230
- deploy_hf.pyAdded+69
- engine.pyAdded+289
- gradio_app.pyAdded+273
- requirements-deploy.txtAdded+2
- requirements.txtAdded+59
- static/app.jsAdded+513
- static/index.htmlAdded+290
- static/style.cssAdded+843
- tests/test_backend.pyAdded+243
- tests/test_deploy.pyAdded+44
- tests/test_gradio.pyAdded+191
123456789# Examples only; export real random values in your shell or use Space Secrets.# APP_ACCESS_KEY must have at least 24 characters.# APP_SECRET_KEY must have at least 32 characters, different from the access key.APP_ACCESS_KEY=APP_SECRET_KEY=WORKSPACE_NAME=Security operationsDATA_DIR=./data# Set false ONLY for loopback HTTP development.COOKIE_SECURE=true1234567891011.env.env.*!.env.exampledata/.venv/__pycache__/*.pyc*.db*.db-**.sqlite*output/123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320{ "checked_on": "2026-10-31", "tool": "pip-audit 2.10.1", "packages_checked": 58, "records": [ { "package": "pillow", "version": "12.3.0", "advisory": "PYSEC-2026-4327", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "PYSEC-2026-4328", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "PYSEC-2026-4326", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "PYSEC-2026-4339", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "PYSEC-2026-4340", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "PYSEC-2026-4343", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "PYSEC-2026-4334", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "PYSEC-2026-4337", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "PYSEC-2026-4341", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "PYSEC-2026-4330", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "PYSEC-2026-4338", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "PYSEC-2026-4335", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "PYSEC-2026-4336", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "PYSEC-2026-4331", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "PYSEC-2026-4332", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "PYSEC-2026-4329", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "PYSEC-2026-4333", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "PYSEC-2026-4342", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "CVE-2026-112895", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "CVE-2026-112400", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "CVE-2026-112897", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "CVE-2026-112395", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "CVE-2026-112404", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "CVE-2026-112899", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "CVE-2026-112900", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "CVE-2026-112893", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "CVE-2026-112891", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "CVE-2026-112390", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "CVE-2026-112401", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "CVE-2026-112391", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "CVE-2026-112894", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "CVE-2026-112406", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "CVE-2026-112399", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "CVE-2026-112892", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "CVE-2026-112393", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "CVE-2026-96638", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "CVE-2026-96640", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "CVE-2026-96778", "fix_versions": [ "13.0.0" ] }, { "package": "pillow", "version": "12.3.0", "advisory": "GHSA-78g4-xqwv-q3g8", "fix_versions": [ "13.0.0" ] } ], "interpretation": "Presence confirmed by pinned dependency metadata. Text-only application has no image/file inputs or Pillow decoding calls. Runtime reachability of these advisories is unverified. Pillow13 is outside Gradio6.31 declared dependency bound; incompatible override was not applied."}123456789101112131415# Workflow provenance
The user explicitly invoked local Napolean and Napolean Security skills. This implementation expresses their commander/scope/evidence/challenge/adjudication concepts in original application code. Reading the skills did not activate upstream runtimes.
Napolean Security references AgriciDaniel/claude-cybersecurity, tanviet12/vbsec, agamm/claude-code-owasp, ghostsecurity/skills, goplussecurity/agentguard, codexstar69/bug-hunter, kenryu42/cc-safety-net, anthropics/defending-code-reference-harness, trailofbits/skills and cloudflare/security-audit-skill. None of their executables, rule sets or source files are bundled, copied or claimed to have run. Their licenses do not automatically apply to this original application. Future integrations require inspecting exact versions, licenses, permissions and data flow.
The new workspace had no existing repository to map; Graphify was not run. The preferred local Crawl4AI documentation fetch failed because its browser process could not launch. Official web retrieval was used instead.
Primary documentation consulted on 2026-10-31:- [Hugging Face Gradio Spaces](https://huggingface.co/docs/hub/spaces-sdks-gradio): native SDK and application entry-point configuration.- [Hugging Face Docker Spaces](https://huggingface.co/docs/hub/spaces-sdks-docker): consulted before user selected no Docker; Docker delivery was removed.- [Hugging Face Space management](https://huggingface.co/docs/huggingface_hub/guides/manage-spaces): repository creation, secrets and source upload.- [Hugging Face Spaces overview](https://huggingface.co/docs/hub/spaces-overview): visibility and account/compute constraints; verify current terms before provisioning.
No AI model is trained or used. Mission plans are deterministic original templates, and evidence candidates come from local Python rules. No unsupported claim of upstream scanner equivalence, production assurance or compliance is intended.1234534567898910111112141314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283---title: Napolean Cyber Commandemoji: 🐢colorFrom: bluecolorTo: purpleemoji: 🛡️colorFrom: graycolorTo: bluesdk: gradiosdk_version: 6.31.0python_version: '3.12'app_file: app.pyapp_file: gradio_app.pypython_version: 3.13pinned: falseshort_description: Enterprise security assessment workbench with five hat persp---
Check out the configuration reference at https://huggingface.co/docs/hub/spaces-config-reference# Napolean Cyber Command
A security assessment workbench for a managed business security service. Five analytical perspectives share one scope, one evidence ledger, and analyst review. This starter runs on a CPU, does not require a model API, and does not send assessment submissions to external services.
## What works
- Python snippet checks nominate risky execution, shell invocation and secret-like assignment candidates. This is bounded heuristic review, not whole-repository analysis.- Structured alert triage correlates repeated failed logins and nominates privilege-change and malware events for investigation.- Tabletop exercises use disclosed keyword routing for ransomware, supply-chain, identity/phishing, cloud and generic scenarios, producing role-specific missions and deliverables.- Red, blue, white, black and purple perspectives each receive a mission plan. These are analytical roles, not user access permissions or running autonomous agents.- Analysts record evidence notes and adjudicate candidates. Automatic checks never confirm a vulnerability.- Results and activity persist in SQLite; export JSON or Markdown and delete assessments. Raw submitted source/logs are not stored.
## Run locally
Python 3.13 or 3.14 is recommended. From this directory:
```shpython3 -m venv .venv.venv/bin/python -m pip install -r requirements.txt# Generate two DIFFERENT values with this command, then export them below:.venv/bin/python -c 'import secrets; print(secrets.token_urlsafe(48))'export APP_ACCESS_KEY='paste-first-random-value'export APP_SECRET_KEY='paste-second-random-value'export WORKSPACE_NAME='Your business security workspace'.venv/bin/python gradio_app.py```
Open the local URL printed by Gradio. Sign in as `analyst` using `APP_ACCESS_KEY`. Do not use the placeholder strings above as real secrets. The `.env.example` file is documentation, not automatically loaded. With missing or invalid keys, the native app displays setup instructions and exposes no assessment functionality.
The native Gradio app is mounted on FastAPI and served by Uvicorn with an outer same-origin request guard. The native Gradio interface supports all three workflows, five perspectives, analyst review, a saved register, copyable JSON/Markdown exports and confirmed deletion. No file uploads or cached downloadable reports are used. An alternative Flask browser interface remains in `static/` for local engineering evaluation; it is not mounted by the native Gradio Space.
## Run checks
```sh.venv/bin/python -m unittest discover -s tests -vnode --check static/app.js```
See [verification](VERIFICATION.md) for exact checks and known limits.
## Hugging Face project
The project uses the native [Gradio Spaces SDK](https://huggingface.co/docs/hub/spaces-sdks-gradio); no Docker is used. The private Space is [PabloRod11/napolean-cyber-command](https://huggingface.co/spaces/PabloRod11/napolean-cyber-command).
Before enabling assessments, set two DIFFERENT random Space Secrets in [Space settings](https://huggingface.co/spaces/PabloRod11/napolean-cyber-command/settings):
- `APP_ACCESS_KEY`: at least 24 characters, used for the shared `analyst` login.- `APP_SECRET_KEY`: at least 32 characters, used for internal signed sessions.
Set `WORKSPACE_NAME` as an optional variable. The Space remains locked without valid keys. Runtime secrets are never included in source uploads. Use the top-level app URL when browser iframe policies block login cookies. Keep the Space private and configure HTTPS through the hosting platform.
For a separate NEW private Gradio deployment:
```sh.venv/bin/python -m pip install -r requirements-deploy.txt.venv/bin/hf auth login.venv/bin/python deploy_hf.py --repo-id YOUR_ACCOUNT/ANOTHER_PROJECT_NAME```
The helper asks for application keys without echoing, creates a private repository, configures secrets, and uploads only allowlisted source. It refuses to reuse an existing repository. It does not request paid hardware. The existing Space was created through the authenticated browser, not through this helper. Upload success is not runtime verification. See the [official Space management guide](https://huggingface.co/docs/huggingface_hub/guides/manage-spaces).
**Storage:** local SQLite is disposable unless durable storage is separately configured and tested. Do not onboard customer records until backup, restore, retention, encryption and a supported durable database/storage design are in place. Do not assume object-storage mounts provide SQLite locking semantics. Confirm current account compute/storage terms before scaling.
## Service scope
This is a functional service prototype. Authentication uses one shared key per deployment; there is no individual identity, RBAC, SSO, customer self-service signup, subscription billing, SIEM ingestion, incident SLA, or compliance certification. Use a separate deployment and keys for each pilot customer. Never describe this version as a secure multi-tenant SaaS.
The project encodes Napolean coordination and Napolean Security's evidence lifecycle. It does not install or execute the skills' ten upstream scanners, activate runtime guards, train a model, or run real attacks. Black-hat perspective means attacker-perspective lab planning. Red-hat perspective means authorized adversary simulation planning. Runtime confirmation is a human attestation backed by review notes, not automated exploitation evidence.
Read [service offering](SERVICE.md), [security model](SECURITY.md), and [upstream provenance](PROVENANCE.md) before customer trials.1234567891011121314151617181920212223242526272829303132333435363738# Security model and operating limits
## Boundaries
One deployment is one customer workspace. The shared access key grants full access to that workspace, including review, export and deletion. Hat selections change analytical perspectives only. They do not grant additional privileges. No individual attribution or security separation exists between holders of the same key.
The API accepts bounded text/JSON, never executes submissions, and performs no target URL fetching or model requests. Python syntax trees and conservative patterns nominate candidates; human analysts must validate reachability and impact. The server stores assessment output and review notes, not raw submitted content. Names, scopes, actor identities and analyst notes can still be sensitive: data minimization is not an encryption guarantee.
## Native Gradio deployment
The Space launches `gradio_app.py` with Gradio's shared `analyst` login. The authenticated Gradio callbacks call the Flask application in-process; no Flask listener or Flask API is mounted publicly. Gradio is responsible for external session and callback authentication. An outer ASGI same-origin policy rejects foreign Origin requests before Gradio handles them. Native user sessions follow Gradio's lifecycle; the internal Flask one-hour lifetime is not a one-hour native login guarantee. The Flask cookie/CSRF controls described below protect the optional Flask interface and internal adapter, not a separate public Gradio API. Test external authentication after every framework upgrade.
With missing or invalid keys, only a locked setup page is built. No assessment callbacks or store are created in that state. Gradio analytics and public share tunnels are disabled; inputs use text components rather than file upload components. Export output is copyable text rather than cached downloadable files. Callback inputs can still exist in framework/process memory during a request; no claim of forensic memory erasure is made.
## Flask engine/API controls
Required application secrets, signed expiring sessions, HTTP-only strict cookies, CSRF validation on mutations, bounded login retries, request size and field limits, UUID records, parameterized SQLite access, restrictive browser headers, local static assets and output escaping. The optional Flask interface has an in-process login throttle that needs a single worker to be consistent. The native adapter uses fresh authenticated Flask clients internally; the Flask throttle is not a rate limiter for Gradio login. Add and test ingress rate limiting and identity management before a business launch.
Run behind HTTPS. Keep HTTPS and secure session settings enabled. Keep the Space private; use top-level navigation when embedded cookie policies interfere. Do not log secrets, source submissions or request bodies at a proxy. Rotate access/session keys when changing workspace membership; restart every process after changing keys. Signed sessions are not centrally revocable per person.
## Data lifecycle
Results and analyst activity live in DATA_DIR. Directory/file permissions and storage encryption must be managed by the operator. Deletion removes logical records from the active application database, not guaranteed forensic erasure of SQLite pages, snapshots, exported files or backups. Exports leave the application boundary. Define retention and export handling with each pilot customer.
Use a tested managed data store and backups before service launch; local Space storage is not a customer durability commitment. Never share one deployment across customers. No key vault, field encryption, tenant-aware data model, immutable audit log or SOC 2 assessment is included.
## Coverage and limitations
No whole-repository parser, dependency advisory scanner, credential validation, fuzzing, live exploit test, endpoint/agent tooling, malware execution, network reconnaissance or LLM runtime exists here. Code checks cover selected Python syntax only; alerts depend on the supplied schema and completeness. A zero-candidate result is limited coverage, never proof of security. Manual verdicts are analyst attestations and may be wrong.
Treat all input, imported evidence and mission plans as untrusted. Review scope and written authorization before any separate testing. No mode expands permission or authorizes changes to production. Legal/compliance decisions and customer-facing assurances require qualified review.
## Reporting
No public vulnerability reporting address has been configured. Establish a monitored private security contact and incident process before distributing the service to customers. Do not publish customer evidence or credentials in issue trackers.
## Dependency advisory gapThe native dependency lock contains Pillow12.3.0 through Gradio6.31.0. pip-audit reported39 advisory records with fixes13.0.0, outside Gradio's declared <13 bound. The application uses text-only components and does not call image decoders; exploit-path reachability has not been established. Do not treat this as resolved. See DEPENDENCY-ADVISORIES.json and VERIFICATION.md.12345678910111213141516171819202122232425262728293031323334353637383940414243# Turning the workbench into a business service
## Proposed first offer
An analyst-led security assurance pilot for businesses with a small engineering team and limited internal security capacity. Sell a scoped outcome, not an autonomous pentest or a promise that software is secure. This is a proposed commercial direction; no customer validation, market sizing or willingness-to-pay study has been completed.
A pilot combines a bounded Python code review, triage of a customer-provided structured alert sample, and a tabletop exercise. Customer and analyst agree assets, revision/time range, authorized activities, exclusions, evidence handling and escalation contacts. The delivered package contains the evidence ledger, unresolved coverage gaps, prioritized remediation recommendations and a follow-up validation plan.
## Five perspectives
| Perspective | Analyst service | Customer deliverable || --- | --- | --- || Red | Plan authorized adversary simulations around the agreed boundary | Test plan, prerequisites, stop conditions || Blue | Review selected alerts and response readiness | Triage queue, detection gaps, response actions || White | Validate nominated code concerns and remediation | Evidence-backed findings and retest notes || Black | Model attacker incentives and plausible paths inside a lab scope | Threat scenarios and assumptions to challenge || Purple | Pair attack hypotheses with detection and remediation validation | Joint exercise plan and coverage backlog |
In this version the application creates mission plans and bounded heuristic candidates. Qualified analysts perform the actual assessment, challenge and decisions. Do not market all five perspectives as five running AI agents.
## Suggested engagement sequence
1. Intake: confirm decision-maker, assets, authorization, critical business processes, scope, allowed data, contact and exclusions.2. Baseline: collect minimal approved snippets and normalized event samples, record revision/time window, and run the appropriate workbench flow.3. Validation: a reviewer challenges each candidate; record evidence, prerequisites, mitigations and unresolved claims.4. Readout: explain demonstrated impact separately from severity hypotheses; agree remediation owners and deadlines outside the prototype.5. Follow-up: re-evaluate remediated code/controls and document residual risk; never convert missing evidence into a passing result.
## Packaging hypotheses
Start with a fixed-scope paid pilot, then test recurring analyst review and exercise facilitation with interested customers. Pricing should reflect measured analyst hours, scope, evidence complexity, retest effort, support and infrastructure. No prices or financial forecasts are asserted here. Validate demand with customer interviews and a small number of signed pilot agreements before building subscription billing.
Potential tiers to validate: a one-time baseline assessment, recurring review and detection tuning, and a dedicated customer deployment with contracted analyst availability. Do not promise 24/7 monitoring or response times before staffing and operational testing support them.
## Pilot readiness
The present code is suitable for synthetic data demos and engineering evaluation. Before accepting real customer data, establish written scope/terms and data processing arrangements; review hosting location/subprocessors and access; test backups and restores; configure secure storage and retention; provide an individual identity and audit design appropriate to the engagement; run independent application security testing.
Before shared SaaS: build and verify tenant isolation, per-user SSO/RBAC, immutable audit events, secret management, job isolation, rate and cost controls, observability and incident handling. Add billing only after the service and commercial terms are validated. Any model integration needs explicit customer data-disclosure controls and a provider evaluation; none is enabled here.
## Measures for pilots
Track time to reviewed report, candidates confirmed/rejected/unresolved by an analyst, analyst minutes per assessment, remediation completion agreed with the customer, retest results, customer usefulness feedback and repeat engagement intent. Do not use candidate count as an effectiveness score or a security certification.12345678910111213141516171819202122232425262728293031323334353637# Verification and security evidence
Checked on 2026-10-31. New workspace; no source Git revision existed locally. Remote source is a new private native Gradio Space for PabloRod11. Docker was removed at the user's request.
## Functional checks
The unittest suite exercises the actual Flask engine and native Gradio callbacks: all three workflows, all five perspectives, scoped authorization, authenticated results and exports, CSRF on the optional Flask API, limits/malformed input, redaction, analyst decisions, persistence, exports, deletion, missing-key setup lock and stale-selection protection. Exact final test counts are recorded below after the integrated run.
A real in-app browser exercised the optional Flask interface: login, Python assessment, JSON alert assessment, exercise, five mission plans, evidence review, saved verdict, assessment search and persistence after reload. The native Gradio interface was also exercised through login and creation of a five-role ransomware tabletop; input was cleared after creation and the saved report showed the selected category and five distinct deliverables. Synthetic fixtures only were used. Screenshots were inspected. Multiple desktop/mobile viewport sizes were not independently automated; the original browser inspector/CLI was unavailable.
JavaScript syntax check: `node --check static/app.js`. Taste app-mode lint: zero failures, 16 advisory warnings for terminal typography, small labels, role numbering and a dialog shadow. Monospace/labels and numbering are deliberate terminal-design choices; system fonts avoid remote font requests. This is not a full accessibility certification.
## Security ledger
| ID | Root cause / boundary | Evidence and prerequisites | Verdict / confidence | Remediation status || --- | --- | --- | --- | --- || NS-001 | Quoted multiword credentials and bearer values survived metadata redaction in engine.py | Reviewer created a scope containing a quoted multiword password; value returned and followed persistence/export path. Customer must put a secret into metadata/notes. | confirmed-runtime, medium impact, high confidence | Fixed with full quoted-value and bearer sanitization; regression covers metadata, notes, database and exports. Redaction remains best-effort. || NS-002 | Gradio6.31 hosted-origin CORS policy allowed foreign origins with credentialed callbacks | Reviewer used an authenticated hosted-host TestClient; foreign Origin could read /config and indexed callback assessment output. Requires victim cookies and hosting gate to permit cross-origin requests; not reproduced against HF browser deployment. | confirmed-runtime in local hosted-host model, high potential impact, high confidence within model | Explicit same-origin ASGI guard added to actual launch path with read/login/mutation regression coverage. See final check below. || NS-003 | Native Gradio dependency bound selects Pillow12.3.0 with advisory matches | pip-audit2.10.1 queried pinned package versions; 39 advisory records for Pillow, fixes13.0.0 outside Gradio6.31 declared <13 bound. Multiple records may describe related issues. | confirmed-static package presence; runtime exposure unresolved | Text-only components, no image processing code. No incompatible override applied. Full minimal advisory list is in DEPENDENCY-ADVISORIES.json. Re-evaluate a compatible Gradio/Pillow release before business launch. || NS-004 | Optional Flask throttle depends on proxy remote_addr | Source inspection only; shared reverse proxy addresses may cause shared 5-minute login lockouts. | unresolved deployment behavior | Flask is not mounted in native Space. Test ingress identity/rate limiting before exposing optional Flask interface. |
The independent reviewer also ran 12 concurrent analyst updates across four threads: all returned200 and all12 activity events were retained. API updates use SQLite transactions. This is a bounded concurrency check, not a load or durability guarantee.
## Coverage limits
No live customer target, external exploitation, malware execution, model evaluation, whole-repository audit or ten upstream scanner integration ran. No security certification or independent third-party penetration test is implied. Gradio has an authenticated global upload endpoint despite no upload components; the launch limits file sizes to1KB and blocks DATA_DIR from file serving. Raw input transient memory and browser/framework behavior are not forensic erasure guarantees.
Local dependencies were tested on Python3.14. Native Gradio produces upstream unclosed-event-loop ResourceWarnings while building Blocks in tests; no failures were hidden. Remote runtime configuration, host-level access controls, long-lived sessions, backups and storage persistence require separate validation. Individual identity/RBAC, managed durable storage, ingress rate limits and incident operations remain launch work.
## Final integrated result
- Full suite: `python -m unittest discover -s tests -v` — **31 tests passed**, 5.975 seconds on the final integrated run.- `node --check static/app.js` — passed.- `pip check` — no broken requirements.- Same-origin middleware tests exercise the actual FastAPI app passed to Uvicorn by native main; foreign hosted origins, null/malformed origins, login, config, indexed callbacks and preflights are rejected403; valid same-origin and absent-Origin navigation are allowed.- Native dependency audit:58 pinned packages checked;39 advisory records in Pillow12.3.0, runtime exposure unresolved. Not a clean dependency result.- Remote source upload and hosted setup state are verified separately below. Application keys must be entered by the owner through Space Secrets before customer operations become available.123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230"""Single-workspace service. Configure keys before starting the application factory."""
from contextlib import closing, contextmanagerfrom datetime import timedeltaimport hmacimport jsonimport osfrom pathlib import Pathimport secretsimport sqlite3import threadingimport time
from flask import Flask, jsonify, request, session, send_from_directoryfrom werkzeug.exceptions import HTTPException
from engine import VERDICTS, analyze, bounded_text, markdown_export, now, redact
def create_app(config=None): app = Flask(__name__, static_folder='static', static_url_path='/static') app.config.from_mapping( APP_ACCESS_KEY=os.environ.get('APP_ACCESS_KEY', ''), SECRET_KEY=os.environ.get('APP_SECRET_KEY', ''), DATA_DIR=os.environ.get('DATA_DIR', './data'), WORKSPACE_NAME=os.environ.get('WORKSPACE_NAME', 'Enterprise workspace'), SESSION_COOKIE_NAME='cyber_command_session', SESSION_COOKIE_HTTPONLY=True, SESSION_COOKIE_SAMESITE='Strict', SESSION_COOKIE_SECURE=os.environ.get('COOKIE_SECURE', 'true').lower() != 'false', PERMANENT_SESSION_LIFETIME=timedelta(hours=1), MAX_CONTENT_LENGTH=280000, ) if config: app.config.update(config) access_key = app.config['APP_ACCESS_KEY'] secret_key = app.config['SECRET_KEY'] if not isinstance(access_key, str) or len(access_key) < 24 or not isinstance(secret_key, (str, bytes)) or len(secret_key) < 32: raise ValueError('Set APP_ACCESS_KEY (24+ characters) and APP_SECRET_KEY (32+ characters).') secret_bytes = secret_key.encode() if isinstance(secret_key, str) else secret_key if hmac.compare_digest(access_key.encode(), secret_bytes): raise ValueError('Access and session signing keys must be distinct.') data_dir = Path(app.config['DATA_DIR']) data_dir.mkdir(parents=True, exist_ok=True, mode=0o700) database = data_dir / 'assessments.sqlite3' with closing(sqlite3.connect(database)) as initial, initial: initial.execute('PRAGMA secure_delete=ON') initial.execute('CREATE TABLE IF NOT EXISTS assessments (id TEXT PRIMARY KEY, body TEXT NOT NULL)') database.chmod(0o600) failures = {} throttle_lock = threading.Lock()
@contextmanager def connection(): with closing(sqlite3.connect(database, timeout=10)) as db, db: db.execute('PRAGMA secure_delete=ON') yield db
def authenticated(): if session.get('authenticated') is True and isinstance(session.get('expires_at'), (int, float)) and session['expires_at'] > time.time(): return True session.clear() return False
def session_response(): active = authenticated() return jsonify(authenticated=active, csrf_token=session.get('csrf_token') if active else None, workspace=app.config['WORKSPACE_NAME'])
def body(): value = request.get_json(silent=True) if not isinstance(value, dict): raise ValueError('A JSON object is required.') return value
def load(assessment_id, db=None): if db is None: with connection() as owned: row = owned.execute('SELECT body FROM assessments WHERE id=?', (assessment_id,)).fetchone() else: row = db.execute('SELECT body FROM assessments WHERE id=?', (assessment_id,)).fetchone() if row is None: from flask import abort abort(404, description='Assessment not found.') return json.loads(row[0])
@app.before_request def protect(): if request.path.startswith('/api/') and request.path not in ('/api/session', '/api/login'): if not authenticated(): return jsonify(error='Authentication required.'), 401 if request.method not in ('GET', 'HEAD', 'OPTIONS'): supplied = request.headers.get('X-CSRF-Token', '') expected = session.get('csrf_token', '') if not supplied or not expected or not hmac.compare_digest(supplied.encode(), expected.encode()): return jsonify(error='Invalid CSRF token.'), 403
@app.after_request def headers(response): response.headers['Content-Security-Policy'] = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'" response.headers['X-Content-Type-Options'] = 'nosniff' response.headers['Referrer-Policy'] = 'no-referrer' response.headers['Permissions-Policy'] = 'camera=(), microphone=(), geolocation=()' response.headers['Cache-Control'] = 'no-store' if request.is_secure: response.headers['Strict-Transport-Security'] = 'max-age=31536000' return response
@app.errorhandler(ValueError) def bad_value(error): return jsonify(error=str(error)), 400
@app.errorhandler(HTTPException) def http_error(error): return jsonify(error=error.description), error.code
@app.errorhandler(Exception) def unexpected(error): # Do not log request data or exception messages that might contain customer input. app.logger.error('Request failed (%s).', type(error).__name__) return jsonify(error='Request could not be completed.'), 500
@app.get('/') def index(): return send_from_directory(app.static_folder, 'index.html')
@app.get('/api/session') def get_session(): return session_response()
@app.post('/api/login') def login(): payload = body() provided = payload.get('access_key') if not isinstance(provided, str) or len(provided) > 1000: raise ValueError('Access key must be a string of at most 1000 characters.') current = time.monotonic() address = request.remote_addr or 'unknown' with throttle_lock: # Bounded in-memory throttle; deployment intentionally runs a single worker. for key in list(failures): if current - failures[key][0] >= 300: del failures[key] started, attempts = failures.get(address, (current, 0)) if attempts >= 5: return jsonify(error='Too many login attempts. Try again in five minutes.'), 429 if not hmac.compare_digest(provided.encode(), access_key.encode()): if len(failures) >= 4096 and address not in failures: return jsonify(error='Login capacity exceeded. Try again later.'), 429 failures[address] = (started, attempts + 1) return jsonify(error='Invalid access key.'), 401 failures.pop(address, None) session.clear() session.permanent = True session.update(authenticated=True, csrf_token=secrets.token_urlsafe(32), expires_at=time.time() + 3600) return session_response()
@app.post('/api/logout') def logout(): session.clear() return jsonify(ok=True)
@app.get('/api/assessments') def list_assessments(): with connection() as db: rows = db.execute('SELECT body FROM assessments ORDER BY rowid DESC').fetchall() summaries = [] for row in rows: assessment = json.loads(row[0]) summary = {field: assessment[field] for field in ('id', 'name', 'workflow', 'scope', 'created_at', 'roles')} summary.update(finding_count=len(assessment['findings']), unresolved_count=sum(f['verdict'] == 'unresolved' for f in assessment['findings'])) summaries.append(summary) return jsonify(assessments=summaries)
@app.post('/api/assessments') def create_assessment(): assessment = analyze(body()) with connection() as db: db.execute('INSERT INTO assessments (id, body) VALUES (?, ?)', (assessment['id'], json.dumps(assessment))) return jsonify(assessment=assessment), 201
@app.get('/api/assessments/<assessment_id>') def get_assessment(assessment_id): return jsonify(assessment=load(assessment_id))
@app.delete('/api/assessments/<assessment_id>') def delete_assessment(assessment_id): with connection() as db: cursor = db.execute('DELETE FROM assessments WHERE id=?', (assessment_id,)) if not cursor.rowcount: from flask import abort abort(404, description='Assessment not found.') return jsonify(ok=True)
@app.patch('/api/assessments/<assessment_id>/findings/<finding_id>') def review_finding(assessment_id, finding_id): payload = body() verdict = payload.get('verdict') if verdict not in VERDICTS: raise ValueError('Unsupported finding verdict.') minimum = 20 if verdict in ('confirmed-static', 'confirmed-runtime', 'rejected') else 1 note = redact(bounded_text(payload.get('note'), 'Evidence note', 4000, minimum)) with connection() as db: db.execute('BEGIN IMMEDIATE') assessment = load(assessment_id, db) target = next((f for f in assessment['findings'] if f['id'] == finding_id), None) if target is None: from flask import abort abort(404, description='Finding not found.') target.update(verdict=verdict, review_note=note) assessment['activity'].append(dict(at=now(), action='finding_reviewed', note=f'{finding_id}: {verdict}. Analyst evidence: {note}')) assessment['summary'] = f'{len(assessment["findings"])} candidate(s); {sum(f["verdict"] == "unresolved" for f in assessment["findings"])} unresolved. Verdicts reflect shared-workspace analyst decisions, not automated proof.' db.execute('UPDATE assessments SET body=? WHERE id=?', (json.dumps(assessment), assessment_id)) return jsonify(assessment=assessment)
@app.get('/api/assessments/<assessment_id>/export') def export_assessment(assessment_id): assessment = load(assessment_id) fmt = request.args.get('format', 'json') if fmt == 'json': response = app.response_class(json.dumps(assessment, indent=2), mimetype='application/json') extension = 'json' elif fmt == 'markdown': response = app.response_class(markdown_export(assessment), mimetype='text/markdown') extension = 'md' else: raise ValueError('Export format must be json or markdown.') response.headers['Content-Disposition'] = f'attachment; filename="assessment-{assessment["id"]}.{extension}"' return response
return app123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869"""Opt-in source publication to a NEW, private Hugging Face Gradio Space."""import argparsefrom getpass import getpassimport osfrom pathlib import Pathimport reimport sys
SOURCE_FILES = ( 'README.md', 'requirements.txt', 'gradio_app.py', 'app.py', 'engine.py', 'static/index.html', 'static/app.js', 'static/style.css', 'SECURITY.md', 'SERVICE.md', 'PROVENANCE.md', 'VERIFICATION.md', 'DEPENDENCY-ADVISORIES.json',)
def validate_repo_id(repo_id): if not isinstance(repo_id, str) or not re.fullmatch(r'[A-Za-z0-9][A-Za-z0-9_-]{0,95}/[A-Za-z0-9][A-Za-z0-9_-]{0,95}', repo_id): raise ValueError('Use an account-or-organization/project-name repository ID.')
def collect_files(root): root = Path(root).resolve() for name in SOURCE_FILES: path = root / name if not path.is_file() or path.is_symlink() or any(p.is_symlink() for p in path.parents if p != root and root in p.parents): raise ValueError(f'Missing or symlinked source: {name}') if not path.resolve().is_relative_to(root) or path.stat().st_size > 2_000_000: raise ValueError(f'Invalid source path or oversized file: {name}') return list(SOURCE_FILES)
def deploy(api, repo_id, root, access_key, secret_key): validate_repo_id(repo_id) if len(access_key) < 24 or len(secret_key) < 32 or access_key == secret_key: raise ValueError('Use different random access and session keys (24 and 32 characters minimum).') root = Path(root).resolve() files = collect_files(root) api.create_repo(repo_id=repo_id, repo_type='space', space_sdk='gradio', private=True, exist_ok=False) api.add_space_secret(repo_id=repo_id, key='APP_ACCESS_KEY', value=access_key) api.add_space_secret(repo_id=repo_id, key='APP_SECRET_KEY', value=secret_key) api.upload_folder(repo_id=repo_id, repo_type='space', folder_path=str(root), allow_patterns=files, commit_message='Add Napolean Cyber Command service prototype')
def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument('--repo-id', required=True, help='Your Hugging Face account/project-name') args = parser.parse_args() validate_repo_id(args.repo_id) try: from huggingface_hub import HfApi, get_token except ImportError: parser.error('Install requirements-deploy.txt in your virtual environment first.') token = get_token() if not token: parser.error('Authenticate locally with hf auth login or supply HF_TOKEN in the environment.') access = os.environ.get('APP_ACCESS_KEY') or getpass('Workspace access key (24+ random characters): ') secret = os.environ.get('APP_SECRET_KEY') or getpass('Different session signing key (32+ random characters): ') try: deploy(HfApi(token=token), args.repo_id, Path(__file__).resolve().parent, access, secret) except ValueError as exc: parser.error(str(exc)) except Exception as exc: # Provider error strings may contain credentials, URLs or request metadata. print(f'Deployment incomplete ({type(exc).__name__}). Inspect the private Space in your account; ' 'a partial repository may exist. Nothing was automatically deleted.', file=sys.stderr) return 1 print(f'Source uploaded to https://huggingface.co/spaces/{args.repo_id}') print('Check the Space build and runtime before sharing. Local SQLite storage is not a durability guarantee.') return 0
if __name__ == '__main__': raise SystemExit(main())123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289"""Local, bounded candidate nomination. Never executes submissions or calls a model."""
import astfrom collections import Counterfrom datetime import datetime, timezoneimport jsonimport reimport uuid
ROLES = ('red', 'blue', 'white', 'black', 'purple')WORKFLOWS = ('code', 'alerts', 'exercise')VERDICTS = ('unresolved', 'confirmed-static', 'confirmed-runtime', 'rejected')
def now(): return datetime.now(timezone.utc).isoformat()
def bounded_text(value, label, maximum, minimum=1): if not isinstance(value, str) or len(value) > maximum or len(value.strip()) < minimum: raise ValueError(f'{label} must contain {minimum}–{maximum} characters.') if any(ord(char) < 32 and char not in '\n\r\t' for char in value): raise ValueError(f'{label} contains unsupported control characters.') return value.strip()
SECRET_NAME = re.compile(r'(?:secret|password|passwd|token|api_?key|access_?key|private_?key)', re.I)SECRET_INLINE = re.compile(r'''(?i)(\b[\w.-]*(?:secret|password|passwd|token|api_?key|access_?key|private_?key)[\w.-]*\s*[=:]\s*)(?:"[^"\r\n]*"|'[^'\r\n]*'|[^\s,;\r\n]+)''')BEARER = re.compile(r'(?i)(\b(?:authorization\s*:\s*)?bearer\s+)[A-Za-z0-9._~+/=-]+')KNOWN_TOKEN = re.compile(r'\b(?:hf_[A-Za-z0-9]{16,}|sk-[A-Za-z0-9_-]{16,}|AKIA[A-Z0-9]{16})\b')
def redact(value): """Best-effort metadata sanitization; generated evidence never includes raw lines.""" value = SECRET_INLINE.sub(r'\1[REDACTED]', value) return KNOWN_TOKEN.sub('[REDACTED]', BEARER.sub(r'\1[REDACTED]', value))
def finding(title, severity, location, root_cause, evidence, remediation, prerequisites): return dict(id=uuid.uuid4().hex, title=title, severity=severity, confidence='low', verdict='unresolved', location=location, root_cause=root_cause, input_to_impact='Analyst must trace input control, reachable code, and business impact.', prerequisites=prerequisites, mitigations='Not evaluated. Inspect validation, authorization, isolation and compensating controls.', evidence=evidence, remediation=remediation, review_note='')
def code_candidates(content): try: tree = ast.parse(content) except (SyntaxError, ValueError, RecursionError, MemoryError) as exc: raise ValueError('Code must be a syntactically valid, bounded Python snippet.') from exc candidates = [] # Resolve simple import aliases for subprocess APIs; do not infer arbitrary data flow. modules = {'subprocess'} shell_functions = set() for node in ast.walk(tree): if isinstance(node, ast.Import): modules.update(alias.asname or alias.name for alias in node.names if alias.name == 'subprocess') if isinstance(node, ast.ImportFrom) and node.module == 'subprocess': shell_functions.update(alias.asname or alias.name for alias in node.names) for node in ast.walk(tree): location = f'Python snippet line {getattr(node, "lineno", "?")}' if isinstance(node, ast.Call): if isinstance(node.func, ast.Name) and node.func.id in ('eval', 'exec'): candidates.append(finding('Dynamic Python evaluation', 'high', location, 'A call to a dynamic evaluation builtin may accept untrusted code.', 'AST identified an eval/exec call; arguments and source text omitted.', 'Replace dynamic evaluation with explicit parsing or a bounded dispatch table.', 'Untrusted input must reach this call; builtin shadowing and reachability are unverified.')) subprocess_call = (isinstance(node.func, ast.Attribute) and isinstance(node.func.value, ast.Name) and node.func.value.id in modules and node.func.attr in ('run', 'call', 'Popen', 'check_call', 'check_output', 'getoutput', 'getstatusoutput')) imported_call = isinstance(node.func, ast.Name) and node.func.id in shell_functions shell_true = any(k.arg == 'shell' and isinstance(k.value, ast.Constant) and k.value.value is True for k in node.keywords) if (subprocess_call or imported_call) and shell_true: candidates.append(finding('Shell-enabled process invocation', 'high', location, 'A subprocess call explicitly enables shell interpretation.', 'AST identified a subprocess invocation with shell=True; command omitted.', 'Use shell=False with an argument list; constrain executable and arguments.', 'An attacker must influence the command or environment; source-to-sink flow is unverified.')) if isinstance(node, (ast.Assign, ast.AnnAssign)): targets = node.targets if isinstance(node, ast.Assign) else [node.target] names = [child.id for target in targets for child in ast.walk(target) if isinstance(child, ast.Name)] value = node.value if any(SECRET_NAME.search(name) for name in names) and isinstance(value, ast.Constant) and isinstance(value.value, str) and len(value.value) >= 8: candidates.append(finding('Possible embedded credential', 'medium', location, 'A secret-like variable is assigned a string literal.', 'Secret-like literal assignment detected. Value and variable name [REDACTED].', 'Verify whether this is an active secret; if so revoke it and use a secret store.', 'Literal may be a placeholder; validity and exposure have not been checked.')) if len(candidates) >= 100: break return candidates, [ 'Limited Python AST nomination: direct eval/exec, simple subprocess imports with literal shell=True, and secret-like literal assignments.', 'Maximum 100 candidates; overflow is not analyzed. No execution, dependency audit, cross-file analysis, taint tracking, alias rebinding or exploit validation.', 'No matches do not establish security; inspect authentication, authorization, tenant isolation and framework-specific behavior separately.' ]
def alert_candidates(content): try: events = json.loads(content) except (ValueError, RecursionError) as exc: raise ValueError('Alerts must be a valid JSON array.') from exc if not isinstance(events, list) or len(events) > 500: raise ValueError('Alerts must be a JSON array of at most 500 objects.') for event in events: if not isinstance(event, dict) or set(event) - {'event', 'actor', 'source_ip'}: raise ValueError('Alert objects accept only event, actor and source_ip fields.') bounded_text(event.get('event'), 'Alert event', 100) for field in ('actor', 'source_ip'): if field in event: bounded_text(event[field], f'Alert {field}', 200) counts = Counter((event.get('actor', '(unknown)'), event.get('source_ip', '(unknown)')) for event in events if event['event'] == 'login_failed') candidates = [] for (actor, source), count in counts.items(): if count >= 5: candidates.append(finding('Repeated failed logins', 'medium', 'Submitted alert batch', 'Five or more login_failed events share actor and source identifiers in this batch.', f'{count} matching failures; actor/source identifiers omitted to minimize retained log data.', 'Check the time window, account ownership and MFA; correlate with successful logins.', 'Batch events may be duplicated or span unrelated periods; no timestamp or identity validation.')) for label, title in (('privilege_change', 'Privilege change requires review'), ('malware_detected', 'Malware alert requires validation')): count = sum(event['event'] == label for event in events) if count: candidates.append(finding(title, 'high' if label == 'malware_detected' else 'medium', 'Submitted alert batch', 'An event label calls for human security triage.', f'{count} {label} event(s); raw log and identity values omitted.', 'Validate the sensor evidence, establish business context and follow the incident response runbook.', 'Event labels are untrusted reports; authenticity, approval and actual compromise are unverified.')) skipped = sum(event['event'] not in ('login_failed', 'privilege_change', 'malware_detected') for event in events) return candidates, ['Limited batch correlation of login_failed, privilege_change and malware_detected labels.', f'{skipped} event(s) skipped because their labels are not supported by these local rules.', 'No live telemetry, event authenticity checks, timestamp analysis, deduplication or malware analysis.', 'Raw logs and actor/source identifiers are not retained; collect corroborating evidence in your controlled incident system.']
ROLE_PLANS = { 'red': ('Adversary simulation', 'Evaluate scoped attack hypotheses against approved assets.', ['Confirm asset ownership, written scope, stop conditions and test window.', 'Describe plausible attack paths and required access; use only isolated fixtures.', 'Challenge each hypothesis against existing controls and submit evidence to the commander.'], 'A scoped simulation plan with prerequisites, control checks and evidence requests.'), 'blue': ('Defense and incident triage', 'Identify defensive evidence and proportionate response actions.', ['Establish baseline telemetry, asset criticality and incident ownership.', 'Correlate candidate indicators with independent evidence and document competing explanations.', 'Propose containment and detection changes for human approval; submit gaps for adjudication.'], 'A triage checklist, proposed detections and response decision record.'), 'white': ('Independent application review', 'Validate source-level candidates and document remediation.', ['Trace inputs through authentication, authorization and trust boundaries.', 'Attempt to refute each candidate using validation, reachability and compensating controls.', 'Record a verdict with evidence and a scoped regression test before declaring a fix.'], 'An evidence-backed review ledger and remediation checklist.'), 'black': ('Attacker-perspective laboratory', 'Model attacker objectives in an isolated, authorized training environment.', ['Use fictional targets or explicitly owned laboratory assets; document prohibited actions.', 'Describe attacker incentives, prerequisites and boundary crossings without performing exploitation.', 'Challenge the modeled path against mitigations; give defenders evidence requirements for adjudication.'], 'A bounded threat model and tabletop scenario with defensive checkpoints.'), 'purple': ('Joint control validation', 'Connect adversary hypotheses to observable detection and response outcomes.', ['Pair each hypothesis with a defensive owner and expected telemetry.', 'Define an isolated exercise, measurable success criteria and benign evidence fixtures.', 'Compare expected and observed signals; challenge attribution and adjudicate coverage gaps jointly.'], 'A joint exercise plan and detection-coverage improvement backlog.'),}
SCENARIOS = { 'ransomware': { 'keywords': ('ransomware', 'encrypt', 'extortion'), 'red': ('Model a lab-only path from a fictional foothold to payroll encryption; define stop conditions before any simulation.', 'Ransomware attack-path worksheet and approved lab boundaries.'), 'blue': ('Walk through endpoint isolation, incident declaration, backup integrity checks and restoration priorities without changing live systems.', 'Ransomware triage and recovery decision checklist.'), 'white': ('Review least privilege, backup separation and restore evidence; challenge whether encryption paths remain reachable.', 'Backup-control and privilege review with requested evidence.'), 'black': ('Model extortion incentives, access prerequisites and data exposure using fictional documents only.', 'Fictional extortion threat model with prevention checkpoints.'), 'purple': ('Pair each modeled encryption stage with endpoint telemetry and a recovery exercise acceptance criterion.', 'Ransomware detection matrix and timed restore exercise plan.'), }, 'supply-chain': { 'keywords': ('supply-chain', 'supply chain', 'third-party', 'dependency', 'package', 'vendor'), 'red': ('Model how a fictional compromised package could cross a build-to-release boundary without introducing malicious code.', 'Supply-chain attack-path worksheet for an isolated fixture.'), 'blue': ('Identify build logs, artifact provenance and release owners needed to corroborate a package-compromise report.', 'Package incident triage and release containment checklist.'), 'white': ('Review dependency pinning, artifact signatures, build permissions and reproducibility evidence.', 'Dependency and build integrity review checklist.'), 'black': ('Describe a fictional supplier adversary objective and required trust relationships; use no real poisoned packages.', 'Supplier threat model and trust-boundary inventory.'), 'purple': ('Map a benign dependency-change fixture to build alerts, release gates and response owners.', 'Supply-chain control exercise with observable release gates.'), }, 'identity/phishing': { 'keywords': ('phishing', 'identity', 'identities', 'credential', 'password', 'mfa', 'login'), 'red': ('Model a fictional credential-capture-to-account-access path; use dummy identities and no messages to real users.', 'Authorized identity simulation outline with dummy-account boundaries.'), 'blue': ('Identify authentication logs, MFA events and session revocation decisions needed for an account-takeover tabletop.', 'Identity incident triage and session containment checklist.'), 'white': ('Review MFA enrollment, recovery flows, session expiry and privilege approval evidence.', 'Identity-control review and recovery-flow evidence requests.'), 'black': ('Describe attacker incentives and prerequisites for a fictional account takeover without creating lures or collecting credentials.', 'Fictional account-takeover threat model.'), 'purple': ('Map a benign failed-login fixture and dummy privilege change to detections and account recovery criteria.', 'Identity detection matrix and recovery exercise plan.'), }, 'cloud': { 'keywords': ('cloud', 'aws', 'azure', 'gcp', 'bucket', 'kubernetes', 'iam'), 'red': ('Model an isolated cloud trust-boundary crossing using a fictional role and test resource; prohibit production changes.', 'Cloud role-path worksheet and test-resource scope.'), 'blue': ('Identify cloud audit logs, role-session provenance and resource ownership before proposing containment.', 'Cloud alert triage and role-containment decision checklist.'), 'white': ('Review IAM policies, public exposure, secret access and tenant boundaries using supplied policy evidence.', 'Cloud policy and isolation review checklist.'), 'black': ('Model fictional cloud-role abuse incentives and prerequisites without obtaining credentials or touching live resources.', 'Cloud trust-boundary threat model.'), 'purple': ('Pair a benign test-role action with audit events, alert ownership and a rollback acceptance criterion.', 'Cloud control exercise with audit-log expectations.'), }, 'generic': { 'keywords': (), 'red': ('Select one fictional business asset and model a scoped adversary hypothesis with explicit prerequisites.', 'Generic adversary hypothesis and laboratory scope worksheet.'), 'blue': ('Establish incident owners, business-critical assets and evidence collection priorities for the tabletop.', 'Business incident triage and escalation worksheet.'), 'white': ('Inventory trust boundaries, approvals and compensating controls that an analyst must validate.', 'Business control evidence checklist.'), 'black': ('Describe a fictional adversary objective and resource constraints using only approved tabletop facts.', 'Fictional business threat model.'), 'purple': ('Connect one tabletop hypothesis to a detection owner, expected evidence and measurable response target.', 'Joint tabletop control validation worksheet.'), },}
def scenario_category(content): """Keyword routing only; first matching category wins in the documented order.""" lowered = content.casefold() for category, details in SCENARIOS.items(): if any(re.search(r'\b' + re.escape(keyword) + r'\w*\b', lowered) for keyword in details['keywords']): return category return 'generic'
def analyze(payload): name = bounded_text(payload.get('name'), 'Name', 120) scope = bounded_text(payload.get('scope'), 'Scope', 2000) content = bounded_text(payload.get('content'), 'Content', 64000) workflow = payload.get('workflow') if workflow not in WORKFLOWS: raise ValueError('Choose code, alerts or exercise.') if payload.get('authorization') is not True: raise ValueError('Explicit scope authorization is required.') roles = payload.get('roles') if not isinstance(roles, list) or not 1 <= len(roles) <= 5 or any(not isinstance(r, str) or r not in ROLES for r in roles) or len(set(roles)) != len(roles): raise ValueError('Choose one to five distinct supported roles.') category = None if workflow == 'code': findings, coverage = code_candidates(content) elif workflow == 'alerts': findings, coverage = alert_candidates(content) else: category = scenario_category(content) findings, coverage = [], [f'Tabletop keyword routing selected category: {category}. Only this category is retained; raw scenario prose is discarded.', 'First matching keyword category wins: ransomware, supply-chain, identity/phishing, cloud; otherwise generic. This is not semantic or model analysis.', 'No vulnerability findings, live tests or control validation are produced.'] missions = [] for role in roles: title, objective, steps, deliverable = ROLE_PLANS[role] if workflow == 'exercise': scenario_step, deliverable = SCENARIOS[category][role] steps = [scenario_step] + steps elif workflow == 'code': steps = [f'Review the {len(findings)} unresolved ledger candidate(s); inspect the referenced snippet lines in your controlled source system and trace input reachability.'] + steps else: steps = ['Corroborate the alert ledger against original sensor records in your controlled system; establish timestamps, duplicates, actor ownership and approved changes before assigning impact.'] + steps missions.append(dict(role=role, title=title, objective=f'{objective} Workflow: {workflow}.', steps=steps, deliverable=deliverable, limitations=['Planning guidance only; requires a qualified analyst and separate approval for any live action.', 'No role-specific executable agents, scanners or upstream security tools are running.'])) return dict(id=uuid.uuid4().hex, name=redact(name), workflow=workflow, scope=redact(scope), created_at=now(), roles=roles, findings=findings, missions=missions, scenario_category=category, summary=f'{len(findings)} unresolved candidate(s) from limited local checks. Human validation is required; this is not a security certification.', coverage=coverage, activity=[dict(at=now(), action='created', note='Scope authorization attested; bounded local analysis completed. Raw submission discarded.')])
def markdown_export(assessment): # Escape markup and heading/list injection in user-authored fields. def safe(value): text = str(value).replace('&', '&').replace('<', '<').replace('>', '>') return re.sub(r'([\\`*_{}\[\]()#+.!|>~-])', r'\\\1', text).replace('\n', ' ') lines = ['# Napolean Cyber Command assessment', '', f'Name: {safe(assessment["name"])}', f'Scope: {safe(assessment["scope"])}', f'Workflow: {assessment["workflow"]}', f'Created: {assessment["created_at"]}', '', safe(assessment['summary']), '', '## Evidence ledger'] if assessment.get('scenario_category'): lines.insert(6, f'Scenario category: {assessment["scenario_category"]}') for item in assessment['findings']: lines += ['', f'### {safe(item["title"])}'] for field in ('severity', 'confidence', 'verdict', 'location', 'root_cause', 'input_to_impact', 'prerequisites', 'mitigations', 'evidence', 'remediation', 'review_note'): lines.append(f'{field.replace("_", " ").title()}: {safe(item[field])}') lines += ['', '## Missions'] for mission in assessment['missions']: lines += ['', f'### {mission["role"].title()}: {safe(mission["title"])}', safe(mission['objective'])] lines += [f'- {safe(step)}' for step in mission['steps']] lines += [f'Deliverable: {safe(mission["deliverable"])}'] lines += [f'Limitation: {safe(limitation)}' for limitation in mission['limitations']] lines += ['', '## Coverage'] + [f'- {safe(item)}' for item in assessment['coverage']] lines += ['', '## Activity'] + [f'- {safe(item["at"])} {safe(item["action"])}: {safe(item["note"])}' for item in assessment['activity']] return '\n'.join(lines) + '\n'123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273"""Native Hugging Face Gradio entry point; Flask stays an in-process service only."""
import osfrom pathlib import Pathfrom urllib.parse import quote, urlsplit
# Set before importing Gradio; never retain submitted source in browser run history.os.environ['GRADIO_ANALYTICS_ENABLED'] = 'False'os.environ['GRADIO_RUN_HISTORY'] = 'False'
import gradio as grfrom fastapi import FastAPIfrom starlette.middleware import Middlewarefrom starlette.responses import JSONResponseimport uvicorn
from app import create_appfrom engine import ROLES, VERDICTS
class SameOriginMiddleware: """Reject cross-origin requests before Gradio's hosted CORS implementation."""
def __init__(self, app): self.app = app
@staticmethod def valid_origin(scope): origins = [value for name, value in scope['headers'] if name.lower() == b'origin'] if not origins: return True # First-party navigation and non-browser clients omit Origin. hosts = [value for name, value in scope['headers'] if name.lower() == b'host'] if len(origins) != 1 or len(hosts) != 1: return False try: raw_origin, raw_host = origins[0].decode('ascii'), hosts[0].decode('ascii') if any(char.isspace() for char in raw_origin + raw_host): return False origin, host = urlsplit(raw_origin), urlsplit('//' + raw_host) if origin.scheme not in ('http', 'https') or not origin.hostname or not host.hostname: return False if origin.username is not None or origin.password is not None or host.username is not None or host.password is not None: return False if origin.path or origin.query or origin.fragment or host.path or host.query or host.fragment: return False # TLS terminates at the Hugging Face proxy, so scope['scheme'] may be HTTP. # Hosted service origins must be HTTPS; HTTP is allowed only on loopback. loopback = host.hostname.lower() in ('localhost', '127.0.0.1', '::1') expected_scheme = scope.get('scheme', 'http') if loopback else 'https' default_port = 443 if expected_scheme == 'https' else 80 return (origin.scheme == expected_scheme and origin.hostname.lower() == host.hostname.lower() and (origin.port or default_port) == (host.port or default_port)) except (ValueError, UnicodeError): return False
async def __call__(self, scope, receive, send): if scope['type'] in ('http', 'websocket') and not self.valid_origin(scope): if scope['type'] == 'websocket': await send({'type': 'websocket.close', 'code': 1008}) else: await JSONResponse({'error': 'Cross-origin requests are not allowed.'}, status_code=403)(scope, receive, send) return await self.app(scope, receive, send)
class WorkspaceService: """Preserve the existing authenticated API boundary without exposing a Flask server."""
def __init__(self, app): self._app = app
def _request(self, method, path, payload=None, query=None): with self._app.test_client() as client: options = {'base_url': 'https://internal.invalid'} login = client.post('/api/login', json={'access_key': self._app.config['APP_ACCESS_KEY']}, **options) if login.status_code != 200: raise ValueError('Internal workspace authentication failed.') response = client.open(path, method=method, json=payload, query_string=query, headers={'X-CSRF-Token': login.json['csrf_token']}, **options) if response.status_code >= 400: raise ValueError((response.get_json(silent=True) or {}).get('error', 'Workspace request failed.')) if path.endswith('/export'): return response.get_data(as_text=True) return response.get_json()
def list_assessments(self): return self._request('GET', '/api/assessments')['assessments']
def create(self, payload): return self._request('POST', '/api/assessments', payload)['assessment']
def get(self, assessment_id): return self._request('GET', '/api/assessments/' + quote(str(assessment_id), safe=''))['assessment']
def review(self, assessment_id, finding_id, verdict, note): path = '/api/assessments/' + quote(str(assessment_id), safe='') + '/findings/' + quote(str(finding_id), safe='') return self._request('PATCH', path, {'verdict': verdict, 'note': note})['assessment']
def delete(self, assessment_id): return self._request('DELETE', '/api/assessments/' + quote(str(assessment_id), safe=''))
def export(self, assessment_id, fmt): return self._request('GET', '/api/assessments/' + quote(str(assessment_id), safe='') + '/export', query={'format': fmt})
def create_service(config=None): return WorkspaceService(create_app(config))
def mission_report(assessment): lines = [assessment['summary'], '', 'COVERAGE'] + assessment['coverage'] for mission in assessment['missions']: lines += ['', f'{mission["role"].upper()}: {mission["title"]}', mission['objective']] lines += [f'{index}. {step}' for index, step in enumerate(mission['steps'], 1)] lines += ['Deliverable: ' + mission['deliverable']] lines += ['Limitation: ' + text for text in mission['limitations']] return '\n'.join(lines)
def build_ui(service=None): with gr.Blocks(analytics_enabled=False, title='Napolean Cyber Command') as ui: gr.Markdown('# Napolean Cyber Command\nEnterprise security evidence and tabletop workbench') if service is None: gr.Markdown('## Workspace locked: setup required\n' 'Add **APP_ACCESS_KEY** (at least 24 characters) and **APP_SECRET_KEY** ' '(at least 32 characters) as distinct private Hugging Face Space Secrets, then restart. ' 'Use username **analyst** and APP_ACCESS_KEY at login. ' 'No customer data operations are available until configuration is valid. ' 'Choose a durable DATA_DIR before storing business records.') else: gr.Markdown('One isolated customer workspace per deployment. Local heuristic candidates require human validation. ' 'The five perspectives are planning roles. No live scanning, exploitation or model inference runs. ' 'Raw submissions are discarded after analysis; results and analyst notes are retained. ' 'Keep secrets out of metadata and notes: redaction is best-effort.') with gr.Row(): with gr.Column(): name = gr.Textbox(label='Assessment name', max_length=120) workflow = gr.Radio([('Python code review', 'code'), ('Structured alert triage', 'alerts'), ('Training exercise', 'exercise')], value='code', label='Workflow') scope = gr.Textbox(label='Authorized scope', lines=2, max_length=2000, placeholder='Owned assets, purpose, permitted activity and boundaries') roles = gr.CheckboxGroup(list(ROLES), value=list(ROLES), label='Security perspectives', info='Red: adversary simulation · Blue: defense · White: review · Black: attacker-perspective lab · Purple: joint validation') content = gr.Textbox(label='Source, alerts or scenario', lines=10, max_length=64000, placeholder='Python snippet; JSON alert array with event/actor/source_ip fields; or tabletop scenario prose') authority = gr.Checkbox(label='I am authorized to assess the stated scope.', value=False) create_button = gr.Button('Create assessment', variant='primary') with gr.Column(): status = gr.Textbox(label='Workspace status', value='Reload assessments to view retained results.', interactive=False) reload_button = gr.Button('Reload assessments') selection = gr.Dropdown(label='Saved assessment', choices=[], interactive=True) load_button = gr.Button('Open selected assessment') missions = gr.Textbox(label='Missions and coverage', lines=16, interactive=False, buttons=['copy']) report = gr.JSON(label='Evidence ledger and assessment report', value={}) with gr.Row(): finding = gr.Dropdown(label='Finding to review', choices=[], interactive=True) verdict = gr.Dropdown(list(VERDICTS), value='unresolved', label='Analyst verdict', interactive=True) note = gr.Textbox(label='Evidence note', lines=3, max_length=4000, info='Confirmations and rejections require at least 20 characters describing supporting evidence. Verdicts are analyst assertions.') review_button = gr.Button('Save analyst decision') with gr.Row(): export_format = gr.Radio(['json', 'markdown'], value='json', label='Export format') export_button = gr.Button('Prepare copyable export') export_text = gr.Textbox(label='Export text', lines=10, interactive=False, buttons=['copy']) delete_confirm = gr.Checkbox(label='I confirm deletion of the selected assessment and its retained ledger.', value=False) delete_button = gr.Button('Delete selected assessment', variant='stop')
def choices(selected=None): assessments = service.list_assessments() return gr.Dropdown(choices=[(f'{a["name"]} · {a["workflow"]} · {a["finding_count"]} candidates', a['id']) for a in assessments], value=selected), f'{len(assessments)} retained assessment(s).'
def view(assessment): findings = assessment['findings'] return assessment, mission_report(assessment), gr.Dropdown( choices=[(f'{f["severity"]} · {f["title"]} · {f["verdict"]}', f['id']) for f in findings], value=findings[0]['id'] if findings else None)
def guarded(callback): def run(*values): try: return callback(*values) except ValueError as error: raise gr.Error(str(error)) from None return run
def create_assessment(title, mode, authorized_scope, perspectives, submission, attested): assessment = service.create(dict(name=title, workflow=mode, scope=authorized_scope, roles=perspectives, content=submission, authorization=attested)) selected, message = choices(assessment['id']) return selected, message, *view(assessment), '', '', False
def open_assessment(assessment_id): if not assessment_id: return {}, '', gr.Dropdown(choices=[], value=None), '', '', False return *view(service.get(assessment_id)), '', '', False
def reload_assessments(): selected, message = choices() return selected, message, *open_assessment(None)
def review_assessment(assessment_id, finding_id, chosen_verdict, evidence_note): if not assessment_id or not finding_id: raise ValueError('Open an assessment and select a finding first.') assessment = service.review(assessment_id, finding_id, chosen_verdict, evidence_note) return *view(assessment), 'Analyst decision saved.', '', ''
def export_assessment(assessment_id, fmt): if not assessment_id: raise ValueError('Select a saved assessment first.') return service.export(assessment_id, fmt)
def delete_assessment(assessment_id, confirmed): if not assessment_id or confirmed is not True: raise ValueError('Select an assessment and confirm deletion first.') service.delete(assessment_id) selected, message = choices() return selected, message, {}, '', gr.Dropdown(choices=[], value=None), '', '', False
event_options = dict(queue=False, api_visibility='private') reload_button.click(guarded(reload_assessments), outputs=[selection, status, report, missions, finding, note, export_text, delete_confirm], **event_options) create_button.click(guarded(create_assessment), inputs=[name, workflow, scope, roles, content, authority], outputs=[selection, status, report, missions, finding, content, export_text, delete_confirm], **event_options) load_button.click(guarded(open_assessment), inputs=[selection], outputs=[report, missions, finding, note, export_text, delete_confirm], **event_options) review_button.click(guarded(review_assessment), inputs=[selection, finding, verdict, note], outputs=[report, missions, finding, status, export_text, note], **event_options) export_button.click(guarded(export_assessment), inputs=[selection, export_format], outputs=[export_text], **event_options) delete_button.click(guarded(delete_assessment), inputs=[selection, delete_confirm], outputs=[selection, status, report, missions, finding, note, export_text, delete_confirm], **event_options) selection.input(guarded(open_assessment), inputs=[selection], outputs=[report, missions, finding, note, export_text, delete_confirm], **event_options) ui.enable_queue = False ui.run_history = False return ui
def build_application(config=None): try: service = create_service(config) except ValueError: return build_ui() return build_ui(service)
def create_native_app(): try: service = create_service() except ValueError: service = None ui = build_ui(service) data_dir = str(Path(os.environ.get('DATA_DIR', './data')).resolve()) parent = FastAPI(middleware=[Middleware(SameOriginMiddleware)], docs_url=None, redoc_url=None, openapi_url=None) return gr.mount_gradio_app(parent, ui, path='/', server_name='0.0.0.0' if os.environ.get('SPACE_ID') else '127.0.0.1', server_port=7860, auth=('analyst', os.environ['APP_ACCESS_KEY']) if service else None, run_history=False, footer_links=[], show_error=False, allowed_paths=[], blocked_paths=[data_dir], max_file_size='1kb', enable_monitoring=False, mcp_server=False, app_kwargs={'docs_url': None, 'redoc_url': None, 'openapi_url': None}, theme=gr.themes.Base(font=['Arial', 'sans-serif'], font_mono=['Courier New', 'monospace']))
def main(): app = create_native_app() uvicorn.run(app, host='0.0.0.0' if os.environ.get('SPACE_ID') else '127.0.0.1', port=7860, access_log=False)
if __name__ == '__main__': main()12# Optional helper for new native Gradio deployments.huggingface_hub==2.4.01234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859# Native Gradio + local assessment engine; resolved on Python 3.14.annotated-doc==0.0.5annotated-types==0.8.0anyio==4.15.1audioop-lts==0.2.2blinker==1.9.0brotli==1.2.1certifi==2026.10.23click==8.5.0fastapi==0.162.0filelock==4.2.5Flask==3.1.3fsspec==2026.9.0gradio==6.31.0gradio_client==2.7.2groovy==0.1.2h11==0.16.0hf-gradio==0.4.1hf-xet==1.8.0httpcore==1.0.9httpcore2==2.16.0httpx==0.28.1httpx2==2.16.0huggingface_hub==2.4.0idna==3.20itsdangerous==2.2.0Jinja2==3.1.6markdown-it-py==4.2.0MarkupSafe==3.0.4mdurl==0.1.2numpy==2.5.4opentelemetry-api==1.45.2orjson==3.13.0packaging==26.3pandas==3.1.0pillow==12.3.0pydantic==2.14.2pydantic_core==2.50.2pydub==0.25.1Pygments==2.21.0python-dateutil==3.0.0python-multipart==0.0.33pytz==2026.6PyYAML==6.0.3rich==15.0.0safehttpx==0.1.7semantic-version==2.10.0shellingham==1.5.4six==1.17.0starlette==1.10.0tomlkit==0.14.0tqdm==4.70.1truststore==0.10.5typer==0.27.3typing_extensions==4.16.0typing-inspection==0.4.4tzdata==2026.6uvicorn==0.54.0Werkzeug==3.1.9123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513'use strict';const $ = (selector, root = document) => root.querySelector(selector);const state = { csrf: null, assessments: [], assessment: null, finding: null, tab: 'ledger'};const roles = [ ['red', '01', 'Red hat', 'Test assumptions', 'Authorized adversary perspective.'], ['blue', '02', 'Blue hat', 'Strengthen defense', 'Triage signals and plan response.'], ['white', '03', 'White hat', 'Validate evidence', 'Review causes and remediation.'], ['black', '04', 'Black hat', 'Think like an attacker', 'Bounded threat modeling only.'], ['purple', '05', 'Purple hat', 'Close the loop', 'Connect scenarios to detection.'] ];const workflows = { code: 'Code review', alerts: 'Alert triage', exercise: 'Team exercise'};function el(tag, text, cls) { const node = document.createElement(tag); if (text !== undefined) node.textContent = String(text); if (cls) node.className = cls; return node;}function append(parent, ...children) { children.filter(Boolean).forEach(child => parent.append(child)); return parent;}function button(text, fn, cls = '') { const node = el('button', text, cls); node.type = 'button'; node.addEventListener('click', fn); return node;}function notify(message, error = false) { const n = $('#notice'); n.textContent = message; n.className = `visible${error ? ' error' : ''}`; clearTimeout(notify.timer); notify.timer = setTimeout(() => { n.className = ''; }, error ? 9000 : 4500);}function expired() { state.csrf = null; state.assessments = []; state.assessment = null; $('#view').replaceChildren(); document.querySelectorAll('dialog[open]').forEach(d => d.close()); $('#create-form').reset(); $('#content').value = ''; $('#review-note').value = ''; $('#finding-body').replaceChildren(); state.finding = null; $('#shell').hidden = true; $('#login').hidden = false; $('#access-key').focus();}async function api(path, options = {}) { const headers = { ...(options.body ? { 'Content-Type': 'application/json' } : {}), ...(options.method && options.method !== 'GET' && state.csrf ? { 'X-CSRF-Token': state.csrf } : {}), ...options.headers }; const response = await fetch(path, { credentials: 'same-origin', ...options, headers }); const body = await response.json().catch(() => ({ error: 'The server returned an unreadable response.' })); if (!response.ok) { if (response.status === 401 && path !== '/api/login') expired(); throw new Error(body.error || `Request failed (${response.status}).`); } return body;}function formError(form, message) { const inline = form.querySelector('.error-inline'); if (!inline) { notify(message, true); return; } inline.textContent = message; inline.hidden = false; inline.tabIndex = -1; inline.focus();}
async function busy(form, fn) { const inline = form.querySelector('.error-inline'); if (inline) { inline.hidden = true; inline.textContent = ''; } const buttons = [...form.querySelectorAll('button')]; buttons.forEach(b => b.disabled = true); form.setAttribute('aria-busy', 'true'); try { await fn(); } catch (error) { if (inline && !form.closest('[hidden]') && (!form.closest('dialog') || form.closest('dialog').open)) { inline.textContent = error.message; inline.hidden = false; inline.tabIndex = -1; inline.focus(); } else { notify(error.message, true); } } finally { buttons.forEach(b => b.disabled = false); form.removeAttribute('aria-busy'); }}function date(value) { const d = new Date(value); return Number.isNaN(d.getTime()) ? String(value || '—') : d.toLocaleDateString(undefined, { month: 'short', day: 'numeric', year: 'numeric' });}function activate() { $('#nav-overview').classList.add('active'); $('#nav-new').classList.remove('active');}function strip(selected) { const container = el('section', undefined, 'mission-strip'); container.setAttribute('aria-label', 'Five security perspectives'); roles.forEach(([id, num, title, , description]) => { const cell = el('div', undefined, 'hat'); const meta = el('div', undefined, 'hat-number mono'); append(meta, el('span', num), el('span', selected ? (selected.includes(id) ? 'ASSIGNED' : '—') : 'PERSPECTIVE')); append(cell, meta, el('h3', title), el('p', description)); container.append(cell); }); return container;}function heading(kicker, title, description, action) { const row = el('div', undefined, 'page-heading'); const copy = el('div'); append(copy, el('p', kicker, 'eyebrow'), el('h1', title), el('p', description, 'muted')); append(row, copy, action); return row;}function empty(title, text, action) { const box = el('div', undefined, 'empty'); append(box, el('span', '∅', 'empty-index'), el('h2', title), el('p', text), action); return box;}function openCreate() { $('#nav-new').classList.add('active'); $('#create-dialog').showModal(); $('#assessment-name').focus();}async function loadOverview() { activate(); state.assessment = null; $('#view').replaceChildren(el('p', 'Loading assessments…', 'muted')); try { state.assessments = (await api('/api/assessments')).assessments; renderOverview(); } catch (error) { if (state.csrf) { $('#view').replaceChildren(empty('Could not load assessments', error.message, button('Try again', loadOverview))); } notify(error.message, true); }}function renderOverview() { const view = $('#view'); view.replaceChildren(); append(view, heading('COMMAND CENTER / OVERVIEW', 'Your security work, in evidence.', 'Scope a review. Challenge the findings. Record the decision.', button('+ New assessment', openCreate, 'primary')), strip()); const title = el('div', undefined, 'section-title'); append(title, el('h2', 'Assessment register'), el('span', `${String(state.assessments.length).padStart(2, '0')} ENGAGEMENTS`, 'count')); view.append(title); if (!state.assessments.length) { const box = empty('Start with a defined scope.', 'Review a Python snippet, triage structured alerts, or prepare a five-perspective security exercise.', button('Create first assessment ↗', openCreate, 'primary')); box.append(el('small', 'No source connections or scans run automatically.')); view.append(box); return; } const toolbar = el('div', undefined, 'toolbar'); const search = el('input'); search.type = 'search'; search.placeholder = 'Search assessments…'; search.setAttribute('aria-label', 'Search assessments'); const count = el('span', '', 'count'); append(toolbar, search, count); view.append(toolbar); const wrap = el('div', undefined, 'table-wrap'); view.append(wrap); function draw() { const query = search.value.toLowerCase(); const matches = state.assessments.filter(a => `${a.name} ${a.scope} ${a.workflow}`.toLowerCase().includes(query)); count.textContent = `${matches.length} of ${state.assessments.length}`; const table = el('table'); const head = el('tr'); ['Assessment / scope', 'Workflow', 'Created', 'Candidates', 'Open'].forEach(t => head.append(el('th', t))); append(table, append(el('thead'), head)); const body = el('tbody'); matches.forEach(a => { const row = el('tr'); const identity = el('td'); append(identity, button(a.name, () => openAssessment(a.id), 'row-button'), el('span', a.scope, 'subline')); append(row, identity, el('td', workflows[a.workflow] || a.workflow), el('td', date(a.created_at), 'mono'), el('td', a.finding_count, 'mono'), el('td', a.unresolved_count, 'mono')); body.append(row); }); table.append(body); wrap.replaceChildren(table); if (!matches.length) wrap.append(el('p', 'No matching assessments.', 'muted')); } search.addEventListener('input', draw); draw();}async function openAssessment(id) { $('#view').replaceChildren(el('p', 'Loading evidence…', 'muted')); try { state.assessment = (await api(`/api/assessments/${encodeURIComponent(id)}`)).assessment; state.tab = 'ledger'; renderAssessment(); } catch (error) { notify(error.message, true); if (state.csrf) await loadOverview(); }}function renderAssessment() { activate(); const a = state.assessment; const view = $('#view'); view.replaceChildren(button('← Assessment register', loadOverview, 'text-button back')); append(view, heading(`${workflows[a.workflow] || a.workflow} / ${date(a.created_at)}`, a.name, a.scope), strip(a.roles)); const actions = el('div', undefined, 'detail-actions'); append(actions, button('↓ Export JSON', () => download('json')), button('↓ Export Markdown', () => download('markdown')), button('Delete assessment', () => $('#delete-dialog').showModal(), 'text-button')); view.append(actions); const stats = el('div', undefined, 'stats'); [['Candidates', a.findings.length], ['Awaiting decision', a.findings.filter(f => f.verdict === 'unresolved').length], ['Perspectives assigned', a.roles.length]].forEach(([label, value]) => { const cell = el('div', undefined, 'stat'); append(cell, el('span', label), el('strong', String(value).padStart(2, '0'))); stats.append(cell); }); append(view, stats, el('p', a.summary, 'muted')); const tabs = el('div', undefined, 'tabs'); tabs.setAttribute('role', 'tablist'); const panel = el('section'); panel.id = 'assessment-panel'; panel.setAttribute('role', 'tabpanel'); [['ledger', 'Evidence ledger'], ['missions', 'Missions'], ['coverage', 'Coverage & activity']].forEach(([key, label]) => { const node = button(label, () => { state.tab = key; renderAssessment(); }, `tab${state.tab === key ? ' active' : ''}`); node.id = `tab-${key}`; node.setAttribute('role', 'tab'); node.setAttribute('aria-selected', String(state.tab === key)); node.setAttribute('aria-controls', panel.id); tabs.append(node); }); panel.setAttribute('aria-labelledby', `tab-${state.tab}`); tabs.addEventListener('keydown', event => { if (!['ArrowLeft', 'ArrowRight', 'Home', 'End'].includes(event.key)) return; event.preventDefault(); const keys = ['ledger', 'missions', 'coverage']; const index = keys.indexOf(state.tab); state.tab = keys[event.key === 'Home' ? 0 : event.key === 'End' ? 2 : (index + (event.key === 'ArrowRight' ? 1 : 2)) % 3]; renderAssessment(); $(`#tab-${state.tab}`).focus(); }); tabs.querySelectorAll('[role=tab]').forEach(tab => { tab.tabIndex = tab.getAttribute('aria-selected') === 'true' ? 0 : -1; }); append(view, tabs, panel); if (state.tab === 'ledger') renderLedger(panel, a); if (state.tab === 'missions') a.missions.forEach(m => { const article = el('article', undefined, 'mission'); const head = el('div', undefined, 'mission-header'); append(head, el('p', `${m.role.toUpperCase()} HAT`, 'eyebrow'), el('h3', m.title)); append(article, head, el('p', m.objective)); const steps = el('ol'); m.steps.forEach(s => steps.append(el('li', s))); append(article, steps, el('p', `Deliverable: ${m.deliverable}`)); m.limitations.forEach(l => article.append(el('p', `Limit: ${l}`, 'fine'))); panel.append(article); }); if (state.tab === 'coverage') { const section = el('div', undefined, 'coverage'); append(section, el('h3', 'Checked boundaries & limitations')); const list = el('ul'); a.coverage.forEach(c => list.append(el('li', typeof c === 'string' ? c : JSON.stringify(c)))); append(section, list, el('h3', 'Decision history')); a.activity.forEach(item => { const record = el('div', undefined, 'record-section'); append(record, el('h3', `${date(item.at)} · ${item.action}`), el('p', item.note)); section.append(record); }); panel.append(section); }}function renderLedger(panel, a) { const title = el('div', undefined, 'section-title'); append(title, el('h2', 'Candidate findings'), el('span', 'ANALYST VERDICT REQUIRED', 'count')); panel.append(title); if (!a.findings.length) { panel.append(empty('No candidates from this input.', 'This result covers only the limited checks listed under Coverage. Use the assigned missions to continue the review.')); return; } const toolbar = el('div', undefined, 'toolbar'); const search = el('input'); search.type = 'search'; search.placeholder = 'Search evidence, location, verdict…'; search.setAttribute('aria-label', 'Search findings'); const count = el('span', '', 'count'); append(toolbar, search, count); panel.append(toolbar); const wrap = el('div', undefined, 'table-wrap'); panel.append(wrap); function draw() { const q = search.value.toLowerCase(); const matches = a.findings.filter(f => `${f.title} ${f.location} ${f.verdict} ${f.evidence}`.toLowerCase().includes(q)); count.textContent = `${matches.length} records`; const table = el('table'); const head = el('tr'); ['Candidate / location', 'Severity', 'Confidence', 'Verdict'].forEach(t => head.append(el('th', t))); table.append(append(el('thead'), head)); const body = el('tbody'); matches.forEach(f => { const row = el('tr'); const identity = el('td'); append(identity, button(f.title, () => openFinding(f), 'row-button'), el('span', f.location, 'subline mono')); append(row, identity, el('td', f.severity, 'tag'), el('td', f.confidence, 'tag'), el('td', f.verdict, 'tag')); body.append(row); }); table.append(body); wrap.replaceChildren(table); if (!matches.length) wrap.append(el('p', 'No matching findings.', 'muted')); } search.addEventListener('input', draw); draw();}function displayValue(value) { if (Array.isArray(value)) return value.join('\n'); if (value && typeof value === 'object') return JSON.stringify(value, null, 2); return String(value || 'None recorded.');}function openFinding(f) { state.finding = f; const body = $('#finding-body'); body.replaceChildren(el('h2', f.title), el('p', `${f.severity.toUpperCase()} SEVERITY / ${f.confidence.toUpperCase()} CONFIDENCE`, 'eyebrow')); [['Location', f.location], ['Root cause', f.root_cause], ['Input to impact', f.input_to_impact], ['Prerequisites', f.prerequisites], ['Mitigations inspected', f.mitigations], ['Evidence', f.evidence], ['Remediation', f.remediation]].forEach(([title, value]) => { const section = el('div', undefined, 'record-section'); append(section, el('h3', title), el('p', displayValue(value))); body.append(section); }); $('#verdict').value = f.verdict; $('#review-note').value = f.review_note || ''; $('#finding-dialog').showModal();}async function download(format) { try { const response = await fetch(`/api/assessments/${encodeURIComponent(state.assessment.id)}/export?format=${format}`, { credentials: 'same-origin' }); if (!response.ok) { if (response.status === 401) expired(); const error = await response.json().catch(() => ({})); throw new Error(error.error || 'Export failed.'); } const url = URL.createObjectURL(await response.blob()); const link = el('a'); link.href = url; link.download = `assessment-${state.assessment.id}.${format === 'json' ? 'json' : 'md'}`; document.body.append(link); link.click(); link.remove(); setTimeout(() => URL.revokeObjectURL(url), 1000); } catch (error) { notify(error.message, true); }}$('#login-form').addEventListener('submit', event => { event.preventDefault(); busy(event.currentTarget, async () => { const session = await api('/api/login', { method: 'POST', body: JSON.stringify({ access_key: $('#access-key').value }) }); $('#access-key').value = ''; await enter(session); });});async function enter(session) { if (session.authenticated !== true || typeof session.csrf_token !== 'string' || !session.csrf_token || typeof session.workspace !== 'string') throw new Error('The server returned an invalid session. Sign in again.'); state.csrf = session.csrf_token; $('#workspace-name').textContent = session.workspace; $('#login').hidden = true; $('#shell').hidden = false; await loadOverview();}$('#nav-overview').addEventListener('click', loadOverview);$('.brand').addEventListener('click', e => { e.preventDefault(); loadOverview();});$('#nav-new').addEventListener('click', openCreate);$('#logout').addEventListener('click', () => busy($('#shell'), async () => { await api('/api/logout', { method: 'POST' }); expired(); notify('Signed out.');}));document.querySelectorAll('[data-close]').forEach(b => b.addEventListener('click', () => b.closest('dialog').close()));$('#create-dialog').addEventListener('close', () => $('#nav-new').classList.remove('active'));const help = { code: ['Python source', 'Paste a Python snippet. Source is inspected for a limited set of static candidates; it is never executed.'], alerts: ['Alert events / JSON array', 'Use up to 500 JSON objects with event, actor, and optional source_ip. Supported signals: repeated login_failed, privilege_change, malware_detected.'], exercise: ['Exercise scenario', 'Describe the business, assets, constraints, and scenario. The workbench creates bounded mission plans; it does not simulate an attack.']};let previousWorkflow = 'code';$('#workflow').addEventListener('change', () => { if ($('#content').value.trim() && !window.confirm('Changing workflow will clear your current input. Continue?')) { $('#workflow').value = previousWorkflow; return; } previousWorkflow = $('#workflow').value; const [label, description] = help[$('#workflow').value]; $('#input-label').textContent = label; $('#input-help').textContent = description; $('#content').value = '';});$('#sample').addEventListener('click', () => { if ($('#content').value.trim() && !window.confirm('Replace the current input with the sample?')) return; const w = $('#workflow').value; const samples = { code: 'import subprocess\n\ndef run_diagnostic(user_input):\n return subprocess.run(user_input, shell=True)\n', alerts: JSON.stringify(Array.from({ length: 5 }, () => ({ event: 'login_failed', actor: 'sample-user', source_ip: '192.0.2.10' })), null, 2), exercise: 'A fictional retailer must respond to a suspected account takeover affecting its customer support portal. Scope: tabletop discussion only. Test escalation, identity verification, evidence preservation, and detection handoffs. No production systems or external targets.' }; $('#content').value = samples[w]; if (!$('#assessment-name').value) $('#assessment-name').value = `Sample ${workflows[w].toLowerCase()}`; if (!$('#scope').value) $('#scope').value = 'Fictional sample input only; no external systems'; notify('Sample input loaded. Review scope and authorization before creating.');});$('#create-form').addEventListener('submit', event => { event.preventDefault(); const form = event.currentTarget; const selected = [...form.querySelectorAll('[name="roles"]:checked')].map(n => n.value); if (!selected.length) { formError(form, 'Select at least one perspective.'); return; } busy(form, async () => { const result = await api('/api/assessments', { method: 'POST', body: JSON.stringify({ name: $('#assessment-name').value.trim(), workflow: $('#workflow').value, scope: $('#scope').value.trim(), authorization: $('#authorization').checked, content: $('#content').value, roles: selected }) }); form.reset(); previousWorkflow = 'code'; $('#content').value = ''; $('#input-label').textContent = help.code[0]; $('#input-help').textContent = help.code[1]; $('#create-dialog').close(); state.assessment = result.assessment; state.tab = 'ledger'; renderAssessment(); notify('Assessment created. Candidates await analyst review.'); });});$('#verdict-form').addEventListener('submit', event => { event.preventDefault(); const note = $('#review-note').value.trim(); if (note.length < 20) { formError(event.currentTarget, 'Add a substantive decision note of at least 20 characters.'); return; } busy(event.currentTarget, async () => { state.assessment = (await api(`/api/assessments/${encodeURIComponent(state.assessment.id)}/findings/${encodeURIComponent(state.finding.id)}`, { method: 'PATCH', body: JSON.stringify({ verdict: $('#verdict').value, note }) })).assessment; $('#finding-dialog').close(); renderAssessment(); notify('Analyst decision recorded.'); });});$('#confirm-delete').addEventListener('click', () => busy($('#delete-dialog'), async () => { await api(`/api/assessments/${encodeURIComponent(state.assessment.id)}`, { method: 'DELETE' }); $('#delete-dialog').close(); await loadOverview(); notify('Assessment deleted.');}));(async () => { try { const session = await api('/api/session'); if (session.authenticated) await enter(session); else expired(); } catch (error) { expired(); notify(`Cannot connect to workspace: ${error.message}`, true); }})();window.addEventListener('beforeunload', event => { const draft = $('#assessment-name').value.trim() || $('#scope').value.trim() || $('#content').value.trim(); const noteChanged = $('#finding-dialog').open && state.finding && ($('#review-note').value !== (state.finding.review_note || '') || $('#verdict').value !== state.finding.verdict); if (state.csrf && (draft || noteChanged)) { event.preventDefault(); event.returnValue = ''; }});123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290<!DOCTYPE html><html lang="en"> <head> <meta charset="utf-8"/> <meta content="width=device-width,initial-scale=1" name="viewport"/> <meta content="dark" name="color-scheme"/> <meta content="#171719" name="theme-color"/> <title> Napolean · Cyber Command </title> <link href="/static/style.css" rel="stylesheet"/> <script defer="" src="/static/app.js"> </script> </head> <body> <a class="skip" href="#main"> Skip to content </a> <div aria-live="polite" id="notice" role="status"> </div> <section hidden="" id="login"> <div class="login-brand mono"> N / CYBER COMMAND </div> <form class="login-panel" id="login-form"> <p class="error-inline" hidden="" id="login-form-error" role="alert"> </p> <p class="eyebrow"> NAPOLEAN / SECURE WORKSPACE </p> <h1> Evidence first. <br/> Decisions that hold. </h1> <p class="muted"> An enterprise workbench for scoped security reviews, alert triage, and team exercises. </p> <label for="access-key"> Workspace access key </label> <input autocomplete="current-password" id="access-key" name="access_key" required="" type="password"/> <button class="primary" type="submit"> Open workspace <span aria-hidden="true"> ↗ </span> </button> <p class="fine"> Single customer deployment · Analyst-reviewed findings </p> </form> <p class="login-footer mono"> RED / BLUE / WHITE / BLACK / PURPLE </p> </section> <div hidden="" id="shell"> <aside> <a aria-label="Napolean home" class="brand" href="#"> <span class="brand-mark"> N <span> ↗ </span> </span> <span> NAPOLEAN <small> CYBER COMMAND </small> </span> </a> <p class="eyebrow workspace-label"> WORKSPACE </p> <nav aria-label="Main"> <button class="nav active" id="nav-overview"> 01 <span> Assessments </span> </button> <button class="nav" id="nav-new"> 02 <span> New assessment </span> </button> </nav> <div class="rail-bottom"> <div class="workspace-name" id="workspace-name"> </div> <p class="fine"> Scoped input. Human decisions. </p> <button class="text-button" id="logout"> Sign out ↗ </button> </div> </aside> <main id="main" tabindex="-1"> <header class="topline"> <span class="mono"> SECURITY OPERATIONS / WORKBENCH </span> <span class="mono" id="session-status"> ● SESSION ACTIVE </span> </header> <div id="view"> </div> <footer> <span class="mono"> NAPOLEAN / EVIDENCE BEFORE VERDICTS </span> <span> Local analysis · No autonomous scanning </span> </footer> </main> </div> <dialog aria-labelledby="create-title" id="create-dialog"> <form id="create-form"> <p class="error-inline" hidden="" id="create-form-error" role="alert"> </p> <div class="dialog-head"> <div> <p class="eyebrow"> NEW ENGAGEMENT </p> <h2 id="create-title"> Define the assessment. </h2> </div> <button aria-label="Close assessment form" class="close" data-close="" type="button"> × </button> </div> <div class="form-grid"> <div> <label for="assessment-name"> Assessment name </label> <input id="assessment-name" maxlength="120" name="name" placeholder="Q4 application review" required=""/> </div> <div> <label for="workflow"> Workflow </label> <select id="workflow" name="workflow"> <option value="code"> Code review / Python </option> <option value="alerts"> Alert triage / JSON </option> <option value="exercise"> Team exercise / Scenario </option> </select> </div> </div> <label for="scope"> Authorized scope </label> <input id="scope" maxlength="1000" name="scope" placeholder="Owned service, repository, or exercise boundary" required=""/> <fieldset> <legend> Assign perspectives </legend> <div class="role-checks"> <label> <input checked="" name="roles" type="checkbox" value="red"/> Red </label> <label> <input checked="" name="roles" type="checkbox" value="blue"/> Blue </label> <label> <input checked="" name="roles" type="checkbox" value="white"/> White </label> <label> <input checked="" name="roles" type="checkbox" value="black"/> Black </label> <label> <input checked="" name="roles" type="checkbox" value="purple"/> Purple </label> </div> </fieldset> <div class="input-heading"> <label for="content" id="input-label"> Python source </label> <button class="text-button" id="sample" type="button"> Use sample input ↙ </button> </div> <textarea id="content" maxlength="64000" name="content" required="" rows="9" spellcheck="false"></textarea> <p class="fine" id="input-help"> Paste a Python snippet. Source is inspected for a limited set of static candidates; it is never executed. </p> <label class="attestation"> <input id="authorization" required="" type="checkbox"/> <span> I am authorized to review this material within the scope above. I have removed credentials and unnecessary personal data. </span> </label> <p class="fine"> Raw input is not retained. Findings and analyst notes are retained in this workspace. </p> <div class="dialog-actions"> <button data-close="" type="button"> Cancel </button> <button class="primary" type="submit"> Create assessment ↗ </button> </div> </form> </dialog> <dialog aria-labelledby="finding-title" id="finding-dialog"> <div class="dialog-head"> <p class="eyebrow"> EVIDENCE RECORD </p> <button aria-label="Close finding" class="close" data-close="" type="button"> × </button> </div> <div id="finding-body"> </div> <form id="verdict-form"> <p class="error-inline" hidden="" id="verdict-form-error" role="alert"> </p> <label for="verdict"> Analyst verdict </label> <select id="verdict"> <option value="unresolved"> Unresolved </option> <option value="confirmed-static"> Confirmed static </option> <option value="confirmed-runtime"> Confirmed runtime </option> <option value="rejected"> Rejected </option> </select> <label for="review-note"> Decision evidence / note </label> <textarea id="review-note" maxlength="4000" minlength="20" placeholder="Describe the evidence supporting your decision." required="" rows="4"></textarea> <p class="fine"> A runtime verdict requires evidence you obtained independently. This workbench does not execute source or validate exploitation. </p> <div class="dialog-actions"> <button data-close="" type="button"> Close </button> <button class="primary" type="submit"> Record decision ↗ </button> </div> </form> </dialog> <dialog aria-labelledby="delete-title" id="delete-dialog"> <h2 id="delete-title"> Delete this assessment? </h2> <p> Its findings, missions, and analyst decisions will be permanently removed. </p> <div class="dialog-actions"> <button data-close="" type="button"> Keep assessment </button> <button class="danger" id="confirm-delete"> Delete assessment </button> </div> </dialog> </body></html>123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843:root { --ground:#171719; --surface:#131217; --raised:#212023; --border:#303034; --muted:#a0a1a7; --text:#fff; --accent:#4a8ad6; font-family:-apple-system,BlinkMacSystemFont,"Segoe UI",sans-serif; color:var(--text); background:var(--ground); font-size:14px; color-scheme:dark}* { box-sizing:border-box}body { margin:0}button,input,select,textarea { font:inherit}button,a,input,select,textarea { touch-action:manipulation}button { cursor:pointer; border:1px solid #4b4b50; border-radius:2px; background:transparent; color:#fff; min-height:38px; padding:8px 14px}button:hover { background:#27262a}button:disabled { opacity:.5; cursor:wait}button:focus-visible,a:focus-visible,input:focus-visible,select:focus-visible,textarea:focus-visible { outline:2px solid var(--accent); outline-offset:4px}a { color:inherit}h1,h2,h3,p { margin-top:0}h1 { font-size:34px; font-weight:500; letter-spacing:-1.2px; line-height:1.18}h2 { font-size:23px; font-weight:500; letter-spacing:-.5px}h3 { font-size:16px; font-weight:500}p { line-height:1.6}.mono,.eyebrow,.fine,time,.count,th,.tag { font-family:ui-monospace,SFMono-Regular,Consolas,monospace; font-variant-numeric:tabular-nums}.eyebrow { font-size:10px; letter-spacing:1.5px; color:var(--muted); margin-bottom:16px}.muted,.fine { color:var(--muted)}.fine { font-size:11px; line-height:1.6}.primary { background:#eeedf0; color:#171719; border-color:#eeedf0}.primary:hover { background:#d2d1d6}.danger { border-color:#e5566f; color:#f28b9c}.text-button { border:0; padding:4px 0; min-height:32px; font-size:12px; color:#c1c2c8; text-align:left}.text-button:hover { background:transparent; color:white; text-decoration:underline}.skip { position:fixed; top:-100px; left:20px; z-index:100}.skip:focus { top:12px; background:var(--surface); padding:12px}.login-brand { position:absolute; top:36px; left:40px; font-size:13px; letter-spacing:2px}#login { min-height:100svh; padding:140px 24px 70px; place-items:center}#login:not([hidden]) { display:grid}.login-panel { width:min(450px,100%)}.login-panel h1 { font-size:48px}.login-panel .primary { width:100%; margin:20px 0; display:flex; justify-content:space-between}.login-footer { font-size:10px; letter-spacing:2px; color:var(--muted); margin-top:50px}#shell:not([hidden]) { display:grid; grid-template-columns:216px minmax(0,1fr); min-height:100svh}aside { border-right:1px solid var(--border); padding:32px 24px; position:sticky; top:0; height:100svh; display:flex; flex-direction:column}.brand { display:flex; gap:11px; align-items:center; text-decoration:none; font-size:12px; letter-spacing:1px; font-weight:600}.brand small { display:block; font-size:8px; margin-top:6px; letter-spacing:1.5px; color:var(--muted)}.brand-mark { font-size:35px; font-weight:400; position:relative; line-height:1}.brand-mark span { font-size:16px; position:absolute; right:-5px; top:-4px}.workspace-label { margin-top:70px}.nav { display:flex; gap:18px; border:0; width:100%; padding:15px 0; color:var(--muted); font-size:11px}.nav span { font-size:13px}.nav.active span { color:white; text-decoration:underline; text-decoration-color:var(--accent); text-underline-offset:15px; text-decoration-thickness:1px}.nav:hover { background:transparent; color:white}.rail-bottom { margin-top:auto; padding-top:40px}.workspace-name { font-size:13px; overflow-wrap:anywhere}.rail-bottom .fine { margin-top:8px}main { padding:0 42px; min-width:0}.topline { display:flex; justify-content:space-between; gap:15px; padding:29px 0; border-bottom:1px solid var(--border); font-size:9px; letter-spacing:1px; color:var(--muted)}.page-heading { display:flex; justify-content:space-between; align-items:center; gap:20px; padding:42px 0 28px}.page-heading p { margin-bottom:0}.page-heading h1 { margin-bottom:9px}.mission-strip { display:grid; grid-template-columns:repeat(5,1fr); background:var(--surface); margin:4px 0 32px}.hat { padding:22px 17px; border-right:1px solid var(--border)}.hat:last-child { border:0}.hat .hat-number { font-size:10px; color:var(--muted); display:flex; justify-content:space-between; margin-bottom:24px}.hat h3 { margin-bottom:8px}.hat p { font-size:11px; color:var(--muted); line-height:1.5; margin:0}.section-title { display:flex; justify-content:space-between; align-items:center; gap:16px; margin:32px 0 20px}.section-title h2 { font-size:20px; margin:0; color:#c3c3c9}.toolbar { display:flex; justify-content:space-between; align-items:center; gap:20px; margin-bottom:14px}.toolbar input { max-width:310px}.count { color:var(--muted); font-size:11px; white-space:nowrap}input,select,textarea { display:block; width:100%; background:var(--surface); color:white; border:1px solid #48474d; border-radius:2px; padding:10px 11px; min-height:39px}input::placeholder,textarea::placeholder { color:#898990}textarea { font-family:ui-monospace,SFMono-Regular,Consolas,monospace; font-size:12px; line-height:1.6; resize:vertical}label { display:block; font-size:12px; color:#c9c9cd; margin:18px 0 8px}table { border-collapse:collapse; width:100%; font-size:12px; text-align:left}th { font-size:10px; color:var(--muted); font-weight:400; padding:12px 10px; white-space:nowrap}td { padding:19px 10px; border-top:1px solid var(--border); vertical-align:top; overflow-wrap:anywhere}td:first-child,th:first-child { padding-left:0}td:last-child,th:last-child { text-align:right; padding-right:0}.row-button { border:0; padding:0; min-height:24px; text-align:left; font-size:13px}.row-button:hover { background:transparent; text-decoration:underline; text-underline-offset:5px}.subline { font-size:10px; color:var(--muted); display:block; margin-top:6px}.empty { padding:58px 20px 64px; background:var(--surface); text-align:center}.empty-index { font-family:ui-monospace,monospace; font-size:42px; color:#77777e; display:block; margin-bottom:21px}.empty h2 { margin-bottom:12px}.empty p { max-width:430px; margin:0 auto 22px; color:var(--muted); font-size:13px}.empty small { display:block; margin-top:20px; color:var(--muted); font-size:11px}.stats { display:grid; grid-template-columns:repeat(3,1fr); padding:20px 0; border-top:1px solid var(--border); border-bottom:1px solid var(--border); margin:15px 0 25px}.stat { padding-left:24px; border-left:1px solid var(--border)}.stat:first-child { padding-left:0; border-left:0}.stat strong { display:block; font:28px ui-monospace,SFMono-Regular,monospace; margin:8px 0}.stat span { font-size:11px; color:var(--muted)}.detail-actions { display:flex; flex-wrap:wrap; gap:10px; margin:18px 0}.detail-actions button { font-size:11px}.tabs { display:flex; gap:28px; border-bottom:1px solid var(--border); margin-top:28px}.tab { border:0; border-radius:0; padding:13px 0; font-size:12px; color:var(--muted)}.tab.active { border-bottom:1px solid var(--accent); color:white}.tag { font-size:10px; color:#cbcad0}.mission { padding:25px 0; border-bottom:1px solid var(--border)}.mission-header { display:flex; gap:22px; align-items:baseline}.mission-header .eyebrow { width:65px}.mission p,.mission li,.coverage li { font-size:12px; color:#c2c2c8; line-height:1.7}.mission ol { padding-left:20px}.coverage { padding:26px 0}.coverage ul { padding-left:20px}.record-section { padding:15px 0; border-bottom:1px solid var(--border)}.record-section h3 { font-size:10px; text-transform:uppercase; letter-spacing:1px; color:var(--muted)}.record-section p { font-size:12px; margin:0; white-space:pre-wrap; overflow-wrap:anywhere}.back { margin-top:24px}.error-inline { color:#f28b9c; font-size:12px}.table-wrap { overflow-x:auto}footer { display:flex; justify-content:space-between; gap:15px; padding:30px 0; margin-top:50px; border-top:1px solid var(--border); font-size:9px; color:var(--muted)}dialog { background:#171719; color:white; border:1px solid #4a494f; border-radius:4px; width:min(760px,calc(100vw - 32px)); max-height:calc(100dvh - 40px); padding:30px}dialog::backdrop { background:rgb(0 0 0/.75)}.dialog-head { display:flex; justify-content:space-between; align-items:flex-start; gap:20px}.dialog-head h2 { margin-bottom:0}.close { border:0; font-size:25px; line-height:1; padding:0 8px; min-height:30px}.form-grid { display:grid; grid-template-columns:1fr 1fr; gap:18px}.dialog-actions { display:flex; gap:12px; justify-content:flex-end; margin-top:24px}fieldset { border:0; padding:0; margin:20px 0}legend { font-size:12px; color:#c9c9cd}.role-checks { display:flex; justify-content:space-between; gap:8px}.role-checks label,.attestation { display:flex; align-items:flex-start; gap:9px}.role-checks input,.attestation input { width:16px; height:16px; min-height:16px; accent-color:#a0a1a7; flex-shrink:0; margin:0}.role-checks label { font-size:12px; margin:12px 0}.attestation { font-size:11px; line-height:1.6}.input-heading { display:flex; justify-content:space-between; align-items:end; gap:16px}.input-heading label { margin-bottom:8px}#notice { position:fixed; right:25px; bottom:25px; max-width:500px; z-index:200; background:#2a292e; border-left:2px solid var(--accent); padding:14px 20px; font-size:12px; box-shadow:0 8px 30px #0005; display:none}#notice.visible { display:block}#notice.error { border-color:#e5566f}#delete-dialog { max-width:500px}#delete-dialog p { color:var(--muted); font-size:13px}[hidden] { display:none!important}@media(min-width:1600px) { main { padding:0 64px } #view { max-width:1500px; margin:auto }}@media(max-width:1000px) { #shell:not([hidden]) { grid-template-columns:176px minmax(0,1fr) } aside { padding:28px 18px } main { padding:0 25px } .mission-strip { grid-template-columns:repeat(5,minmax(110px,1fr)); overflow-x:auto } .hat { padding:18px 12px } .hat p { font-size:10px }}@media(max-width:700px) { #shell:not([hidden]) { display:block } aside { position:static; height:auto; padding:18px 20px; border-bottom:1px solid var(--border); border-right:0; display:grid; grid-template-columns:1fr auto; gap:10px } .brand small { font-size:7px } .brand-mark { font-size:28px } .workspace-label,.rail-bottom { display:none } nav { display:flex; gap:18px; align-items:center } .nav { font-size:0; padding:10px 0 } .nav span { font-size:11px } .nav.active span { text-underline-offset:10px } main { padding:0 20px } .topline { font-size:8px; padding:20px 0 } .topline span:last-child { display:none } .page-heading { padding-top:28px; align-items:flex-start } .page-heading h1 { font-size:28px } .page-heading .primary { font-size:11px; white-space:nowrap } .page-heading p { font-size:12px } .mission-strip { grid-template-columns:repeat(5,138px); margin-bottom:24px } .hat .hat-number { margin-bottom:18px } .hat p { font-size:11px } .toolbar { gap:10px } .toolbar input { max-width:none } .stats { grid-template-columns:repeat(3,1fr) } .stat { padding-left:15px } .stat strong { font-size:23px } .stat span { font-size:10px } .form-grid { grid-template-columns:1fr; gap:0 } dialog { padding:23px } .role-checks { flex-wrap:wrap; justify-content:flex-start; gap:18px } .role-checks label { margin-bottom:0 } .tabs { gap:25px } .detail-actions { gap:8px } .detail-actions button { font-size:10px } .empty { padding:40px 15px } footer { flex-direction:column; line-height:1.6 } .login-panel h1 { font-size:39px } .login-brand { left:24px } #notice { right:16px; left:16px; bottom:16px } .mission-header { display:block } .mission-header .eyebrow { margin-bottom:8px } .input-heading { align-items:center } .input-heading .text-button { font-size:10px }}.page-heading h1,.page-heading p,.mission p,.mission h3,.record-section p { overflow-wrap:anywhere; min-width:0}.page-heading>div { min-width:0}.row-button { overflow-wrap:anywhere; max-width:100%}.table-wrap { max-width:100%}.table-wrap table { min-width:520px}.error-inline { margin:12px 0; color:#f28b9c}.error-inline:focus { outline:1px solid #e5566f; outline-offset:4px}123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243import jsonimport osimport tempfileimport timeimport unittestfrom pathlib import Path
from app import create_app
class BackendTest(unittest.TestCase): def setUp(self): self.temp = tempfile.TemporaryDirectory() self.config = {'TESTING': True, 'DATA_DIR': self.temp.name, 'APP_ACCESS_KEY': 'workspace-access-key-long-enough', 'SECRET_KEY': 'session-secret-key-32-characters-long', 'SESSION_COOKIE_SECURE': False} self.app = create_app(self.config) self.client = self.app.test_client() self.token = self.login()
def tearDown(self): self.temp.cleanup()
def login(self, client=None): response = (client or self.client).post('/api/login', json={'access_key': self.config['APP_ACCESS_KEY']}) self.assertEqual(response.status_code, 200) return response.json['csrf_token']
def create(self, **updates): payload = dict(name='Scope review', workflow='code', scope='Owned test app only', authorization=True, content='eval(user_input)', roles=['red', 'blue', 'white', 'black', 'purple']) payload.update(updates) return self.client.post('/api/assessments', json=payload, headers={'X-CSRF-Token': self.token})
def test_authentication_and_csrf_protect_results_and_mutations(self): other = self.app.test_client() self.assertFalse(other.get('/api/session').json['authenticated']) self.assertEqual(other.get('/api/assessments').status_code, 401) self.assertEqual(other.get('/api/assessments/a/export').status_code, 401) self.assertEqual(self.client.post('/api/assessments', json={}).status_code, 403) self.assertEqual(self.client.post('/api/logout', headers={'X-CSRF-Token': 'wrong'}).status_code, 403) self.assertEqual(self.client.post('/api/logout', headers={'X-CSRF-Token': self.token}).status_code, 200) self.assertEqual(self.client.get('/api/assessments').status_code, 401)
def test_login_rate_limit_expiry_and_secure_headers(self): other = self.app.test_client() for _ in range(5): self.assertEqual(other.post('/api/login', json={'access_key': 'incorrect'}).status_code, 401) self.assertEqual(other.post('/api/login', json={'access_key': 'incorrect'}).status_code, 429) with self.client.session_transaction() as session: session['expires_at'] = time.time() - 10 self.assertEqual(self.client.get('/api/assessments').status_code, 401) response = self.client.get('/api/session') self.assertIn("default-src 'self'", response.headers['Content-Security-Policy']) self.assertEqual(response.headers['Cache-Control'], 'no-store') self.assertEqual(response.headers['X-Content-Type-Options'], 'nosniff')
def test_invalid_scope_roles_and_payloads_are_rejected(self): for update in ({'authorization': False}, {'authorization': 'true'}, {'scope': ''}, {'workflow': 'scan'}, {'roles': []}, {'roles': ['admin']}, {'roles': ['red', 'red']}, {'roles': ['red', {}]}, {'content': 3}, {'content': 'x' * 64001}, {'name': 'x' * 121}): with self.subTest(update=list(update)): self.assertEqual(self.create(**update).status_code, 400) for value in ([], None, 'text', 1): self.assertEqual(self.client.post('/api/assessments', json=value, headers={'X-CSRF-Token': self.token}).status_code, 400) response = self.client.post('/api/assessments', data='x' * 300000, content_type='application/json', headers={'X-CSRF-Token': self.token}) self.assertEqual(response.status_code, 413) self.assertIn('error', response.json)
def test_code_candidates_are_unresolved_and_never_execute_input(self): marker = Path(self.temp.name) / 'executed' response = self.create(content=f'import subprocess\neval(user_input)\nsubprocess.run(command, shell=True)\nopen({str(marker)!r}, "w").write("bad")') self.assertEqual(response.status_code, 201) assessment = response.json['assessment'] self.assertFalse(marker.exists()) self.assertEqual(len(assessment['findings']), 2) self.assertEqual({f['verdict'] for f in assessment['findings']}, {'unresolved'}) self.assertEqual({m['role'] for m in assessment['missions']}, {'red', 'blue', 'white', 'black', 'purple'}) self.assertTrue(all(m['limitations'] and m['steps'] for m in assessment['missions'])) self.assertTrue(assessment['coverage']) clean = self.create(content='print("hello")').json['assessment'] self.assertEqual(clean['findings'], []) self.assertIn('limited', clean['summary'].lower()) self.assertEqual(self.create(content='def bad(').status_code, 400)
def test_secret_values_and_raw_submission_are_never_persisted(self): secret = 'extremely-private-secret-64388' raw_marker = '# RAW-SUBMISSION-NOT-STORED-77441' response = self.create(content=f'API_KEY = "{secret}"\n{raw_marker}\neval("{secret}")') self.assertEqual(response.status_code, 201) assessment = response.json['assessment'] self.assertGreaterEqual(len(assessment['findings']), 2) self.assertNotIn(secret, response.get_data(as_text=True)) self.assertNotIn(raw_marker, response.get_data(as_text=True)) for file in Path(self.temp.name).iterdir(): if file.is_file(): self.assertNotIn(secret.encode(), file.read_bytes()) self.assertNotIn(raw_marker.encode(), file.read_bytes())
def test_alert_correlations_are_grouped_and_schema_is_strict(self): events = [{'event': 'login_failed', 'actor': 'alice', 'source_ip': '192.0.2.1'} for _ in range(5)] events += [{'event': 'privilege_change', 'actor': 'bob'}, {'event': 'malware_detected'}] assessment = self.create(workflow='alerts', content=json.dumps(events)).json['assessment'] self.assertEqual(len(assessment['findings']), 3) for content in ('{}', 'invalid', '[1]', '[{"event":3}]', '[{"event":"login_failed","actor":[]}]', json.dumps([{'event': 'login_failed'}] * 501), '[{"event":"x","extra":42}]'): self.assertEqual(self.create(workflow='alerts', content=content).status_code, 400) split = [{'event': 'login_failed', 'actor': str(i), 'source_ip': '192.0.2.1'} for i in range(5)] self.assertEqual(self.create(workflow='alerts', content=json.dumps(split)).json['assessment']['findings'], [])
def test_exercise_generates_plans_without_inventing_findings(self): assessment = self.create(workflow='exercise', content='Tabletop ransomware at a fictional business').json['assessment'] self.assertEqual(assessment['findings'], []) self.assertEqual(len(assessment['missions']), 5) single = self.create(workflow='exercise', content='A scoped tabletop', roles=['blue']).json['assessment'] self.assertEqual([m['role'] for m in single['missions']], ['blue'])
def test_review_persistence_export_and_deletion(self): assessment = self.create().json['assessment'] aid, fid = assessment['id'], assessment['findings'][0]['id'] path = f'/api/assessments/{aid}' review = path + f'/findings/{fid}' for payload in ({'verdict': 'confirmed-runtime', 'note': ''}, {'verdict': 'fake', 'note': 'test'}, {'verdict': 'confirmed-static', 'note': 'yes'}, {'verdict': 'rejected', 'note': []}): self.assertEqual(self.client.patch(review, json=payload, headers={'X-CSRF-Token': self.token}).status_code, 400) response = self.client.patch(review, json={'verdict': 'confirmed-static', 'note': 'Reviewed taint flow in owned test app.'}, headers={'X-CSRF-Token': self.token}) self.assertEqual(response.status_code, 200) self.assertEqual(response.json['assessment']['findings'][0]['verdict'], 'confirmed-static') fresh = create_app(self.config).test_client() self.login(fresh) self.assertEqual(fresh.get(path).json['assessment']['findings'][0]['verdict'], 'confirmed-static') listing = fresh.get('/api/assessments').json['assessments'] self.assertEqual(listing[0]['unresolved_count'], 0) for fmt in ('json', 'markdown'): export = fresh.get(path + '/export?format=' + fmt) self.assertEqual(export.status_code, 200) self.assertIn('attachment', export.headers['Content-Disposition']) self.assertIn('Reviewed taint flow', export.get_data(as_text=True)) self.assertEqual(fresh.get(path + '/export?format=html').status_code, 400) self.assertEqual(self.client.delete(path, headers={'X-CSRF-Token': self.token}).status_code, 200) self.assertEqual(fresh.get(path).status_code, 404) self.assertEqual(fresh.get(path + '/export').status_code, 404) self.assertEqual(fresh.get('/api/assessments').json['assessments'], [])
def test_nonexistent_findings_and_resources_return_json_errors(self): self.assertEqual(self.client.get('/api/assessments/missing').status_code, 404) aid = self.create().json['assessment']['id'] response = self.client.patch(f'/api/assessments/{aid}/findings/missing', json={'verdict': 'unresolved', 'note': 'Not available'}, headers={'X-CSRF-Token': self.token}) self.assertEqual(response.status_code, 404) self.assertIn('error', response.json)
def test_production_requires_strong_deployment_keys(self): from unittest.mock import patch with patch.dict(os.environ, {'APP_ACCESS_KEY': '', 'APP_SECRET_KEY': ''}): with self.assertRaises(ValueError): create_app({'DATA_DIR': self.temp.name}) app = create_app({'DATA_DIR': self.temp.name, 'APP_ACCESS_KEY': 'x' * 24, 'SECRET_KEY': 's' * 32}) self.assertTrue(app.config['SESSION_COOKIE_SECURE'])
def test_whitespace_cannot_bypass_content_limit(self): self.assertEqual(self.create(content='eval(x)' + ' ' * 64000).status_code, 400)
def test_non_ascii_csrf_is_rejected_without_server_error(self): response = self.client.post('/api/logout', headers={'X-CSRF-Token': 'é'}) self.assertEqual(response.status_code, 403)
def test_hostile_text_is_data_and_markdown_export_escapes_it(self): response = self.create(name='<img src=x onerror=alert(1)>', content='print("safe")') self.assertEqual(response.status_code, 201) assessment = response.json['assessment'] export = self.client.get(f'/api/assessments/{assessment["id"]}/export?format=markdown') self.assertNotIn('<img', export.get_data(as_text=True)) self.assertIn('<', export.get_data(as_text=True))
def test_deep_json_and_invalid_unicode_return_client_errors(self): response = self.client.post('/api/assessments', data='[' * 1100 + '0' + ']' * 1100, content_type='application/json', headers={'X-CSRF-Token': self.token}) self.assertEqual(response.status_code, 400) self.assertEqual(self.create(content='print("\ud800")').status_code, 400) response = self.client.post('/api/login', json={'access_key': '\ud800' * 24}) self.assertEqual(response.status_code, 400)
def test_exercise_routes_scenarios_without_retaining_raw_prose(self): ransomware = self.create(workflow='exercise', content='Unique prose 95342: ransomware encrypts payroll').json['assessment'] identity = self.create(workflow='exercise', content='Unique prose 89241: phishing targets business identities').json['assessment'] cloud = self.create(workflow='exercise', content='AWS cloud tenant access review').json['assessment'] supply = self.create(workflow='exercise', content='Third-party package supply-chain incident').json['assessment'] generic = self.create(workflow='exercise', content='A business security workshop').json['assessment'] expected = ('ransomware', 'identity/phishing', 'cloud', 'supply-chain', 'generic') for assessment, category in zip((ransomware, identity, cloud, supply, generic), expected): self.assertEqual(assessment['scenario_category'], category) self.assertTrue(all(len(m['steps']) >= 4 for m in assessment['missions'])) self.assertNotEqual(ransomware['missions'][0]['steps'], identity['missions'][0]['steps']) serialized = json.dumps(ransomware) + json.dumps(identity) self.assertNotIn('Unique prose', serialized) for file in Path(self.temp.name).iterdir(): if file.is_file(): self.assertNotIn(b'Unique prose', file.read_bytes())
def test_workflow_missions_guide_evidence_collection(self): code = self.create().json['assessment'] alerts = self.create(workflow='alerts', content='[{"event":"malware_detected"}]').json['assessment'] self.assertIn('ledger', code['missions'][0]['steps'][0].lower()) self.assertIn('corroborat', alerts['missions'][0]['steps'][0].lower())
def test_deployment_keys_must_be_distinct(self): with self.assertRaises(ValueError): create_app({'DATA_DIR': self.temp.name, 'APP_ACCESS_KEY': 'x' * 32, 'SECRET_KEY': 'x' * 32})
def test_multiword_secrets_and_bearer_tokens_are_redacted_across_metadata(self): password = 'Correct Horse Battery Staple' bearer = 'private-session-token-92841' assessment = self.create(name=f'password="{password}"', scope=f'Owned test: Authorization: Bearer {bearer}').json['assessment'] aid, fid = assessment['id'], assessment['findings'][0]['id'] response = self.client.patch(f'/api/assessments/{aid}/findings/{fid}', json={'verdict': 'unresolved', 'note': f'password=\'{password}\'; Authorization: Bearer {bearer}'}, headers={'X-CSRF-Token': self.token}) self.assertEqual(response.status_code, 200) outputs = [response.get_data(as_text=True), self.client.get('/api/assessments').get_data(as_text=True)] for fmt in ('json', 'markdown'): outputs.append(self.client.get(f'/api/assessments/{aid}/export?format={fmt}').get_data(as_text=True)) for value in outputs: self.assertNotIn(password, value) self.assertNotIn(bearer, value) for file in Path(self.temp.name).iterdir(): if file.is_file(): self.assertNotIn(password.encode(), file.read_bytes()) self.assertNotIn(bearer.encode(), file.read_bytes())
def test_unknown_alert_labels_disclose_skipped_count(self): assessment = self.create(workflow='alerts', content='[{"event":"unrecognized"},{"event":"another"}]').json['assessment'] self.assertEqual(assessment['findings'], []) self.assertIn('2 event(s) skipped', ' '.join(assessment['coverage']))
if __name__ == '__main__': unittest.main()1234567891011121314151617181920212223242526272829303132333435363738394041424344import tempfileimport unittestfrom pathlib import Pathfrom deploy_hf import collect_files, deploy, validate_repo_id
class FakeHub: def __init__(self): self.calls = [] def create_repo(self, **kw): self.calls.append(('create', kw)) def add_space_secret(self, **kw): self.calls.append(('secret', kw)) def upload_folder(self, **kw): self.calls.append(('upload', kw))
class DeploymentTests(unittest.TestCase): def test_manifest_excludes_customer_data_and_keys(self): root = Path(__file__).resolve().parents[1] files = collect_files(root) self.assertIn('app.py', files) self.assertIn('gradio_app.py', files) self.assertNotIn('Dockerfile', files) self.assertIn('engine.py', files) self.assertFalse(any(p.startswith('data/') or '.env' in p for p in files)) self.assertFalse(any('tests' in p for p in files))
def test_creation_is_private_and_does_not_reuse_repo(self): api = FakeHub() deploy(api, 'example/cyber-command', Path(__file__).resolve().parents[1], 'a'*30, 'b'*40) create = api.calls[0][1] self.assertEqual(create, dict(repo_id='example/cyber-command', repo_type='space', space_sdk='gradio', private=True, exist_ok=False)) self.assertEqual([c[0] for c in api.calls], ['create','secret','secret','upload']) upload = api.calls[-1][1] self.assertNotIn('data/', upload['allow_patterns']) self.assertEqual(upload['repo_type'], 'space')
def test_bad_ids_and_secrets_cause_no_network_mutation(self): for value in ('public', '../escape', 'a/b/c', 'a/b?token=secret'): with self.assertRaises(ValueError): validate_repo_id(value) api = FakeHub() with self.assertRaises(ValueError): deploy(api, 'example/cyber-command', Path('.'), 'short', 'b'*40) self.assertEqual(api.calls, [])
def test_missing_source_is_rejected(self): with tempfile.TemporaryDirectory() as d: with self.assertRaises(ValueError): collect_files(Path(d))
if __name__ == '__main__': unittest.main()123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191import jsonimport osimport tempfileimport unittestfrom pathlib import Pathfrom unittest.mock import patch
from gradio_app import build_application, build_ui, create_service, main
class NativeWorkspaceTest(unittest.TestCase): def setUp(self): self.temp = tempfile.TemporaryDirectory() self.config = {'TESTING': True, 'DATA_DIR': self.temp.name, 'APP_ACCESS_KEY': 'native-workspace-access-key-12345', 'SECRET_KEY': 'native-session-signing-key-long-enough-12345'} self.service = create_service(self.config)
def tearDown(self): self.temp.cleanup()
def payload(self, **changes): value = dict(name='Native review', scope='Owned laboratory app', workflow='code', content='eval(user_input)', authorization=True, roles=['red', 'blue', 'white', 'black', 'purple']) value.update(changes) return value
def test_adapter_runs_all_workflows_and_preserves_evidence_decisions(self): self.assertEqual(self.service.list_assessments(), []) code = self.service.create(self.payload()) alert = self.service.create(self.payload(workflow='alerts', content='[{"event":"malware_detected"}]')) exercise = self.service.create(self.payload(workflow='exercise', content='A ransomware tabletop')) self.assertEqual(len(code['findings']), 1) self.assertEqual(len(alert['findings']), 1) self.assertEqual(exercise['scenario_category'], 'ransomware') self.assertEqual(len(exercise['missions']), 5) reviewed = self.service.review(code['id'], code['findings'][0]['id'], 'confirmed-static', 'Traced input reachability through the owned laboratory application.') self.assertEqual(reviewed['findings'][0]['verdict'], 'confirmed-static') fresh = create_service(self.config) self.assertEqual(fresh.get(code['id'])['findings'][0]['verdict'], 'confirmed-static') self.assertEqual(len(fresh.list_assessments()), 3) self.assertEqual(json.loads(fresh.export(code['id'], 'json'))['id'], code['id']) self.assertIn('Traced input reachability', fresh.export(code['id'], 'markdown')) self.assertTrue(fresh.delete(code['id'])['ok']) with self.assertRaises(ValueError): fresh.get(code['id'])
def test_adapter_preserves_scope_validation_and_redaction(self): with self.assertRaises(ValueError): self.service.create(self.payload(authorization=False)) with self.assertRaises(ValueError): self.service.create(self.payload(roles=['unknown'])) assessment = self.service.create(self.payload(content='password="private-secret-value-44232"')) self.assertNotIn('private-secret-value-44232', json.dumps(assessment)) with self.assertRaises(ValueError): self.service.review(assessment['id'], assessment['findings'][0]['id'], 'confirmed-runtime', 'yes') with self.assertRaises(ValueError): self.service.export(assessment['id'], 'html')
def test_native_ui_has_workflows_roles_review_and_no_file_components(self): ui = build_ui(self.service) config = ui.get_config_file() types = [component['type'] for component in config['components']] self.assertNotIn('file', types) self.assertNotIn('uploadbutton', types) props = [component.get('props', {}) for component in config['components']] role = next(item for item in props if item.get('label') == 'Security perspectives') self.assertEqual(set(role['value']), {'red', 'blue', 'white', 'black', 'purple'}) workflow = next(item for item in props if item.get('label') == 'Workflow') choices = [choice[1] if isinstance(choice, (tuple, list)) else choice for choice in workflow['choices']] self.assertEqual(set(choices), {'code', 'alerts', 'exercise'}) self.assertTrue(any(item.get('label') == 'Evidence note' for item in props)) self.assertTrue(any(item.get('label') == 'Export text' for item in props)) self.assertFalse(ui.analytics_enabled) self.assertFalse(ui.enable_queue) self.assertFalse(ui.run_history) self.assertTrue(all(not dependency['queue'] for dependency in config['dependencies']))
def test_native_callbacks_create_review_export_and_delete(self): ui = build_ui(self.service) callbacks = [block.fn for block in ui.fns.values()] created = callbacks[1]('Callback review', 'code', 'Owned lab app', ['red', 'blue', 'white', 'black', 'purple'], 'eval(user_input)', True) self.assertEqual(len(created), 8) assessment = created[2] self.assertEqual(created[5], '') self.assertEqual(len(assessment['missions']), 5) opened = callbacks[2](assessment['id']) self.assertEqual(opened[0]['id'], assessment['id']) reviewed = callbacks[3](assessment['id'], assessment['findings'][0]['id'], 'rejected', 'Verified this is unreachable in the supplied owned app.') self.assertEqual(reviewed[0]['findings'][0]['verdict'], 'rejected') self.assertEqual(len(reviewed), 6) self.assertEqual(reviewed[5], '') self.assertIn('Verified this is unreachable', callbacks[4](assessment['id'], 'markdown')) with self.assertRaises(Exception): callbacks[5](assessment['id'], False) self.assertEqual(len(self.service.list_assessments()), 1) callbacks[5](assessment['id'], True) self.assertEqual(self.service.list_assessments(), [])
def test_selection_change_and_reload_clear_stale_review_and_delete_state(self): ui = build_ui(self.service) config = ui.get_config_file() input_events = [dependency for dependency in config['dependencies'] if any(target[1] == 'input' for target in dependency['targets'])] self.assertEqual(len(input_events), 1) callback = ui.fns[input_events[0]['id']].fn first = self.service.create(self.payload()) second = self.service.create(self.payload(name='Second review')) selected = callback(second['id']) self.assertEqual(selected[0]['id'], second['id']) self.assertNotEqual(selected[0]['id'], first['id']) self.assertEqual(selected[3:], ('', '', False)) cleared = callback(None) self.assertEqual(cleared[0], {}) self.assertEqual(cleared[3:], ('', '', False)) reloaded = list(ui.fns.values())[0].fn() self.assertEqual(len(reloaded), 8) self.assertEqual(reloaded[2], {}) self.assertFalse(reloaded[-1])
def test_gradio_auth_gates_config_and_callbacks_without_mounting_flask(self): import gradio as gr from fastapi import FastAPI from fastapi.testclient import TestClient ui = build_ui(self.service) mounted = gr.mount_gradio_app(FastAPI(), ui, path='/', auth=('analyst', self.config['APP_ACCESS_KEY']), run_history=False, enable_monitoring=False, mcp_server=False, theme=gr.themes.Base(font=['Arial', 'sans-serif'], font_mono=['Courier New', 'monospace'])) with TestClient(mounted) as client: self.assertEqual(client.get('/config').status_code, 401) callback = client.post('/gradio_api/run/run', json={'data': [], 'fn_index': 0}) self.assertIn(callback.status_code, (401, 403)) self.assertEqual(client.get('/api/assessments').status_code, 404) self.assertEqual(client.post('/login', data={'username': 'analyst', 'password': 'wrong'}).status_code, 400) self.assertEqual(client.post('/login', data={'username': 'analyst', 'password': self.config['APP_ACCESS_KEY']}).status_code, 200) config = client.get('/config') self.assertEqual(config.status_code, 200) self.assertNotIn('fonts.googleapis.com', config.text) self.assertFalse(config.json()['run_history'])
def test_missing_secrets_render_setup_without_backend_or_data_directory(self): config = {'DATA_DIR': str(Path(self.temp.name) / 'must-not-exist')} with patch.dict(os.environ, {'APP_ACCESS_KEY': '', 'APP_SECRET_KEY': ''}): with self.assertRaises(ValueError): create_service(config) ui = build_application(config) self.assertFalse(Path(config['DATA_DIR']).exists()) ui_config = ui.get_config_file() self.assertEqual(ui_config['dependencies'], []) content = ' '.join(str(c.get('props', {}).get('value', '')) for c in ui_config['components']) self.assertIn('APP_ACCESS_KEY', content) self.assertIn('APP_SECRET_KEY', content) self.assertNotIn(self.config['APP_ACCESS_KEY'], content)
def test_deployed_origin_policy_blocks_hosted_cross_site_reads_and_mutations(self): from fastapi.testclient import TestClient with patch.dict(os.environ, {'APP_ACCESS_KEY': self.config['APP_ACCESS_KEY'], 'APP_SECRET_KEY': self.config['SECRET_KEY'], 'DATA_DIR': self.temp.name, 'SPACE_ID': 'test/cyber-command'}): with patch('gradio_app.uvicorn.run') as launch: main() mounted = launch.call_args.args[0] self.assertEqual(launch.call_args.kwargs['host'], '0.0.0.0') hosted = 'https://test-cyber-command.hf.space' with TestClient(mounted, base_url=hosted) as client: foreign_login = client.post('/login', data={'username': 'analyst', 'password': self.config['APP_ACCESS_KEY']}, headers={'Origin': 'https://attacker.example'}) self.assertEqual(foreign_login.status_code, 403) self.assertNotIn('access-control-allow-origin', foreign_login.headers) self.assertEqual(client.post('/login', data={'username': 'analyst', 'password': self.config['APP_ACCESS_KEY']}).status_code, 200) for origin in ('https://attacker.example', 'null', hosted + '/path', 'http://test-cyber-command.hf.space', hosted + ':443@attacker.example', hosted + ':9443'): with self.subTest(origin=origin): response = client.get('/config', headers={'Origin': origin}) self.assertEqual(response.status_code, 403) self.assertNotIn('access-control-allow-origin', response.headers) callback = client.post('/gradio_api/run/run', json={'data': [], 'fn_index': 0}, headers={'Origin': origin}) self.assertEqual(callback.status_code, 403) preflight = client.options('/config', headers={'Origin': 'https://attacker.example', 'Access-Control-Request-Method': 'GET'}) self.assertEqual(preflight.status_code, 403) self.assertNotIn('access-control-allow-origin', preflight.headers) config = client.get('/config', headers={'Origin': hosted}) self.assertEqual(config.status_code, 200) callback = client.post('/gradio_api/run/run', json={'data': [], 'fn_index': 0}, headers={'Origin': hosted}) self.assertEqual(callback.status_code, 200) self.assertEqual(client.get('/config').status_code, 200)
if __name__ == '__main__': unittest.main().env.exampleAdded+9
.gitignoreAdded+11
DEPENDENCY-ADVISORIES.jsonAdded+320
PROVENANCE.mdAdded+15
README.md+76-7
SECURITY.mdAdded+38
SERVICE.mdAdded+43
VERIFICATION.mdAdded+37
app.pyAdded+230
deploy_hf.pyAdded+69
engine.pyAdded+289
gradio_app.pyAdded+273
requirements-deploy.txtAdded+2
requirements.txtAdded+59
static/app.jsAdded+513
static/index.htmlAdded+290
static/style.cssAdded+843
tests/test_backend.pyAdded+243
tests/test_deploy.pyAdded+44
tests/test_gradio.pyAdded+191