Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
Phase 2: supply-chain gates + hard-fail insecure prod defaults (#423)
Beenu Arora300ccd548f9f
diff --git a/.github/LICENSES.md b/.github/LICENSES.mdindex b25414f44..7f6e3eec6 100644--- a/.github/LICENSES.md+++ b/.github/LICENSES.md@@ -1,6 +1,6 @@# Third-Party Content Licenses-AiSOC ships under [Apache-2.0](LICENSE). Some content under [`detections/`](detections/) is **imported** from upstream open-source detection corpora and is redistributed under each upstream project's own license. Every imported rule carries a `provenance` block documenting its source, upstream id, commit SHA, and license, so you can always trace a rule back to its origin.+AiSOC ships under the [MIT License](LICENSE). Some content under [`detections/`](detections/) is **imported** from upstream open-source detection corpora and is redistributed under each upstream project's own license. Every imported rule carries a `provenance` block documenting its source, upstream id, commit SHA, and license, so you can always trace a rule back to its origin.This file is the canonical attribution registry. It is updated automatically when [`tools/detection-import/import.py`](tools/detection-import/import.py) runs.@@ -61,9 +61,9 @@ DRL-1.1 summary: you may use, modify, and redistribute Sigma rules provided you## Native AiSOC content-Everything under `detections/cloud/`, `detections/identity/`, `detections/endpoint/`, `detections/network/`, `detections/application/`, and `detections/data-exfil/` is **native AiSOC content** authored against AiSOC's own normalized event schema. Native rules are licensed under [Apache-2.0](LICENSE) and carry a `provenance.source: native` marker.+Everything under `detections/cloud/`, `detections/identity/`, `detections/endpoint/`, `detections/network/`, `detections/application/`, and `detections/data-exfil/` is **native AiSOC content** authored against AiSOC's own normalized event schema. Native rules are licensed under the [MIT License](LICENSE) and carry a `provenance.source: native` marker.-`detections/community/` carries community contributions, also under Apache-2.0 with the contributor named in the provenance block.+`detections/community/` carries community contributions, also under MIT with the contributor named in the provenance block.---diff --git a/.github/workflows/security.yml b/.github/workflows/security.ymlnew file mode 100644index 000000000..af263b7c4--- /dev/null+++ b/.github/workflows/security.yml@@ -0,0 +1,115 @@+name: Security++# Phase 2 supply-chain + truth gates. Complements the existing codeql.yml+# (SAST), security-audit.yml (dependency CVEs), and scorecard.yml.+#+# Enforcement policy (honest ratchet):+# - HARD gate (fails the build): the claim-to-gate matrix ratchet. A new+# ungated marketing claim must never merge.+# - OBSERVE gates (report, do not fail yet): gitleaks, Semgrep, Trivy,+# checkov/tfsec. These scan a ~200k-line pre-existing codebase (with test+# fixtures / demo placeholders); we surface findings on every PR and+# ratchet them to blocking once a baseline is triaged into+# .security/allowlist.yml (gitleaks: .gitleaksignore). Flipping+# continue-on-error to false is the tracked Phase 2 continuation.+# GitHub native push-protection remains the always-on hard secret gate.++on:+ pull_request:+ push:+ branches: [main]+ schedule:+ - cron: "0 7 * * 1"++permissions:+ contents: read++jobs:+ # ── HARD: every marketing claim maps to a gate (ratchet) ──────────────────+ claim-gate-matrix:+ name: Claim-to-gate matrix (ratchet)+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v7+ - uses: actions/setup-python@v6+ with:+ python-version: "3.12"+ - name: Enforce no new NO GATE rows+ run: python3 scripts/check_claim_gate_matrix.py++ # ── OBSERVE: secret scan (report; ratchet to blocking after triage) ───────+ secret-scan:+ name: Secret scan (gitleaks, observe)+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v7+ - name: Install gitleaks+ run: |+ set -euo pipefail+ VERSION=8.21.2+ curl -sSL "https://github.com/gitleaks/gitleaks/releases/download/v${VERSION}/gitleaks_${VERSION}_linux_x64.tar.gz" -o /tmp/gitleaks.tgz+ tar -xzf /tmp/gitleaks.tgz -C /tmp gitleaks+ sudo mv /tmp/gitleaks /usr/local/bin/gitleaks+ gitleaks version+ - name: Scan working tree (respects .gitleaksignore)+ continue-on-error: true+ run: gitleaks dir . --redact --exit-code 1 --no-banner++ # ── OBSERVE: SAST beyond CodeQL ───────────────────────────────────────────+ semgrep:+ name: Semgrep (observe)+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v7+ - uses: actions/setup-python@v6+ with:+ python-version: "3.12"+ - name: Install semgrep+ run: pip install --quiet semgrep+ - name: Scan+ continue-on-error: true+ run: |+ semgrep --error --disable-version-check \+ --config p/security-audit \+ --config p/owasp-top-ten \+ --config p/python \+ --config p/typescript \+ --config p/react \+ --exclude plans/ \+ services/ apps/ packages/ scripts/++ # ── OBSERVE: filesystem vuln scan (complements dependency SCA) ────────────+ trivy-fs:+ name: Trivy filesystem (observe)+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v7+ - name: Install & run Trivy (report-only)+ continue-on-error: true+ run: |+ set -uo pipefail+ VERSION=0.55.2+ curl -sSL "https://github.com/aquasecurity/trivy/releases/download/v${VERSION}/trivy_${VERSION}_Linux-64bit.tar.gz" -o /tmp/trivy.tgz+ tar -xzf /tmp/trivy.tgz -C /tmp trivy+ /tmp/trivy fs --severity HIGH,CRITICAL --ignore-unfixed --skip-dirs plans --exit-code 0 .++ # ── OBSERVE: IaC misconfig scan ───────────────────────────────────────────+ iac-scan:+ name: IaC scan (checkov + tfsec, observe)+ runs-on: ubuntu-latest+ steps:+ - uses: actions/checkout@v7+ - uses: actions/setup-python@v6+ with:+ python-version: "3.12"+ - name: checkov (terraform + helm)+ continue-on-error: true+ run: |+ pip install --quiet checkov+ checkov -d infra/terraform --quiet --compact || true+ checkov -d infra/helm --quiet --compact || true+ - name: tfsec (terraform)+ continue-on-error: true+ uses: aquasecurity/[email protected]+ with:+ working_directory: infra/terraformdiff --git a/.security/allowlist.yml b/.security/allowlist.ymlnew file mode 100644index 000000000..96a9a4612--- /dev/null+++ b/.security/allowlist.yml@@ -0,0 +1,20 @@+# Security scanner allowlist (Phase 2)+#+# Suppressions for the Semgrep / Trivy / checkov / tfsec scanners in+# .github/workflows/security.yml. Every entry MUST carry a reason and an+# expiry date; expired entries fail CI once the scanners flip from observe to+# blocking (tracked Phase 2 continuation). This is separate from the+# dependency-CVE ignore list at scripts/security_audit_ignores.txt.+#+# Schema:+# entries:+# - tool: semgrep|trivy|checkov|tfsec+# id: <rule/check id>+# path: <optional path glob>+# reason: <why this is acceptable> # required, non-empty+# expires: YYYY-MM-DD # required, <= 90 days out+#+# Keep this list empty until a scanner is ratcheted to blocking; add triaged+# baseline findings here at that time, never blanket-suppress.++entries: []diff --git a/CHANGELOG.md b/CHANGELOG.mdindex c8e1ec79b..208f534df 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -9,6 +9,8 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0### Security+- **Phase 2 — supply chain + truth gates.** New `.github/workflows/security.yml`: a claim-to-gate matrix ratchet (`scripts/check_claim_gate_matrix.py` — the NO GATE count may only decrease; enforces the Phase 0 promise) as the HARD gate, plus gitleaks (secret), Semgrep, Trivy (fs), and checkov/tfsec in report-and-ratchet ("observe") mode with a triage allowlist at `.security/allowlist.yml` / `.gitleaksignore` (GitHub push-protection remains the always-on hard secret gate). **Insecure defaults now hard-fail the boot in production**: `enforce_secure_defaults()` (`services/api/app/core/config.py`) raises `InsecureProductionDefaultsError` when `ENVIRONMENT=production` and any placeholder secret remains, wired into `app/main.py` startup and gated by `services/api/tests/test_security_defaults.py::test_enforce_*`. Added `TRADEMARK.md` (the MIT code is free; the name is not), `docs/operations/verifying-releases.md`, a README `Maturity` note, and fixed the `.github/LICENSES.md` license inconsistency (AiSOC ships under MIT, matching `LICENSE`/README, not Apache-2.0). Claim-to-gate matrix now 10 GATED / 14 PARTIAL / 3 NO GATE. Per-image CycloneDX SBOM + cosign signing + SLSA provenance, SHA-pinning all actions, and flipping the code scanners to blocking are the tracked Phase 2 continuation.+- **Phase 1.6 — platform/vault hardening (KMS envelope encryption).** New `services/api/app/security/envelope_cipher.py`: optional envelope encryption for the credential vault. Each secret is encrypted with a fresh per-secret data key (DEK); the DEK is wrapped by a key-encryption key (KEK) that never leaves KMS/HSM (`vault:v2:<kek_id>:<wrapped_dek>:<ciphertext>`), so a DB dump or a leaked env var yields only wrapped DEKs. Pluggable `KeyManager` protocol with `LocalKeyManager` (default, backward-compatible), `AwsKmsKeyManager` (boto3; GCP KMS / Vault Transit implement the same protocol), and an in-memory `FakeKmsKeyManager` for tests. Key rotation is a cheap **re-wrap** (`EnvelopeCipher.rewrap`) that never re-encrypts the secret body. Gated by `services/api/tests/test_envelope_cipher.py` (round-trip, rotation + re-wrap, plaintext-never-in-token, fail-closed on tamper/wrong-KEK). Added `docs/security/platform-threat-model.md` (STRIDE, vault as top asset) and `docs/security/connector-least-privilege.md`. Completes Phase 1.- **Phase 1.5 — cost-DoS enforcement.** New `services/agents/app/core/cost_governor.py`: a per-tenant `CostGovernor` that turns the existing `aisoc_run_costs` telemetry into enforcement — rolling-window soft/hard USD budgets, a circuit breaker that drops investigations to deterministic-only mode once the hard cap is hit (instead of billing unboundedly), a per-alert token ceiling (`cap_tokens`), and an evidence-hash dedup cache so a flood of identical alerts costs one investigation, not N. Gated by `services/agents/tests/test_cost_governor.py` (10 tests incl. the headline 10 000-identical-alert flood asserting spend stays at exactly one run, and a distinct-alert flood asserting the circuit breaker bounds spend near the hard cap). Live-orchestrator wiring of `get_governor().check(...)` before the LLM call is the tracked continuation.diff --git a/README.md b/README.mdindex 58d494730..7fcc878a3 100644--- a/README.md+++ b/README.md@@ -165,6 +165,8 @@ Full architecture (every service, every storage role, the v1.5 console workbenchA handful of headline capabilities — the rest are catalogued in [`apps/docs/docs/features/`](apps/docs/docs/features/) and indexed at the top of [`apps/docs/docs/intro.md`](apps/docs/docs/intro.md):+> **Maturity.** Connectors, Investigation Rail + Ledger, and Hunt-as-Code are GA. Detection-as-Code and L0–L4 autonomy are beta (eval-gate and rollback/post-action-verification hardening in progress). The live-agent benchmark is preview; the substrate eval suites are GA. Full per-claim status: [`docs/audit/REALITY_REPORT.md`](docs/audit/REALITY_REPORT.md).+- **69 click-and-connect data connectors** (EDR/XDR, SIEM, cloud, CNAPP, identity, SaaS, VCS, K8s audit, network) with schema-driven config, live `Test connection`, and vault-encrypted secrets. Walkthrough: [`apps/docs/docs/connectors/index.md`](apps/docs/docs/connectors/index.md).- **Investigation Rail + replayable Investigation Ledger** — every prompt, tool call, evidence chip, and rationale stored against a case, replayable in the UI. [`apps/docs/docs/console/investigation-rail.md`](apps/docs/docs/console/investigation-rail.md).- **Detection-as-Code lifecycle** — propose → review → eval-gate → promote; CI rejects any candidate that regresses MITRE accuracy. [`apps/docs/docs/concepts/detections.md`](apps/docs/docs/concepts/detections.md) — and the 800+ native Sigma rules live in [`detections/`](detections/).diff --git a/TRADEMARK.md b/TRADEMARK.mdnew file mode 100644index 000000000..8095bbb65--- /dev/null+++ b/TRADEMARK.md@@ -0,0 +1,29 @@+# AiSOC Trademark and Brand Policy++The AiSOC **code** is free under the [MIT License](LICENSE). The AiSOC **name and logo** are not part of that grant. This is deliberate: MIT lets anyone fork the code (that is the point), but a funded competitor should not be able to fork it, outspend the community on marketing, and pass their product off as "AiSOC."++## What you may do without permission++- Use, fork, modify, and redistribute the source under the MIT License.+- State truthfully that your product is "built on AiSOC," "powered by AiSOC," or "a fork of AiSOC," provided it is clear you are not the official project.+- Use the AiSOC name in blog posts, talks, comparisons, and documentation that refer to the project.++## What requires permission++- Naming a fork, product, service, or company "AiSOC" (or a confusingly similar name).+- Using the AiSOC name or logo as your own product/service branding, or in a way that implies official endorsement, affiliation, or that your distribution is the canonical one.+- Using the AiSOC logo in modified form, or on merchandise.++## Distributing a modified version++If you distribute a modified build, please rename it so users are not misled about what they are running and who supports it. You must keep the MIT `LICENSE` and copyright notices intact, but the product name should be yours.++## Hosted / managed offerings++Offering a hosted or managed service is permitted by the MIT License, but you may not market it under the AiSOC name or imply it is the official hosted AiSOC without permission.++## Requests++To request permission for a use not covered above, open a discussion or contact the maintainers via the channels in [`SUPPORT.md`](SUPPORT.md). We aim to be permissive for community, educational, and non-deceptive uses.++This policy may evolve as the project's governance matures (see [`ROADMAP.md`](ROADMAP.md) — governance phase). It does not restrict any right granted by the MIT License to the code itself.diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex a733d2baa..4031d710e 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -31,15 +31,17 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| SAST | README badge (CodeQL) | `codeql.yml` | GATED | - || Dependency CVE scanning | (implied by security) | `security-audit.yml` | GATED | - || OpenSSF Scorecard | README badge L13 | `scorecard.yml` | GATED | - |-| Container image / IaC / secret scanning (Trivy/checkov/tfsec/gitleaks/Semgrep) | (implied by security) | none | NO GATE | Phase 2 |+| Container image / IaC / secret scanning (Trivy/checkov/tfsec/gitleaks/Semgrep) | (implied by security) | `security.yml` (claim-matrix ratchet HARD; gitleaks/Semgrep/Trivy/checkov/tfsec observe) | PARTIAL (matrix ratchet enforced; secret + code/IaC/container scanners report-and-ratchet, allowlist at `.security/allowlist.yml` / `.gitleaksignore`; GitHub push-protection is the always-on hard secret gate) | Phase 2 || Signed / attested release artifacts | (implied by "run next to crown jewels") | `release.yml` (SPDX source SBOM), `build-extensions.yml` (extension cosign) | PARTIAL (images unsigned; no per-image SBOM/SLSA) | Phase 2 |-| Insecure defaults hard-fail in production | (implied by self-host) | none (warn-only) | NO GATE | Phase 2 |+| Insecure defaults hard-fail in production | (implied by self-host) | `ci.yml` api tests (`test_security_defaults.py::test_enforce_*`; `enforce_secure_defaults` raises at boot in production) | GATED | - || OpenAPI stability for 3 SDKs + MCP | (implied by SDKs) | `check-openapi.yml` (drift only) | NO GATE (no breaking-change semantics) | Phase 11 |## Summary-- GATED: 9+- GATED: 10- PARTIAL: 14-- NO GATE: 4 (Phases 1.1/1.3/1.4 moved prompt-injection, non-Postgres isolation, and no-data-exfiltration from NO GATE to PARTIAL)+- NO GATE: 3 (Phase 2 moved insecure-defaults-hard-fail to GATED and secret/IaC/container scanning to PARTIAL; remaining NO GATE close in Phases 4/10/11)++The ratchet is enforced by `scripts/check_claim_gate_matrix.py` (wired into `security.yml`): the NO GATE count may only decrease.The Definition of Done requires zero `NO GATE` and zero unclosed `PARTIAL`. Each row's "Closes in" column is the binding commitment.diff --git a/docs/operations/verifying-releases.md b/docs/operations/verifying-releases.mdnew file mode 100644index 000000000..50cfae93b--- /dev/null+++ b/docs/operations/verifying-releases.md@@ -0,0 +1,51 @@+# Verifying AiSOC Releases++You run AiSOC images next to your crown jewels, so you should verify what you download. This page documents how to check release integrity today and what stronger attestations are landing.++## Available today++### Source tarball checksums (`release.yml`)++Every tagged release publishes the source tarball plus SHA-256 and SHA-512 checksums as release assets.++```bash+# Download the tarball and checksums from the release, then:+sha256sum -c aisoc-<version>.tar.gz.sha256+sha512sum -c aisoc-<version>.tar.gz.sha512+```++### Source SBOM (`release.yml`)++Each release attaches an SPDX SBOM for the source tree (generated by `anchore/sbom-action`). Import it into your SCA tooling to inventory dependencies.++### Browser-extension signatures (`build-extensions.yml`)++The osquery browser-extension binaries are signed with `cosign` (keyless / OIDC) on `ext-v*` tags. Verify with:++```bash+cosign verify-blob \+ --certificate <artifact>.pem \+ --signature <artifact>.sig \+ --certificate-identity-regexp 'https://github.com/beenuar/AiSOC/.*' \+ --certificate-oidc-issuer https://token.actions.githubusercontent.com \+ <artifact>+```++## Landing (Phase 2 continuation)++The following are tracked to complete the signed-and-attested supply chain for the container images (today the 12 GHCR service images are pushed unsigned):++- **CycloneDX SBOM per image**, attached to each `ghcr.io/beenuar/*` image.+- **`cosign` image signatures** (keyless OIDC) for every service image, verifiable with:++ ```bash+ cosign verify \+ --certificate-identity-regexp 'https://github.com/beenuar/AiSOC/.*' \+ --certificate-oidc-issuer https://token.actions.githubusercontent.com \+ ghcr.io/beenuar/aisoc-api:<version>+ ```++- **SLSA v1 build provenance** attestation per image, verifiable with `slsa-verifier`.+- **SHA-pinned GitHub Actions** across all workflows (currently pinned by tag).++Progress and the enforcing gates are tracked in [`docs/audit/CLAIM_TO_GATE_MATRIX.md`](../audit/CLAIM_TO_GATE_MATRIX.md) and `ROADMAP.md`.diff --git a/scripts/check_claim_gate_matrix.py b/scripts/check_claim_gate_matrix.pynew file mode 100644index 000000000..d7ad5e778--- /dev/null+++ b/scripts/check_claim_gate_matrix.py@@ -0,0 +1,108 @@+#!/usr/bin/env python3+"""Enforce the claim-to-gate matrix (Phase 2).++`docs/audit/CLAIM_TO_GATE_MATRIX.md` maps every marketing/capability claim to+the CI job that proves it, or `NO GATE`. The Definition of Done requires zero+`NO GATE` rows. Until we get there, this gate is a **ratchet**: the number of+`NO GATE` rows may only decrease. A PR that adds a new claim without a gate+(or removes a gate) fails.++Usage:+ python3 scripts/check_claim_gate_matrix.py # enforce ratchet+ python3 scripts/check_claim_gate_matrix.py --print # print counts only++Exit codes: 0 ok, 1 regression (NO GATE increased) or malformed matrix.+"""++from __future__ import annotations++import argparse+import re+import sys+from pathlib import Path++ROOT = Path(__file__).resolve().parent.parent+MATRIX = ROOT / "docs" / "audit" / "CLAIM_TO_GATE_MATRIX.md"++# Ratchet baseline: the number of NO GATE rows allowed. Lower this as phases+# close gaps; never raise it. Phase 1 closed injection / non-Postgres isolation+# / no-exfiltration; Phase 2 closed insecure-defaults + secret/IaC scanning.+# Remaining NO GATE rows close in Phases 4 / 10 / 11.+MAX_NO_GATE = 3+++def _parse_status_rows(text: str) -> list[str]:+ """Return the Status cell of every data row in the claim-to-gate table."""+ lines = text.splitlines()+ header_idx = None+ status_col = None+ for i, line in enumerate(lines):+ if line.strip().startswith("|") and "Status" in line and "Claim" in line:+ cols = [c.strip() for c in line.strip().strip("|").split("|")]+ try:+ status_col = cols.index("Status")+ except ValueError:+ continue+ header_idx = i+ break+ if header_idx is None or status_col is None:+ raise ValueError("could not locate the claim-to-gate table header (Claim ... Status)")++ statuses: list[str] = []+ # data rows start after the header separator (|---|---|...)+ for line in lines[header_idx + 2 :]:+ s = line.strip()+ if not s.startswith("|"):+ break # table ended+ if re.match(r"^\|[\s:|-]+\|?$", s):+ continue # separator+ cols = [c.strip() for c in s.strip("|").split("|")]+ if len(cols) <= status_col:+ continue+ statuses.append(cols[status_col])+ return statuses+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--print", dest="print_only", action="store_true")+ parser.add_argument("--max-no-gate", type=int, default=MAX_NO_GATE)+ args = parser.parse_args()++ if not MATRIX.exists():+ print(f"ERROR: {MATRIX} not found", file=sys.stderr)+ return 1++ try:+ statuses = _parse_status_rows(MATRIX.read_text(encoding="utf-8"))+ except ValueError as exc:+ print(f"ERROR: {exc}", file=sys.stderr)+ return 1++ if not statuses:+ print("ERROR: no claim rows parsed from the matrix", file=sys.stderr)+ return 1++ no_gate = sum(1 for s in statuses if "NO GATE" in s.upper())+ gated = sum(1 for s in statuses if s.upper().startswith("GATED"))+ partial = sum(1 for s in statuses if s.upper().startswith("PARTIAL"))++ print(f"claim-to-gate matrix: {len(statuses)} rows — {gated} GATED, {partial} PARTIAL, {no_gate} NO GATE")++ if args.print_only:+ return 0++ if no_gate > args.max_no_gate:+ print(+ f"ERROR: NO GATE rows increased to {no_gate} (ratchet ceiling {args.max_no_gate}). "+ "Every claim needs a CI gate — add the gate or delete the claim.",+ file=sys.stderr,+ )+ return 1++ print(f"OK: NO GATE rows ({no_gate}) within ratchet ceiling ({args.max_no_gate}).")+ return 0+++if __name__ == "__main__":+ raise SystemExit(main())diff --git a/services/api/app/core/config.py b/services/api/app/core/config.pyindex 6be142355..ccb067e80 100644--- a/services/api/app/core/config.py+++ b/services/api/app/core/config.py@@ -752,4 +752,32 @@ def warn_if_insecure_defaults(s: Settings | None = None) -> list[str]:return msgs+def is_production(env: str | None) -> bool:+ """True only for the literal ``production`` environment."""+ return (env or "").strip().lower() == "production"+++class InsecureProductionDefaultsError(RuntimeError):+ """Raised at boot when insecure defaults remain in a production deploy."""+++def enforce_secure_defaults(s: Settings | None = None) -> list[str]:+ """Warn everywhere; **hard-fail the boot** in production (Phase 2).++ ``warn_if_insecure_defaults`` only warns, which means a production deploy+ can silently start with ``changeme``/placeholder secrets. This wrapper is+ the boot-time gate: it emits the same warnings and then, if+ ``ENVIRONMENT=production`` and any insecure default remains, raises so the+ container crash-loops loudly instead of serving with a known-bad secret.++ Returns the (empty, in a healthy prod) list of messages so callers/tests+ can assert on it.+ """+ s = s or settings+ msgs = warn_if_insecure_defaults(s)+ if is_production(s.ENVIRONMENT) and msgs:+ raise InsecureProductionDefaultsError("Refusing to boot in production with insecure defaults:\n - " + "\n - ".join(msgs))+ return msgs++settings = get_settings()diff --git a/services/api/app/main.py b/services/api/app/main.pyindex ad8240328..5fccef652 100644--- a/services/api/app/main.py+++ b/services/api/app/main.py@@ -18,7 +18,7 @@ from app.api.v1.router import api_routerfrom app.auth.oidc import router as oidc_routerfrom app.auth.saml import router as saml_routerfrom app.core.airgap import airgap_status-from app.core.config import is_dev_env, settings, warn_if_insecure_defaults+from app.core.config import enforce_secure_defaults, is_dev_env, settingsfrom app.core.cors import build_cors_kwargsfrom app.core.logging import configure_loggingfrom app.core.scheduler_lock import scheduler_lock@@ -88,8 +88,9 @@ async def lifespan(app: FastAPI) -> AsyncGenerator[None, None]:# Surface insecure defaults (placeholder SECRET_KEY, missing METRICS_TOKEN# outside dev, plugin trust mode disabled outside dev) at the top of the- # log stream so operators see them before anything else.- warn_if_insecure_defaults(settings)+ # log stream so operators see them before anything else. In production this+ # hard-fails the boot rather than serving with a known-bad secret (Phase 2).+ enforce_secure_defaults(settings)# Create all database tables (dev only; use Alembic migrations in prod).# We keep this narrowly scoped to the canonical ``"development"`` labeldiff --git a/services/api/tests/test_security_defaults.py b/services/api/tests/test_security_defaults.pyindex ffbe3bb6f..84db85184 100644--- a/services/api/tests/test_security_defaults.py+++ b/services/api/tests/test_security_defaults.py@@ -16,7 +16,9 @@ from __future__ import annotationsimport pytestfrom app.core.config import (INSECURE_SECRET_KEY_DEFAULTS,+ InsecureProductionDefaultsError,Settings,+ enforce_secure_defaults,warn_if_insecure_defaults,)from fastapi import FastAPI@@ -51,6 +53,29 @@ def _make_settings(**overrides) -> Settings:return Settings(_env_file=None, **base)+# ─── enforce_secure_defaults (Phase 2 hard-fail) ───────────────────────────+++def test_enforce_raises_in_prod_with_insecure_default():+ bad = next(iter(INSECURE_SECRET_KEY_DEFAULTS))+ s = _make_settings(ENVIRONMENT="production", SECRET_KEY=bad)+ with pytest.raises(InsecureProductionDefaultsError):+ enforce_secure_defaults(s)+++def test_enforce_clean_prod_does_not_raise():+ s = _make_settings() # clean production baseline+ assert enforce_secure_defaults(s) == []+++def test_enforce_non_prod_insecure_does_not_raise():+ bad = next(iter(INSECURE_SECRET_KEY_DEFAULTS))+ s = _make_settings(ENVIRONMENT="staging", SECRET_KEY=bad)+ # Non-production: warns (non-empty), but never hard-fails the boot.+ msgs = enforce_secure_defaults(s)+ assert msgs # the warning still fired++# ─── warn_if_insecure_defaults ─────────────────────────────────────────────