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
fix(ingest): authenticate /v1/ingest and derive the tenant from the credential
Beenu Arorac3bbe9038478
diff --git a/.env.example b/.env.exampleindex f612be8a6..d05c446fa 100644--- a/.env.example+++ b/.env.example@@ -263,8 +263,16 @@ NEXT_PUBLIC_WS_URL=ws://localhost:8086## Leave blank for local `docker compose up` (AISOC_DEV_MODE covers it). Set a# real value for anything network-reachable.+#+# `ingest` and `connectors` also use it, and there AISOC_DEV_MODE does NOT+# cover it: POST /v1/ingest is a write into tenant-owned data and has no+# dev-mode shortcut. Set this on both services to let the connector-poll+# path push; a direct curl/script push uses a per-tenant token from+# `make ingest-token` instead and needs nothing here. See+# apps/docs/docs/operations/ingest-authentication.md.AISOC_SERVICE_TOKEN=# Optional per-service overrides, if you'd rather not share one secret:# AISOC_PURPLE_TEAM_SERVICE_TOKEN=# AISOC_HONEYTOKENS_SERVICE_TOKEN=# AISOC_UEBA_SERVICE_TOKEN=+# AISOC_INGEST_SERVICE_TOKEN=diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex a949a318e..d3a43881c 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -435,6 +435,16 @@ jobs:run: python3 scripts/check_connector_profiles.py --self-test- name: Connector profile drift gaterun: python3 scripts/check_connector_profiles.py+ # The same shape one layer over: an inbox template that ships has to be+ # mintable, and a mintable id has to have a template to apply. Both+ # directions, because only one of them was ever checked informally and+ # three templates — ai-runtime, ai-finding and k8s-audit — shipped,+ # were named in the AI SDK's own setup instructions and in the+ # Kubernetes connector docs, and could not be minted at all.+ - name: Inbox template drift gate — self-test+ run: python3 scripts/check_inbox_templates.py --self-test+ - name: Inbox template drift gate+ run: python3 scripts/check_inbox_templates.py# Same question one layer up: a connector name has to reach a profile,# and a model name has to reach a gateway that defines it. AI triage# could not reach a model in the default deployment becausediff --git a/.github/workflows/golden-pipeline.yml b/.github/workflows/golden-pipeline.ymlindex e33536bf3..de01b939f 100644--- a/.github/workflows/golden-pipeline.yml+++ b/.github/workflows/golden-pipeline.yml@@ -131,6 +131,34 @@ jobs:exit 1}+ # /v1/ingest/batch is authenticated, so the pipeline test has to hold a+ # credential like any other caller. Minted through the shipped command+ # rather than inserted into Postgres, so this step also covers the path+ # an operator follows.+ - name: Mint the ingest credential the pipeline test needs+ run: |+ set -euo pipefail+ token="$(docker compose run --rm -T api python -m app.scripts.mint_ingest_token --quiet)"+ if [ -z "$token" ]; then+ echo "::error::mint_ingest_token printed nothing"+ exit 1+ fi+ echo "::add-mask::$token"+ echo "AISOC_INGEST_TOKEN=$token" >> "$GITHUB_ENV"++ # Re-running must return the same token rather than leaving a trail of+ # live credentials nobody revokes. `make smoke` calls this on every run.+ - name: Minting is idempotent+ run: |+ set -euo pipefail+ again="$(docker compose run --rm -T api python -m app.scripts.mint_ingest_token --quiet)"+ echo "::add-mask::$again"+ if [ "$again" != "$AISOC_INGEST_TOKEN" ]; then+ echo "::error::a second mint returned a different token"+ exit 1+ fi+ echo "confirmed: a second mint reused the existing push token"+- name: Golden pipeline — one real event end to endrun: python3 tests/e2e/golden_pipeline/run_golden_pipeline.pydiff --git a/.github/workflows/security.yml b/.github/workflows/security.ymlindex cfa663a37..8b953d3a0 100644--- a/.github/workflows/security.yml+++ b/.github/workflows/security.yml@@ -4,15 +4,24 @@ name: Security# (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.+# - HARD gates (fail the build):+# * the claim-to-gate matrix ratchet — a new ungated marketing claim+# must never merge;+# * gitleaks — the whole tree was triaged and every finding is either+# fixed or recorded in .gitleaksignore with a written reason, so a+# new finding is genuinely new;+# * Trivy — HIGH/CRITICAL with a fix available, currently zero.+# - OBSERVE gates (report, do not fail yet): Semgrep, checkov, tfsec.+# These are not observe-mode because nobody has looked. They were run+# against this tree and the counts are: Semgrep 92 (35 at ERROR),+# checkov 91 failed checks under infra/terraform, tfsec 32 (7 CRITICAL,+# 5 HIGH). Blocking on 215 untriaged findings would red every pull+# request on day one and the first response would be to turn the gate+# back off, so each needs its own triage pass first. The count is stated+# here rather than left as "we'll get to it" so the size of the+# remaining work is visible.+#+# GitHub native push-protection remains the always-on hard secret gate.on:pull_request:@@ -37,40 +46,72 @@ jobs:- name: Enforce no new NO GATE rowsrun: python3 scripts/check_claim_gate_matrix.py- # ── OBSERVE: secret scan (report; ratchet to blocking after triage) ───────+ # ── HARD: secret scan ─────────────────────────────────────────────────────secret-scan:- name: Secret scan (gitleaks, observe)+ name: Secret scan (gitleaks)runs-on: ubuntu-lateststeps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7- # `continue-on-error` also covers the install: this is an OBSERVE gate, so- # a flaky release download must not turn it into a hard red. Without it a- # transient blip here fails the whole job, which is what happened on #614- # (install exited 2, the scan step never ran, and the check reported- # failure as if a secret had been found).+ # No `continue-on-error`, on this step or the next. It used to be on+ # both, and the pairing was the defect rather than the fix: #614 had it+ # on the scan but not the install, so a flaky download reported a hard+ # failure with nothing scanned; the correction put it on the install+ # too, which turned the same blip into a green check with nothing+ # scanned. For a blocking gate neither is acceptable — an install that+ # fails has to fail the job, loudly, because "clean" and "did not run"+ # must never look the same.- name: Install gitleaks- continue-on-error: truerun: |set -euo pipefailVERSION=8.21.2# --fail so an HTTP error is not silently written into the tarball and# surfaced later as a confusing `tar` error; --retry for the blips.- curl -sSL --fail --retry 3 --retry-delay 5 --retry-all-errors \+ curl -sSL --fail --retry 5 --retry-delay 5 --retry-all-errors \"https://github.com/gitleaks/gitleaks/releases/download/v${VERSION}/gitleaks_${VERSION}_linux_x64.tar.gz" \-o /tmp/gitleaks.tgztar -xzf /tmp/gitleaks.tgz -C /tmp gitleakssudo mv /tmp/gitleaks /usr/local/bin/gitleaks- gitleaks version- - name: Scan working tree (respects .gitleaksignore)- continue-on-error: true+ installed="$(gitleaks version)"+ echo "installed gitleaks $installed"+ # Pinned: a silently different version scans with different rules,+ # and the allow-list is fingerprinted against this one.+ if [ "$installed" != "$VERSION" ]; then+ echo "::error title=secret-scan::expected gitleaks $VERSION, got '$installed'"+ exit 1+ fi++ # A clean result only means something if the scanner is reading this+ # tree. With the allow-list moved aside the triaged findings must+ # reappear; if they do not, gitleaks is scanning nothing and the run+ # below would report clean for the wrong reason. This uses the repo's+ # own known-positive corpus rather than a planted secret, so there is+ # no synthetic credential in the tree and nothing to clean up.+ - name: The scanner is actually scanningrun: |- if ! command -v gitleaks >/dev/null 2>&1; then- echo "::warning title=secret-scan::gitleaks install failed — working tree NOT scanned this run"- exit 0+ set -euo pipefail+ mv .gitleaksignore "${RUNNER_TEMP}/.gitleaksignore"+ status=0+ gitleaks dir . --redact --exit-code 1 --no-banner >/dev/null 2>&1 || status=$?+ mv "${RUNNER_TEMP}/.gitleaksignore" .gitleaksignore+ if [ "$status" -eq 0 ]; then+ echo "::error title=secret-scan::gitleaks found nothing with the allow-list removed — it is not scanning this tree, so a clean scan proves nothing"+ exit 1fi- gitleaks dir . --redact --exit-code 1 --no-banner+ echo "confirmed: the scan reads this tree and the allow-list is load-bearing"++ # Blocking. A finding here is either a real secret — rotate it and+ # remove it from the source — or a false positive that belongs in+ # .gitleaksignore with a written reason. Re-adding continue-on-error+ # is not one of the two options.+ - name: Scan working tree (respects .gitleaksignore)+ run: gitleaks dir . --redact --exit-code 1 --no-banner# ── OBSERVE: SAST beyond CodeQL ───────────────────────────────────────────+ #+ # 92 findings against this tree (35 ERROR, 51 WARNING, 3 MEDIUM, 3 INFO),+ # measured with semgrep 1.86.0 and the five configs below. Too many to+ # block on before they are triaged, and `--error` fails on any of them, so+ # this stays report-only with the number written down.semgrep:name: Semgrep (observe)runs-on: ubuntu-latest@@ -93,22 +134,48 @@ jobs:--exclude plans/ \services/ apps/ packages/ scripts/- # ── OBSERVE: filesystem vuln scan (complements dependency SCA) ────────────+ # ── HARD: filesystem vuln scan (complements dependency SCA) ───────────────trivy-fs:- name: Trivy filesystem (observe)+ name: Trivy filesystemruns-on: ubuntu-lateststeps:- uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7- - name: Install & run Trivy (report-only)- continue-on-error: true+ # Still a pinned binary fetched in a `run:` step rather than the+ # marketplace action: the action's version tags proved unreliable and+ # this is the form that has stayed working.+ #+ # `set -e` matters now that this blocks — the previous `set -uo+ # pipefail` let a failed download fall through to a `trivy` that was+ # not there, and with --exit-code 0 the job reported success either+ # way. Install failure must fail the job.+ - name: Install Trivyrun: |- set -uo pipefail+ set -euo pipefailVERSION=0.55.2- curl -sSL "https://github.com/aquasecurity/trivy/releases/download/v${VERSION}/trivy_${VERSION}_Linux-64bit.tar.gz" -o /tmp/trivy.tgz+ curl -sSL --fail --retry 5 --retry-delay 5 --retry-all-errors \+ "https://github.com/aquasecurity/trivy/releases/download/v${VERSION}/trivy_${VERSION}_Linux-64bit.tar.gz" \+ -o /tmp/trivy.tgztar -xzf /tmp/trivy.tgz -C /tmp trivy- /tmp/trivy fs --severity HIGH,CRITICAL --ignore-unfixed --skip-dirs plans --exit-code 0 .+ /tmp/trivy --version++ # Blocking, at zero findings as of this change. HIGH and CRITICAL only,+ # and only where a fixed version exists — an unfixable advisory cannot+ # be actioned by the person whose pull request it reds, and blocking on+ # one would teach people to bypass the gate rather than fix anything.+ # A newly published CVE against a pinned dependency will red pull+ # requests until it is upgraded. That is the intended cost.+ - name: Scan filesystem for fixable HIGH/CRITICAL+ run: |+ set -euo pipefail+ /tmp/trivy fs --severity HIGH,CRITICAL --ignore-unfixed --skip-dirs plans --exit-code 1 .# ── OBSERVE: IaC misconfig scan ───────────────────────────────────────────+ #+ # checkov 3.2.x reports 91 failed checks against infra/terraform (164+ # passing); tfsec 1.28.x reports 32 findings there (7 CRITICAL, 5 HIGH,+ # 2 MEDIUM, 18 LOW). Both stay report-only until those are triaged —+ # promoting them now would red every pull request over pre-existing+ # infrastructure defaults that no single change introduced.iac-scan:name: IaC scan (checkov + tfsec, observe)runs-on: ubuntu-latestdiff --git a/.gitleaksignore b/.gitleaksignoreindex a9e544e5a..7473f98fe 100644--- a/.gitleaksignore+++ b/.gitleaksignore@@ -1,31 +1,115 @@# gitleaks ignore list#-# Each entry is a triaged false-positive. New entries MUST include a comment-# explaining why the match is benign. If a finding cannot be justified, do not-# add it here -- rotate the secret and remove the leak from the source.+# The secret scan is a BLOCKING gate. A finding that is not in this file reds+# the pull request, which is the point: a leaked credential must not be+# something a reviewer can scroll past.#-# Format: <absolute_or_repo_relative_path>:<rule-id>:<line>+# Each entry is a triaged false positive and MUST carry a comment explaining+# why the match is benign. If a finding cannot be justified, do not add it+# here — rotate the secret and remove it from the source.+#+# Format: <repo-relative-path>:<rule-id>:<start-line>+#+# Two things about that format, learned the hard way:+#+# * It is an exact fingerprint. A path on its own matches nothing — gitleaks+# compares the whole `path:rule:line` string — so there is no way to+# exempt a file wholesale from this file.+# * Because the line number is part of it, an edit that shifts a line in one+# of these files invalidates its entry and the scan goes red on a finding+# that was already triaged. Four of the six entries this list held before+# the gate became blocking had rotted exactly that way and were silently+# suppressing nothing. When that happens the fix is to correct the line+# number, never to drop the entry or relax the job.++# ── Detection content ─────────────────────────────────────────────────────++# detections/rule-ids.lock.json pins (category, slug) -> rule id so that+# regenerating the corpus cannot renumber an existing rule. The *keys* are+# rule slugs, and the detections that hunt for credential abuse are named+# after what they detect — "ai-prompt-contained-credential",+# "api-key-leak-in-request", "slack-token-exposed". The values are rule ids+# of the form det-application-085. Nothing in this file is a secret; the+# heuristic is firing on the slug, not on the value.+detections/rule-ids.lock.json:generic-api-key:4+detections/rule-ids.lock.json:generic-api-key:10+detections/rule-ids.lock.json:generic-api-key:15+detections/rule-ids.lock.json:generic-api-key:19+detections/rule-ids.lock.json:generic-api-key:22+detections/rule-ids.lock.json:generic-api-key:39+detections/rule-ids.lock.json:generic-api-key:53+detections/rule-ids.lock.json:generic-api-key:54+detections/rule-ids.lock.json:generic-api-key:65+detections/rule-ids.lock.json:generic-api-key:67+detections/rule-ids.lock.json:generic-api-key:82# Positive test fixture for the `jwt-none-alg` detection rule. This file is# *expected* to contain a JWT with `alg: none` because the detection engine# runs against it as ground truth.detections/fixtures/positive/jwt-none-alg.json:jwt:2-# Render IaC env-var keys (`AISOC_DISABLE_NEO4J`, `AISOC_DISABLE_QDRANT`).-# The generic-api-key rule fires on the long key name; the value is "true",-# not a secret.-render.yaml:generic-api-key:70-render.yaml:generic-api-key:124--# Detection rule literal: `count_5min_per_ip_gt: 30` matches the heuristic.-# This is a rule definition, not a credential.-scripts/detection_specs_part3_application.py:generic-api-key:61+# osquery FIM fixtures. `node_key` is osquery's enrollment identifier and+# these carry the literal "abc123def456" — the field name is what matches.+# Each rule ships a positive and a negative fixture, hence four entries.+detections/fixtures/negative/fim-binary-dropped-writable-dir.json:generic-api-key:5+detections/fixtures/negative/fim-sensitive-file-modified.json:generic-api-key:5+detections/fixtures/positive/fim-binary-dropped-writable-dir.json:generic-api-key:5+detections/fixtures/positive/fim-sensitive-file-modified.json:generic-api-key:5# Detection rule positive sample: an `alg: none` JWT used to validate the# matching detection rule. Same fixture pattern as jwt-none-alg.json.scripts/detection_specs_part2.py:jwt:1111-# Pre-generated Fernet key used as a deterministic test default in-# `test_security_defaults.py`. Real deployments inject AISOC_CREDENTIAL_KEY-# as a secret at runtime; this value is *never* used outside tests.-services/api/tests/test_security_defaults.py:generic-api-key:34+# ── Infrastructure and CI ─────────────────────────────────────────────────++# Render IaC. The match is the YAML `key:` field of an env-var declaration+# and the value is the variable's *name* (`AISOC_DISABLE_NEO4J`,+# `AISOC_DISABLE_QDRANT`), not its value, which is the string "true".+render.yaml:generic-api-key:78+render.yaml:generic-api-key:132++# The disaster-recovery integration job encrypts its backup before uploading+# it, so it needs a key. The value is the AES-128 test vector published in+# FIPS-197 — a well-known constant rather than a secret — and it protects an+# ephemeral MinIO bucket in the runner that holds one probe table.+.github/workflows/integration.yml:generic-api-key:591++# Connector setup doc showing the curl an operator runs to check their Orca+# credential. The value is the literal placeholder "YOUR_TOKEN".+apps/docs/docs/connectors/orca.md:curl-auth-header:121++# ── Test fixtures ─────────────────────────────────────────────────────────++# The support-bundle redaction tests assert that credential shapes are+# stripped from a bundle before it leaves the host. Their corpus therefore+# has to contain things that look like credentials — a sample JWT, a PEM+# header, and AWS's own published example key AKIAIOSFODNN7EXAMPLE. A scanner+# matching them is the test data doing its job.+tests/test_support_bundle.py:jwt:44+tests/test_support_bundle.py:private-key:62+tests/test_support_bundle.py:generic-api-key:112++# Asserts that `api_key = '...'` in an LLM response is classified as a leak.+# The string is "sk-AbCdEf0123456789xyz", invented for the assertion.+services/agents/tests/test_llm_contract_extra.py:generic-api-key:185++# Pre-generated Fernet keys used as deterministic test defaults. Real+# deployments inject AISOC_CREDENTIAL_KEY as a secret at runtime; these values+# are never used outside tests.+services/api/tests/test_dev_mode_unification.py:generic-api-key:57+services/api/tests/test_dev_mode_unification.py:generic-api-key:283+services/api/tests/test_dev_mode_unification.py:generic-api-key:297+services/api/tests/test_dev_mode_unification.py:generic-api-key:348+services/api/tests/test_dev_mode_unification.py:generic-api-key:362+services/api/tests/test_security_defaults.py:generic-api-key:36++# Placeholder PEMs. Each is a PEM header and footer wrapped around the+# literal "XYZ" or "stub" — the vault test only checks that a nested field+# named private_key is encrypted, and the connector tests mock the signer.+services/api/tests/test_credential_vault.py:private-key:47+services/connectors/tests/connectors/test_oci.py:private-key:39+services/connectors/tests/connectors/test_snowflake.py:private-key:17++# Kubernetes audit connector config fixture; "tok-abcdef-1234567890" is an+# invented inbox token for a schema assertion.+services/connectors/tests/test_kubernetes_audit.py:generic-api-key:218diff --git a/CHANGELOG.md b/CHANGELOG.mdindex ea749a2ae..343ee55f1 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,94 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### BREAKING++- **`POST /v1/ingest` and `POST /v1/ingest/batch` now require a credential,+ and the tenant comes from the credential rather than from the+ `X-Tenant-ID` header.** The endpoint the README tells users to push+ telemetry to, and the one `make smoke` exercises, authenticated nothing:+ it read `X-Tenant-ID`, believed it, and wrote events for whatever tenant+ the caller named. Anyone who could reach the port could write alerts into+ any tenant by typing that tenant's UUID. Compose binds the port to+ `127.0.0.1`, which contains it locally, but ingesting real telemetry means+ exposing it and nothing said so at the moment the operator did. The+ comment at `services/ingest/internal/server/server.go` asserting that+ "`/v1/ingest` is token-authenticated per request" had been false since it+ was written; it is true now.++ Rather than invent a second mechanism this extends the one the service+ already had. `/v1/inbox/*` resolves a minted token from+ `tenant_inbox_tokens` to a tenant, with optional HMAC-SHA256 over+ `X-Signature`; `/v1/ingest` now resolves the same kind of token, pinned to+ a new `connector-push` template exactly as `/v1/inbox/cef` is pinned to+ `cef-syslog` — an inbox token is pasted into a third party's webhook+ config, so minting one for PagerDuty must not also hand PagerDuty a+ general ingest credential. A second shape covers AiSOC's own services:+ `services/connectors` polls on behalf of many tenants and cannot hold a+ per-tenant token, so it presents `AISOC_SERVICE_TOKEN` and declares the+ tenant on `X-Tenant-ID`, which is then checked against the tenants table+ before it becomes a scope.++ `X-Tenant-ID` is still read and is never authority. It is **intersected**+ with what the credential authorises, so naming an outside tenant narrows+ to nothing and is refused rather than reaching out — the same+ intersection-only rule `app/security/tenant_scope.py` already implements+ for the Python services, ported to Go in+ `services/ingest/internal/ingestauth`. There is no dev-mode bypass:+ `AISOC_DEV_MODE` does not reach this path, and an ingest service that+ cannot verify a credential answers 503 rather than accepting the write.++ **Every deployment must act.** Mint a push token per external pusher with+ `make ingest-token`, and set `AISOC_SERVICE_TOKEN` on both `ingest` and+ `connectors` if you use pull connectors — without it, connector polling is+ refused, loudly, at startup on one side and per request on the other. Full+ procedure: `apps/docs/docs/operations/ingest-authentication.md`.++### Added++- `make ingest-token` / `python -m app.scripts.mint_ingest_token` mints the+ push credential for a fresh deployment, the role `bootstrap_admin` plays+ for the console login. Idempotent — a second run returns the same token+ rather than leaving a trail of live credentials nobody revokes.+- `connector-push`, `ai-runtime`, `ai-finding` and `k8s-audit` are now+ mintable inbox templates. The last three already shipped as YAML and were+ named in the AI SDK's own setup instructions and in the Kubernetes+ connector docs, but none was in `ALLOWED_TEMPLATE_IDS`, so the documented+ setup for the AI-estate feature returned 400 and the templates were+ unreachable.+- `scripts/check_inbox_templates.py` compares shipped templates against+ mintable ids **in both directions**, plus the console catalog, and carries+ a `--self-test` that injects drift in each direction and requires the gate+ to catch it. A one-directional check would have printed OK throughout the+ defect above.+- The golden pipeline asserts that an unauthenticated push is refused, not+ only that an authenticated one succeeds — the happy path would go on+ passing if authentication were removed.+- `/v1/ingest` now bounds the request body (`INGEST_MAX_BODY_BYTES`, 10 MiB+ default). `MAX_BATCH_SIZE` only counts events after the payload is+ decoded, so nothing bounded the decode itself.++### Changed++- **gitleaks and Trivy are blocking gates.** All five scanners in+ `security.yml` carried `continue-on-error`, so a new finding never redded+ a pull request. Gitleaks found 35 findings on its first real run; every+ one was triaged and recorded in `.gitleaksignore` with a written reason —+ detection rule-id maps, osquery and redaction test fixtures, placeholder+ PEMs, a published AWS example key, a FIPS-197 test vector, and a+ `YOUR_TOKEN` doc placeholder. Four of the six entries the allow-list+ already held had rotted through line drift and were suppressing nothing.+ Trivy reports zero fixable HIGH/CRITICAL and blocks at that.++ Semgrep (92 findings, 35 at ERROR), checkov (91 failed checks) and tfsec+ (32, of which 7 CRITICAL) stay in observe mode. The counts are now written+ into the workflow so the remaining work is visible rather than implied.++ The secret-scan job also fails when the scanner cannot install, instead of+ reporting clean, and proves it is reading the tree before trusting a clean+ result: with the allow-list moved aside the triaged findings must+ reappear. "Clean" and "did not run" previously looked identical.+## [10.0.0] — 2026-09-25**Two ways for a control to be absent: not written, or written and notdiff --git a/Makefile b/Makefileindex e14a5716f..a092dc749 100644--- a/Makefile+++ b/Makefile@@ -24,7 +24,7 @@ PROFILE ?=PROFILE_ARG := $(if $(PROFILE),--profile $(PROFILE),).PHONY: help install up up-full down restart status doctor smoke demo logs clean \- bootstrap test test-unit test-integration test-e2e stats papers \+ bootstrap ingest-token test test-unit test-integration test-e2e stats papers \papers-install demo-scripthelp:@@ -34,6 +34,7 @@ help:@echo " make up Start the CORE stack (postgres, kafka, ingest, fusion, api, web)"@echo " make up-full Start CORE plus lake, graph, vector, search and enrichment"@echo " make bootstrap Create the first administrator and print its password once"+ @echo " make ingest-token Mint the credential POST /v1/ingest/batch requires"@echo " make smoke Push one real event through the pipeline and check it becomes an alert"@echo " make doctor Diagnose the deployment and say what to fix"@echo ""@@ -163,10 +164,25 @@ status:doctor:@./scripts/doctor.sh $(if $(filter full,$(PROFILE)),--full,)+# The credential POST /v1/ingest/batch requires. Idempotent: an existing+# active push token is returned rather than a second one being minted, so+# `smoke` can call it on every run. `make ingest-token ARGS=--rotate`+# replaces it.+ingest-token:+ @$(COMPOSE) run --rm -T api python -m app.scripts.mint_ingest_token $(ARGS)+# The golden pipeline. One real event, through the real spine, observed from# outside. This is the only claim of "it works" the project makes.+#+# The token is minted first because ingest is authenticated: the endpoint+# takes a credential that carries its own tenant rather than a header+# naming one. Minting here keeps `make smoke` a single command.smoke:- @$(PYTHON) tests/e2e/golden_pipeline/run_golden_pipeline.py+ @token="$$($(COMPOSE) run --rm -T api python -m app.scripts.mint_ingest_token --quiet)" || { \+ echo "Could not mint an ingest token — is the stack up? Try 'make doctor'."; \+ exit 1; \+ }; \+ AISOC_INGEST_TOKEN="$$token" $(PYTHON) tests/e2e/golden_pipeline/run_golden_pipeline.pydemo:@echo "Loading synthetic demo data. Every row is tagged is_synthetic=true"diff --git a/README.md b/README.mdindex d4e291f01..6e9411000 100644--- a/README.md+++ b/README.md@@ -84,11 +84,13 @@ make demo## Connect real data-Two ways in. Push, from anything that can make an HTTP request:+Two ways in. Push, from anything that can make an HTTP request. The tenant+comes from the credential, not from a header — mint one with+`make ingest-token` ([how it works](https://beenuar.github.io/AiSOC/docs/operations/ingest-authentication)):```bashcurl -X POST http://localhost:8081/v1/ingest/batch \- -H 'Content-Type: application/json' -H 'X-Tenant-ID: <tenant>' \+ -H 'Content-Type: application/json' -H "Authorization: Bearer $AISOC_INGEST_TOKEN" \-d '{"connector_id":"edr-1","connector_type":"crowdstrike","source_format":"json","events":[{"severity":"high","title":"Encoded PowerShell from Office","host":"WIN-FIN-01","process_name":"powershell.exe"}]}'diff --git a/apps/docs/docs/operations/ingest-authentication.md b/apps/docs/docs/operations/ingest-authentication.mdnew file mode 100644index 000000000..1a7cdcdec--- /dev/null+++ b/apps/docs/docs/operations/ingest-authentication.md@@ -0,0 +1,179 @@+---+sidebar_position: 3+title: Ingest authentication+description: POST /v1/ingest now requires a credential that carries its own tenant. What to do on upgrade, how to mint a token, and how the two credential shapes differ.+---++# Ingest authentication++`POST /v1/ingest` and `POST /v1/ingest/batch` require a credential. The+credential determines which tenant the events are written for; the+`X-Tenant-ID` header no longer does.++:::danger Upgrading an existing deployment++**This is a breaking change and it needs an action from you.** Before this+release the endpoint authenticated nothing. It read `X-Tenant-ID`, believed+it, and wrote events for whatever tenant the caller named — so any client+that could reach the port could write alerts into any tenant, including ones+it had no relationship with.++After upgrading, every existing pusher gets `401` until it presents a+credential. Jump to [What to do on upgrade](#what-to-do-on-upgrade).++:::++## The two credential shapes++Which one you want depends on whether the caller acts for one tenant or+many.++| | Tenant push token | Service token |+|---|---|---|+| Credential | `aitnb_…`, a row in `tenant_inbox_tokens` minted with the `connector-push` template | `AISOC_SERVICE_TOKEN`, a shared secret |+| Authorises | exactly the tenant the token belongs to | any tenant, but one per request and only if it exists |+| Tenant comes from | the token itself | the `X-Tenant-ID` header, checked against the tenants table |+| Use it for | curl, scripts, agents, a single customer's forwarder | AiSOC's own services — `connectors` polls on behalf of every tenant it manages |++Both are presented the same way:++```+Authorization: Bearer <credential>+```++`X-Inbox-Token: <credential>` also works, for forwarders that cannot set an+`Authorization` header. This is the same mechanism and the same header+shapes as the inbox webhooks at `/v1/inbox/*`.++### The tenant header is intersected, never trusted++`X-Tenant-ID` is still accepted, and for a service token it is required —+that is how a trusted service says which tenant it is acting for. But it is+only ever **intersected** with what the credential authorises:++* A push token naming its own tenant: allowed.+* A push token naming a different tenant: `403`. The scope narrows to+ nothing, and nothing means refuse — not "fall back to the token's own+ tenant", and certainly not "reach into the named one".+* A service token naming a tenant that does not exist or is deactivated:+ `403`.+* A service token naming no tenant at all: `403`. An absent scope is+ refused rather than widened to every tenant.+* No credential: `401`.++## Minting a push token++From a shell on the deployment:++```bash+make ingest-token+```++or directly:++```bash+docker compose run --rm api python -m app.scripts.mint_ingest_token+```++Re-running returns the **same** token rather than minting a second one, so+it is safe to call from a script; `make ingest-token ARGS=--rotate` revokes+the current one and issues a replacement. `--tenant <id-or-slug>` picks the+tenant when the deployment has more than one.++From the console, the same token is available under **Settings →+Connectors → Push (any vendor)** as **Direct ingest API**, or over the API:++```bash+curl -X POST https://<your-aisoc-host>/api/v1/inbox/tokens \+ -H "Authorization: Bearer <your console token>" \+ -H 'Content-Type: application/json' \+ -d '{"template_id":"connector-push","label":"EDR forwarder"}'+```++### Pushing with it++```bash+curl -X POST http://localhost:8081/v1/ingest/batch \+ -H 'Content-Type: application/json' \+ -H "Authorization: Bearer $AISOC_INGEST_TOKEN" \+ -d '{"connector_id":"edr-1","connector_type":"crowdstrike","source_format":"json",+ "events":[{"severity":"high","title":"Encoded PowerShell from Office",+ "host":"WIN-FIN-01","process_name":"powershell.exe"}]}'+```++### Signing the body++Mint the token with an `hmac_secret` and the ingest service additionally+requires an `X-Signature: sha256=<hex>` header over the raw request body,+verified in constant time. Same contract as the inbox webhooks, so a+forwarder already signing for `/v1/inbox/*` needs no new code.++## Why `connector-push` specifically++A token minted for `pagerduty` or `cloudflare-logpush` will be refused with+`403` even though it belongs to the right tenant. That is deliberate, and it+mirrors how `/v1/inbox/cef` only accepts a `cef-syslog` token.++An inbox token is pasted into a third party's webhook configuration — once+you have minted one for PagerDuty, PagerDuty holds it. Without the pin, that+vendor could replay its own URL's token against `/v1/ingest` and write+arbitrary connector events for your tenant. Minting a `connector-push` token+is a separate, deliberate act.++## What to do on upgrade++**1. Inventory what pushes to `/v1/ingest`.** Anything that is not an AiSOC+service — a SIEM forwarder, a cron job, a homegrown agent — needs a push+token. Mint one per pusher so you can revoke them independently.++**2. Set `AISOC_SERVICE_TOKEN` if you use pull connectors.** The+`connectors` service polls vendor APIs and pushes the results to+`/v1/ingest`, so it needs the service credential. The same value must be set+on **both** services:++```bash+# .env+AISOC_SERVICE_TOKEN=$(openssl rand -base64 32)+```++`docker-compose.yml` already passes it to both. If it is unset, connector+polling is refused and both services say so: `connectors` warns at startup+that every push will be refused, and `ingest` logs which credential sources+it has. Use `AISOC_INGEST_SERVICE_TOKEN` to give this hop its own secret.++**3. Check the startup log.** The ingest service reports what it can verify:++```+ingest: /v1/ingest requires an authenticated, tenant-scoped credential+ minted_tokens=true service_token=true+```++If it instead logs at error that no credential source is configured, it will+refuse every push. That happens when `DATABASE_DSN` is unset (so minted+tokens cannot be resolved) **and** no service token is set.++**4. There is no opt-out.** `AISOC_DEV_MODE` does not reach this path and no+flag disables it. An ingest service that cannot verify a credential answers+`503` rather than accepting the write unchecked.++## Other ingest routes++| Route | Credential |+|---|---|+| `/v1/ingest`, `/v1/ingest/batch` | push token or service token, as above |+| `/v1/inbox/{token}`, `/v1/inbox/email/{token}` | the token in the URL, optional HMAC |+| `/v1/inbox/cef`, `/v1/inbox/hec` | inbox token in `Authorization`, pinned to the `cef-syslog` / `splunk-hec` template |+| `/v1/ingest/k8s-audit/{tenant_id}` | `X-AiSOC-K8s-Token` shared secret; returns `503` until `K8S_AUDIT_SHARED_SECRET` is set |++## Troubleshooting++| Response | Meaning |+|---|---|+| `401 missing ingest credential` | No `Authorization` or `X-Inbox-Token` header. |+| `401 unrecognised ingest credential` | The token does not resolve. Check for a copy/paste truncation, or mint a new one. |+| `401 this ingest token has been revoked` | Rotated or revoked. Mint a replacement. |+| `403 this token was minted for the "…" template` | Right tenant, wrong template — mint one with `connector-push`. |+| `403 requested tenant is outside the credential's authorised scope` | The `X-Tenant-ID` header names a tenant this credential does not hold. |+| `403 a service token must declare the tenant it is acting for` | Service token with no `X-Tenant-ID`. |+| `403 declared tenant is unknown or inactive` | The declared tenant is not in the tenants table, or `is_active` is false. |+| `503 ingest authentication is not configured` | Neither `DATABASE_DSN` nor `AISOC_SERVICE_TOKEN` is set on the ingest service. |diff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.tsindex 19801d9a3..b0d2b375e 100644--- a/apps/docs/sidebars.ts+++ b/apps/docs/sidebars.ts@@ -184,6 +184,7 @@ const sidebars: SidebarsConfig = {"compliance/fips-posture","operations/credentials","operations/secrets",+ "operations/ingest-authentication","operations/airgap","operations/air-gapped","operations/llm-gateway",diff --git a/docker-compose.yml b/docker-compose.ymlindex ae41360d7..7cca2b0ee 100644--- a/docker-compose.yml+++ b/docker-compose.yml@@ -429,6 +429,14 @@ services:DATABASE_DSN: postgres://aisoc_app:${AISOC_APP_DB_PASSWORD:-aisoc_app_dev_secret}@postgres:5432/aisoc?sslmode=disableLOG_LEVEL: infoJWT_SECRET: dev_secret_key_change_in_production+ # /v1/ingest requires a credential. Two shapes are accepted: a+ # per-tenant push token minted with `make ingest-token` (resolved+ # through DATABASE_DSN above), and this shared service token, which+ # `connectors` presents when it polls on behalf of many tenants.+ # Empty by default — with it unset the connector-poll path is refused+ # and only minted tokens work. The same variable must be set on the+ # `connectors` service. See apps/docs/docs/operations/ingest-authentication.md.+ AISOC_SERVICE_TOKEN: ${AISOC_SERVICE_TOKEN:-}ATTCK_DATA_PATH: /app/data/enterprise-attack.json# Graph-at-ingest needs Neo4j, which is a `full`-profile service. It is# off in CORE and switched on by the `full` overlay. It used to bediff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.mdindex 6c9db5824..46da48e5a 100644--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md@@ -100,6 +100,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`| Envelope encryption: per-secret DEKs wrapped by a KEK in KMS | platform-threat-model.md (information disclosure) | `ci.yml` api job (`test_credential_vault_envelope.py`) — vault writes `vault:v2` when enabled, distinct DEK per secret, `vault:v1` rows still decrypt after the switch, a v2 row fails closed if envelope mode is later disabled, and an unrecognised mode refuses to boot rather than silently writing v1 | GATED | KMS backends beyond AWS are implemented against the same protocol but not integration-tested || Tenant offboarding erases data from every store | operations (data lifecycle) | `ci.yml` api job (`test_tenant_deletion.py`) — the Postgres table list is discovered from `information_schema` rather than hardcoded (14 of 72 tenant-scoped tables have no FK cascade, so a hardcoded list silently orphans them), the tenants row is deleted last, a failed satellite store rolls Postgres back and reports `complete: false`, and global MITRE reference nodes survive the graph purge | GATED | Neo4j MERGEs shared entities on `natural_key` with `tenant_id` as a property, so deleting by tenant can remove a node another tenant also referenced; it re-creates on their next ingest || Per-tenant rate limiting on the public ingest inbox | operations (ingest) | `ci.yml` ingest job (`ratelimit_test.go`, run under `-race`) — separate request and event ceilings, one tenant cannot consume another's budget, a rejected batch consumes no quota, `Retry-After` always rounds up, and idle buckets are swept so the map cannot grow on an attacker-controlled dimension | GATED | limits are per replica (in-process), so the effective ceiling is rate x replicas; an exact global cap needs edge termination |+| A push to the ingest spine is authenticated and its tenant comes from the credential | README (connect real data), operations (ingest authentication) | `ci.yml` ingest job (`ingest_auth_test.go`) — two tenants are seeded and the outsider's own token is proved to write first, so the cross-tenant refusal cannot pass vacuously; `X-Tenant-ID` is intersected with the credential's scope rather than trusted, a service token with no declared tenant resolves to an empty scope and refuses instead of widening, a token minted for another template is refused, and a nil authenticator fails closed + `golden-pipeline.yml` (an unauthenticated push to the deployed service is refused, observed from outside) | GATED | - || Incident resolves to identity, asset, cloud, business and threat context | architecture (context graph) | `ci.yml` api job (`test_incident_context.py`) — the test parses the generated Cypher and asserts every matched variable is tenant-scoped or is a label holding no tenant data, that no variable-length pattern binds a global label (which would bridge tenants), that every dimension is row-capped, and that one failing or slow dimension neither hangs nor discards the others; plus `ci.yml` agents job (`test_bundle_incident_context.py`) for the bundle and prompt wiring | GATED | population of the new labels from connectors is separate work; the traversal returns empty until they are written || A failed context lookup is distinguishable from an alert with no context | architecture (context graph) | `ci.yml` api + agents jobs — an unreachable graph sets `partial` and names the failed dimensions, and the prompt states the gap explicitly rather than omitting it, because silence reads to a model as 'no context exists' | GATED | - || Graph schema changes are versioned and applied to existing deployments | architecture (graph schema) | `graph-schema-check.yml` — the drift gate now compares Go and YAML in **both** directions (it previously only failed when YAML declared something Go lacked, which is the opposite of how the code changes, and passed with 28 Go labels against 17 in YAML); the version is read from schema.go rather than duplicated a third time; and `app.db.graph_migrations` records applied migrations so a schema change lands on existing deployments, not just fresh installs | GATED | ClickHouse and Qdrant still have no migration mechanism |@@ -150,7 +151,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`## Summary-- GATED: 131+- GATED: 132- PARTIAL: 8- NO GATE: 0 (**every claim is backed by a failing test.** The last NO GATE — the weekly benchmark scoreboard running live against `main` — closed in Phase E1: `scripts/check_scoreboard.py` ties the published scoreboard to a deterministic per-PR live-agent MITRE-accuracy run, while the funded weekly `wet-eval.yml` appends the LLM-tier rows. The remaining PARTIAL rows are honest, named deferrals — each states the specific gap and what closes it — not unproven claims.)diff --git a/scripts/check_inbox_templates.py b/scripts/check_inbox_templates.pynew file mode 100644index 000000000..873141330--- /dev/null+++ b/scripts/check_inbox_templates.py@@ -0,0 +1,251 @@+#!/usr/bin/env python3+"""Inbox templates on disk and mintable template ids must agree, both ways.++Two sets have to stay in lock-step:++* the YAML files under ``services/ingest/internal/normalizer/templates/``,+ which are what the Go ingest service can actually apply to a payload;+* ``ALLOWED_TEMPLATE_IDS`` in+ ``services/api/app/api/v1/endpoints/inbox.py``, which is what the mint+ API will accept.++Drift in either direction is silent and neither one is harmless:++* **Allow-listed with no YAML.** The operator mints a URL, pastes it into+ the vendor, and every delivery is dropped because the ingest build has+ no template of that name. The mint is the last moment anyone can tell+ them, which is exactly why the allow-list is validated at mint time.+* **YAML with no allow-list entry.** The template ships, gets documented,+ and cannot be reached — the mint call answers 400. This is the direction+ that actually bit: ``ai-runtime``, ``ai-finding`` and ``k8s-audit`` all+ shipped with YAML, were named in the AI SDK's own setup instructions and+ in the Kubernetes connector docs, and no token could be minted for any+ of them.++A one-directional check would have reported OK throughout that, which is+the shape of gate this repository keeps rediscovering. So this compares both+directions, and every exemption has to be written down with a reason rather+than simply omitted.++Usage:+ python3 scripts/check_inbox_templates.py+ python3 scripts/check_inbox_templates.py --self-test+"""++from __future__ import annotations++import argparse+import ast+import sys+from pathlib import Path++REPO_ROOT = Path(__file__).resolve().parents[1]+TEMPLATE_DIR = REPO_ROOT / "services/ingest/internal/normalizer/templates"+INBOX_ENDPOINT = REPO_ROOT / "services/api/app/api/v1/endpoints/inbox.py"++#: Mintable ids that deliberately have no YAML, and why. An id may only be+#: in ``ALLOWED_TEMPLATE_IDS`` without a template file if it is listed here.+MINTABLE_WITHOUT_TEMPLATE: dict[str, str] = {+ "itsm-inbound": (+ "Terminates at services/api (/api/v1/inbox/itsm/...), not at the Go "+ "ingest service: it needs a database transaction to mirror status "+ "onto aisoc_cases, so there is no OCSF payload mapping to apply."+ ),+ "connector-push": (+ "Names a credential purpose, not a payload mapping. Tokens minted "+ "with it authenticate POST /v1/ingest[/batch], which normalizes "+ "through the ingest service's connector profiles."+ ),+}++#: Templates that ship but are deliberately not mintable, and why. Empty+#: today; kept so that excluding one is a written decision rather than an+#: omission nobody notices.+TEMPLATE_WITHOUT_MINT_PATH: dict[str, str] = {}+++def declared_template_ids() -> set[str]:+ """Parse ALLOWED_TEMPLATE_IDS out of the endpoint module.++ Parsed with ``ast`` rather than imported: this runs in CI without the+ API service's dependencies installed, and importing the module would+ drag in FastAPI, SQLAlchemy and the settings object.+ """+ tree = ast.parse(INBOX_ENDPOINT.read_text(encoding="utf-8"))+ for node in ast.walk(tree):+ targets: list[ast.expr] = []+ if isinstance(node, ast.Assign):+ targets = list(node.targets)+ elif isinstance(node, ast.AnnAssign):+ targets = [node.target]+ else:+ continue+ for target in targets:+ if isinstance(target, ast.Name) and target.id == "ALLOWED_TEMPLATE_IDS":+ value = node.value+ if value is None or not isinstance(value, (ast.Tuple, ast.List)):+ raise SystemExit(f"{INBOX_ENDPOINT}: ALLOWED_TEMPLATE_IDS is not a literal tuple/list")+ ids = set()+ for element in value.elts:+ if not isinstance(element, ast.Constant) or not isinstance(element.value, str):+ raise SystemExit(f"{INBOX_ENDPOINT}: ALLOWED_TEMPLATE_IDS holds a non-string entry")+ ids.add(element.value)+ return ids+ raise SystemExit(f"{INBOX_ENDPOINT}: ALLOWED_TEMPLATE_IDS not found")+++def declared_catalog_ids() -> set[str]:+ """Parse the keys of _TEMPLATE_CATALOG.++ The catalog is what the onboarding wizard renders. ``list_templates``+ silently skips an id with no catalog entry, so an allow-listed template+ with no metadata is mintable over the API and invisible in the console+ — a third drift direction, and the one an operator would experience as+ "the feature does not exist".+ """+ tree = ast.parse(INBOX_ENDPOINT.read_text(encoding="utf-8"))+ for node in ast.walk(tree):+ targets = list(node.targets) if isinstance(node, ast.Assign) else ([node.target] if isinstance(node, ast.AnnAssign) else [])+ for target in targets:+ if isinstance(target, ast.Name) and target.id == "_TEMPLATE_CATALOG":+ value = node.value+ if not isinstance(value, ast.Dict):+ raise SystemExit(f"{INBOX_ENDPOINT}: _TEMPLATE_CATALOG is not a dict literal")+ return {k.value for k in value.keys if isinstance(k, ast.Constant) and isinstance(k.value, str)}+ raise SystemExit(f"{INBOX_ENDPOINT}: _TEMPLATE_CATALOG not found")+++def template_files() -> set[str]:+ if not TEMPLATE_DIR.is_dir():+ raise SystemExit(f"{TEMPLATE_DIR}: template directory not found")+ return {p.stem for p in sorted(TEMPLATE_DIR.glob("*.yaml"))}+++def self_test() -> int:+ """Inject drift in each direction and require the gate to catch each one.++ A one-directional gate prints OK while drift accumulates in the+ direction it does not look, which is how three templates shipped+ unmintable. This asserts both directions still fail, so a refactor that+ quietly stops checking one of them fails here rather than going quiet.+ """+ on_disk = template_files()+ mintable = declared_template_ids()+ catalogued = declared_catalog_ids()++ cases: list[tuple[str, set[str], set[str], set[str]]] = [+ # A template ships but nothing can mint it.+ (+ "shipped template with no mint path",+ on_disk | {"__drift_unmintable"},+ mintable,+ catalogued,+ ),+ # An id is mintable but the template is not there to apply.+ (+ "mintable id with no template file",+ on_disk,+ mintable | {"__drift_missing_yaml"},+ catalogued | {"__drift_missing_yaml"},+ ),+ # Mintable over the API, invisible in the console.+ (+ "mintable id with no catalog entry",+ on_disk | {"__drift_uncatalogued"},+ mintable | {"__drift_uncatalogued"},+ catalogued,+ ),+ ]++ failures = []+ for label, disk, mint, cat in cases:+ if not evaluate(disk, mint, cat):+ failures.append(f"the gate did NOT catch: {label}")++ # The undisturbed tree must be clean, or "the gate catches drift" would+ # be indistinguishable from "the gate fails on everything".+ if evaluate(on_disk, mintable, catalogued):+ failures.append("the undisturbed tree already reports drift, so a caught case proves nothing")++ if failures:+ for failure in failures:+ print(f"self-test FAILED — {failure}", file=sys.stderr)+ return 1+ print(f"self-test OK: the gate catches drift in all {len(cases)} directions.")+ return 0+++def evaluate(on_disk: set[str], mintable: set[str], catalogued: set[str]) -> list[str]:+ """Return the list of drift problems for one (disk, mintable, catalog) triple."""+ failures: list[str] = []++ for template_id in sorted(mintable - on_disk):+ if not MINTABLE_WITHOUT_TEMPLATE.get(template_id):+ failures.append(+ f"'{template_id}' is in ALLOWED_TEMPLATE_IDS but there is no "+ f"{TEMPLATE_DIR.relative_to(REPO_ROOT)}/{template_id}.yaml. "+ f"Tokens minted with it would silently drop every delivery. "+ f"Ship the template, or record the exemption with a reason in "+ f"MINTABLE_WITHOUT_TEMPLATE in {Path(__file__).name}."+ )++ for template_id in sorted(on_disk - mintable):+ if not TEMPLATE_WITHOUT_MINT_PATH.get(template_id):+ failures.append(+ f"'{template_id}.yaml' ships but '{template_id}' is not in "+ f"ALLOWED_TEMPLATE_IDS, so no token can be minted for it and "+ f"the template is unreachable. Add it to the allow-list and to "+ f"_TEMPLATE_CATALOG, or record the exemption with a reason in "+ f"TEMPLATE_WITHOUT_MINT_PATH in {Path(__file__).name}."+ )++ for template_id in sorted(mintable - catalogued):+ failures.append(+ f"'{template_id}' is mintable but has no _TEMPLATE_CATALOG entry, "+ f"so GET /api/v1/inbox/templates omits it and the onboarding "+ f"wizard cannot offer it."+ )++ for template_id in sorted(catalogued - mintable):+ failures.append(f"'{template_id}' has a _TEMPLATE_CATALOG entry but is not in ALLOWED_TEMPLATE_IDS, so minting it returns 400.")++ return failures+++def main() -> int:+ parser = argparse.ArgumentParser(description=__doc__, formatter_class=argparse.RawDescriptionHelpFormatter)+ parser.add_argument(+ "--self-test",+ action="store_true",+ help="assert the gate catches injected drift in every direction",+ )+ args = parser.parse_args()+ if args.self_test:+ return self_test()++ on_disk = template_files()+ mintable = declared_template_ids()+ catalogued = declared_catalog_ids()+ failures: list[str] = list(evaluate(on_disk, mintable, catalogued))++ # Stale exemptions are their own drift: an entry justifying something+ # that no longer exists reads as a reviewed decision while covering+ # nothing, which is how the gitleaks allow-list rotted.+ for template_id in sorted(set(MINTABLE_WITHOUT_TEMPLATE) - mintable):+ failures.append(f"'{template_id}' is exempted in MINTABLE_WITHOUT_TEMPLATE but is not mintable; drop the stale exemption.")+ for template_id in sorted(set(TEMPLATE_WITHOUT_MINT_PATH) - on_disk):+ failures.append(f"'{template_id}' is exempted in TEMPLATE_WITHOUT_MINT_PATH but ships no YAML; drop the stale exemption.")++ if failures:+ print("Inbox template drift:\n", file=sys.stderr)+ for failure in failures:+ print(f" - {failure}\n", file=sys.stderr)+ return 1++ exempt = len(MINTABLE_WITHOUT_TEMPLATE) + len(TEMPLATE_WITHOUT_MINT_PATH)+ print(f"OK: {len(on_disk)} template files, {len(mintable)} mintable ids, {exempt} recorded exemption(s); both directions agree.")+ return 0+++if __name__ == "__main__":+ sys.exit(main())diff --git a/services/api/app/api/v1/endpoints/inbox.py b/services/api/app/api/v1/endpoints/inbox.pyindex b5218ac77..6f8bdb048 100644--- a/services/api/app/api/v1/endpoints/inbox.py+++ b/services/api/app/api/v1/endpoints/inbox.py@@ -61,6 +61,10 @@ router = APIRouter(prefix="/inbox", tags=["inbox"])# UI's "preferred display order" so the wizard can iterate this list# directly.ALLOWED_TEMPLATE_IDS: tuple[str, ...] = (+ # Direct push to /v1/ingest. Unlike every other entry this one names a+ # credential purpose rather than a payload mapping — see the note above+ # ``connector-push`` in ``_TEMPLATE_CATALOG``.+ "connector-push",# P0 templates from the plan"generic-json","pagerduty",@@ -74,6 +78,19 @@ ALLOWED_TEMPLATE_IDS: tuple[str, ...] = ("cef-syslog","splunk-hec","email-forwarded",+ # AI estate. Both templates shipped with the feature and both are what+ # packages/aisoc-ai-sdk tells users to mint, but neither was ever added+ # here — so the documented setup for the AI-estate feature returned 400+ # and the SDK had no reachable endpoint to point at.+ "ai-runtime",+ "ai-finding",+ # Kubernetes apiserver audit, inbox path. The dedicated route+ # POST /v1/ingest/k8s-audit/{tenant_id} is preferred and is what the+ # connector docs lead with, but both those docs and+ # plugins/kubernetes-audit/plugin.yaml describe this token as the+ # supported fallback for control planes that cannot set a custom header+ # in audit-webhook kubeconfig. It could not be minted either.+ "k8s-audit",# Bidirectional ITSM (Workstream 8) — inbound Jira / ServiceNow webhooks.# Tokens minted with this template terminate at# /api/v1/inbox/itsm/{tenant_token}/{connector_instance_id} on services/api@@ -211,6 +228,25 @@ class InboxTemplateInfo(BaseModel):# kept here (not in the YAML) because the YAML is parsed by the Go# service and we don't want a cross-service schema dependency._TEMPLATE_CATALOG: dict[str, dict[str, str]] = {+ # Not a payload mapping. A connector-push token is the credential for+ # ``POST /v1/ingest[/batch]``, which normalizes through the ingest+ # service's connector profiles rather than through a template, so there+ # is deliberately no ``connector-push.yaml`` on disk —+ # ``scripts/check_inbox_templates.py`` records that exemption.+ #+ # The route is pinned to this template id for the same reason+ # ``/v1/inbox/cef`` is pinned to ``cef-syslog``: an inbox token is+ # pasted into a third party's webhook configuration, so minting one for+ # PagerDuty must not also hand PagerDuty a general ingest credential+ # for the tenant.+ "connector-push": {+ "label": "Direct ingest API (curl, scripts, agents)",+ "description": (+ "Credential for POST /v1/ingest/batch. Use it to push telemetry "+ "from a script, an agent, or any tool that can make an HTTP request."+ ),+ "category": "generic",+ },"generic-json": {"label": "Generic JSON","description": ("Forward arbitrary JSON. Best effort field mapping; use a specific template below if your vendor is listed."),@@ -268,6 +304,31 @@ _TEMPLATE_CATALOG: dict[str, dict[str, str]] = {"description": ("Inbound webhook from Mailgun / SES routing rules. Useful for vendors that only deliver alerts via email."),"category": "email",},+ "ai-runtime": {+ "label": "AI runtime activity",+ "description": (+ "Model calls, tool invocations and MCP requests from your AI estate. "+ "Emitted by packages/aisoc-ai-sdk. Routine activity lands in the lake for hunting."+ ),+ "category": "ai",+ },+ "ai-finding": {+ "label": "AI guardrail finding",+ "description": (+ "Prompt injection, excessive agency, sensitive-data egress and other "+ "guardrail hits. Always promoted to an alert, so mint this separately from ai-runtime."+ ),+ "category": "ai",+ },+ "k8s-audit": {+ "label": "Kubernetes audit (webhook fallback)",+ "description": (+ "Apiserver audit events over the inbox. Prefer "+ "POST /v1/ingest/k8s-audit/<tenant_id>; use this only when the "+ "control plane cannot set a custom header."+ ),+ "category": "cloud",+ },"itsm-inbound": {"label": "Inbound ITSM (Jira / ServiceNow)","description": (diff --git a/services/api/app/scripts/mint_ingest_token.py b/services/api/app/scripts/mint_ingest_token.pynew file mode 100644index 000000000..e81ff7d16--- /dev/null+++ b/services/api/app/scripts/mint_ingest_token.py@@ -0,0 +1,231 @@+"""Mint the credential that ``POST /v1/ingest/batch`` requires.++ docker compose run --rm api python -m app.scripts.mint_ingest_token+ # or, from the repo root:+ make ingest-token++Run it once after ``make up`` if you want to push telemetry with curl, a+script, or anything else that is not a configured connector. It prints a+token and the URL to send to. Re-running returns the *same* token rather+than minting a second one, so it is safe to call from a script; pass+``--rotate`` to replace it.++Why this exists+---------------+``/v1/ingest/batch`` used to accept anything. It read an ``X-Tenant-ID``+header, trusted it, and wrote events for whatever tenant the caller named,+so anyone who could reach the port could write alerts into any tenant. It+now requires a credential that carries its own tenant, and this command is+how a fresh deployment gets one — the same role ``bootstrap_admin`` plays+for the console login.++It writes the same ``tenant_inbox_tokens`` row that+``POST /api/v1/inbox/tokens`` writes, using the ``connector-push`` template.+The API route is the path the console uses and is preferred when you have a+session; this command exists for the case the route cannot serve, which is+a fresh stack where nobody has logged in yet.++This is not a dev-mode shortcut and does not consult ``AISOC_DEV_MODE``. It+mints a real credential and is the supported path in every environment.+"""++from __future__ import annotations++import argparse+import asyncio+import os+import secrets+import sys+import uuid+from datetime import UTC, datetime++from sqlalchemy import select, update++from app.core.config import settings+from app.db.database import AsyncSessionLocal+from app.models.inbox import TenantInboxToken+from app.models.tenant import Tenant++# Matches the tenant seeded by migration 001, the same constant+# ``bootstrap_admin`` adopts, so a token minted here belongs to the tenant+# the rest of a fresh install's rows belong to.+DEFAULT_TENANT_ID = uuid.UUID("00000000-0000-0000-0000-000000000001")++# Must equal ingestauth.PushTemplateID in services/ingest. A token minted+# with any other template is refused by /v1/ingest, deliberately:+# see the note in services/api/app/api/v1/endpoints/inbox.py.+PUSH_TEMPLATE_ID = "connector-push"++DEFAULT_LABEL = "Direct ingest API"+++class MintError(RuntimeError):+ """A condition the operator has to resolve, reported without a traceback."""+++def _generate_token() -> str:+ """Same shape as ``_generate_inbox_token`` in the mint endpoint."""+ return f"aitnb_{secrets.token_urlsafe(32)}"+++def _ingest_url() -> str:+ base = (getattr(settings, "INGEST_PUBLIC_URL", "") or "").rstrip("/")+ return f"{base}/v1/ingest/batch" if base else "http://localhost:8081/v1/ingest/batch"+++async def _resolve_tenant(session, tenant_ref: str | None) -> Tenant:+ """Find the tenant to mint for.++ With no ``--tenant`` the canonical seeded tenant wins, then the only+ tenant if there is exactly one. We refuse to guess when several exist:+ a token silently minted for the wrong tenant would send telemetry+ somewhere the operator is not looking, which is worse than an error.+ """+ if tenant_ref:+ try:+ wanted = uuid.UUID(tenant_ref)+ except ValueError:+ result = await session.execute(select(Tenant).where(Tenant.slug == tenant_ref))+ tenant = result.scalar_one_or_none()+ if tenant is None:+ raise MintError(f"no tenant with id or slug {tenant_ref!r}") from None+ return tenant+ result = await session.execute(select(Tenant).where(Tenant.id == wanted))+ tenant = result.scalar_one_or_none()+ if tenant is None:+ raise MintError(f"no tenant with id {tenant_ref!r}")+ return tenant++ result = await session.execute(select(Tenant).where(Tenant.id == DEFAULT_TENANT_ID))+ tenant = result.scalar_one_or_none()+ if tenant is not None:+ return tenant++ result = await session.execute(select(Tenant).order_by(Tenant.created_at))+ tenants = list(result.scalars().all())+ if not tenants:+ raise MintError("no tenants exist yet — run 'make bootstrap' first")+ if len(tenants) > 1:+ names = ", ".join(f"{t.slug} ({t.id})" for t in tenants)+ raise MintError(f"several tenants exist; name one with --tenant: {names}")+ return tenants[0]+++async def mint(*, tenant_ref: str | None, rotate: bool, label: str) -> tuple[str, Tenant, bool]:+ """Return ``(token, tenant, is_new)``.++ Reusing an existing active token is what makes this safe to call from+ ``make smoke`` on every run: a command that minted a fresh credential+ each time would leave a trail of live tokens nobody revokes.+ """+ async with AsyncSessionLocal() as session:+ tenant = await _resolve_tenant(session, tenant_ref)++ result = await session.execute(+ select(TenantInboxToken)+ .where(+ TenantInboxToken.tenant_id == tenant.id,+ TenantInboxToken.template_id == PUSH_TEMPLATE_ID,+ TenantInboxToken.revoked_at.is_(None),+ )+ .order_by(TenantInboxToken.created_at.desc())+ )+ existing = result.scalars().first()++ if existing is not None and not rotate:+ return existing.token, tenant, False++ if existing is not None:+ await session.execute(+ update(TenantInboxToken).where(TenantInboxToken.token == existing.token).values(revoked_at=datetime.now(UTC))+ )++ token = _generate_token()+ session.add(+ TenantInboxToken(+ token=token,+ tenant_id=tenant.id,+ template_id=PUSH_TEMPLATE_ID,+ label=label,+ hmac_secret=None,+ created_at=datetime.now(UTC),+ )+ )+ await session.commit()+ return token, tenant, True+++def _print_human(token: str, tenant: Tenant, *, is_new: bool) -> None:+ bar = "─" * 72+ print(f"\n{bar}")+ print(" Ingest credential for tenant " + f"{tenant.slug} ({tenant.id})")+ print(bar)+ print(f" Token {token}")+ print(bar)+ if is_new:+ print(" Minted now. It is stored in tenant_inbox_tokens and can be")+ print(" rotated with --rotate or revoked from Settings -> Connectors.")+ else:+ print(" This tenant already had a push token; reusing it.")+ print(" Replace it with --rotate.")+ print()+ print(" Push an event:")+ print(f" curl -X POST {_ingest_url()} \\")+ print(" -H 'Content-Type: application/json' \\")+ print(' -H "Authorization: Bearer $AISOC_INGEST_TOKEN" \\')+ print(' -d \'{"connector_id":"edr-1","connector_type":"crowdstrike",')+ print(' "source_format":"json","events":[{"severity":"high",')+ print(' "title":"Encoded PowerShell from Office"}]}\'')+ print()+++def build_parser() -> argparse.ArgumentParser:+ parser = argparse.ArgumentParser(+ prog="python -m app.scripts.mint_ingest_token",+ description="Mint the credential POST /v1/ingest/batch requires.",+ )+ parser.add_argument(+ "--tenant",+ default=os.environ.get("AISOC_TENANT_ID") or None,+ help="tenant id or slug (default: the canonical seeded tenant, or the only one)",+ )+ parser.add_argument(+ "--rotate",+ action="store_true",+ help="revoke the existing push token and mint a replacement",+ )+ parser.add_argument(+ "--label",+ default=DEFAULT_LABEL,+ help=f"operator-facing label (default: {DEFAULT_LABEL!r})",+ )+ parser.add_argument(+ "--quiet",+ action="store_true",+ help="print only the token, for use in scripts",+ )+ return parser+++async def _run(args: argparse.Namespace) -> int:+ token, tenant, is_new = await mint(tenant_ref=args.tenant, rotate=args.rotate, label=args.label)+ if args.quiet:+ # Only the token, and nothing else on stdout, so a caller can do+ # AISOC_INGEST_TOKEN="$(... --quiet)" without parsing.+ print(token)+ else:+ _print_human(token, tenant, is_new=is_new)+ return 0+++def main() -> int:+ args = build_parser().parse_args()+ try:+ return asyncio.run(_run(args))+ except MintError as exc:+ print(f"\nmint_ingest_token failed: {exc}\n", file=sys.stderr)+ return 2+++if __name__ == "__main__": # pragma: no cover - module entrypoint+ raise SystemExit(main())diff --git a/services/connectors/app/ingest_client.py b/services/connectors/app/ingest_client.pyindex a2d274c52..74daa604a 100644--- a/services/connectors/app/ingest_client.py+++ b/services/connectors/app/ingest_client.py@@ -14,6 +14,23 @@ shape::with ``X-Tenant-ID`` header for tenant scoping.+Authentication+--------------+``/v1/ingest`` requires a credential. This process pushes on behalf of every+tenant whose connectors it polls, so it cannot hold a per-tenant push token;+it presents the shared service token instead (``AISOC_SERVICE_TOKEN``, or+``AISOC_INGEST_SERVICE_TOKEN`` to override it for this hop only), which+identifies *a trusted service* rather than a tenant. ``X-Tenant-ID`` then+declares which tenant the push is for, and the ingest service checks that+tenant against the tenants table before it becomes a scope. That is the same+credential shape ``app.security.tenant_scope`` implements for the Python+services.++Without the token every push is refused with 401, which is a deliberate+configuration requirement rather than a soft failure — see+``apps/docs/docs/operations/ingest-authentication.md``. We say so once at construction+time so the cause is visible at startup rather than only in per-poll errors.+We keep this layer **dumb on purpose**: no retries with exponential backoffbeyond a single retry, no circuit breaker, no batching across connectors.The ingest service handles the queueing into Kafka — adding another buffer@@ -25,18 +42,34 @@ down, polls fail loudly and the scheduler records that infrom __future__ import annotations+import loggingimport osimport uuidfrom typing import Anyimport httpx+logger = logging.getLogger(__name__)+# 30s mirrors the ingest service's own ReadTimeout. We don't want the client# to give up before the server has a chance to publish; we also don't want# polls to hang the scheduler thread for minutes if Kafka is wedged._DEFAULT_TIMEOUT_S = 30.0+def resolve_service_token() -> str:+ """The shared secret this service presents to ``/v1/ingest``.++ Per-service override wins over the shared platform token, matching the+ precedence in ``app.security.tenant_scope.resolve_service_token`` and in+ the Go ingest service's own config.+ """+ specific = os.getenv("AISOC_INGEST_SERVICE_TOKEN", "").strip()+ if specific:+ return specific+ return os.getenv("AISOC_SERVICE_TOKEN", "").strip()++class IngestClientError(RuntimeError):"""Raised when the ingest service rejects or fails the push."""@@ -50,11 +83,27 @@ class IngestClient:every caller."""- def __init__(self, base_url: str, *, timeout_seconds: float = _DEFAULT_TIMEOUT_S) -> None:+ def __init__(+ self,+ base_url: str,+ *,+ timeout_seconds: float = _DEFAULT_TIMEOUT_S,+ service_token: str | None = None,+ ) -> None:# Strip trailing slash so we can append paths without doubling up.self._base_url = base_url.rstrip("/")self._timeout = timeout_seconds+ self._service_token = (service_token if service_token is not None else resolve_service_token()).strip()self._client: httpx.AsyncClient | None = None+ if not self._service_token:+ # Warned once here rather than per poll. Every push will be+ # refused, and an operator reading the startup log should not+ # have to wait for the first poll cycle to learn why.+ logger.warning(+ "no ingest service token configured (AISOC_SERVICE_TOKEN / AISOC_INGEST_SERVICE_TOKEN); "+ "every push to %s will be refused with 401",+ self._base_url,+ )@classmethoddef from_env(cls) -> IngestClient:@@ -101,8 +150,14 @@ class IngestClient:url = f"{self._base_url}/v1/ingest/batch"headers = {"Content-Type": "application/json",+ # Declares which tenant this trusted service is acting for. It+ # is not authority on its own — the ingest service intersects it+ # with what the credential authorises and validates it against+ # the tenants table."X-Tenant-ID": str(tenant_id),}+ if self._service_token:+ headers["Authorization"] = f"Bearer {self._service_token}"payload = {"connector_id": str(connector_id),"connector_type": connector_type,@@ -116,11 +171,17 @@ class IngestClient:raise IngestClientError(f"ingest service unreachable at {url}: {exc}") from excif resp.status_code >= 400:- # Pull the body so logs show *why* — typically a missing tenant- # header or oversized batch, both of which we want surfaced- # rather than swallowed.+ # Pull the body so logs show *why* — typically a missing or+ # rejected credential, an undeclared tenant, or an oversized+ # batch, all of which we want surfaced rather than swallowed.body_preview = resp.text[:500]- raise IngestClientError(f"ingest service returned {resp.status_code} for connector {connector_id}: {body_preview}")+ hint = ""+ if resp.status_code in (401, 403):+ hint = (+ " — /v1/ingest requires a credential; set AISOC_SERVICE_TOKEN on both this service "+ "and the ingest service (see apps/docs/docs/operations/ingest-authentication.md)"+ )+ raise IngestClientError(f"ingest service returned {resp.status_code} for connector {connector_id}: {body_preview}{hint}")try:data = resp.json()diff --git a/services/connectors/tests/test_ingest_client_auth.py b/services/connectors/tests/test_ingest_client_auth.pynew file mode 100644index 000000000..0933ec71c--- /dev/null+++ b/services/connectors/tests/test_ingest_client_auth.py@@ -0,0 +1,101 @@+"""The connector-poll push has to present a credential and declare a tenant.++``/v1/ingest`` no longer takes the caller's word for which tenant a batch+belongs to. This process pushes for every tenant it polls, so it holds the+shared service token rather than a per-tenant one, and the tenant it is+acting for travels on ``X-Tenant-ID`` where the ingest service intersects+it with what the credential authorises.++Both halves matter and both are asserted here: a push with no Authorization+header is refused at the far end, and a push that omits the tenant header+resolves to an empty scope there. Either omission is silent on this side —+the request goes out looking fine — which is why the test inspects the+headers that were actually sent rather than only the return value.+"""++from __future__ import annotations++import uuid++import httpx+import pytest+from app.ingest_client import IngestClient, IngestClientError, resolve_service_token++TENANT = uuid.UUID("11111111-1111-4111-8111-111111111111")+++def _client(monkeypatch: pytest.MonkeyPatch, handler, **kwargs) -> IngestClient:+ """An IngestClient whose transport records what it was asked to send."""+ client = IngestClient("http://ingest-worker:8080", **kwargs)+ monkeypatch.setattr(+ client,+ "_get_client",+ lambda: _async_client(handler),+ )+ return client+++async def _async_client(handler) -> httpx.AsyncClient:+ return httpx.AsyncClient(transport=httpx.MockTransport(handler))+++async def test_push_presents_the_service_token_and_declares_the_tenant(monkeypatch: pytest.MonkeyPatch) -> None:+ seen: dict[str, str] = {}++ def handler(request: httpx.Request) -> httpx.Response:+ seen.update(request.headers)+ return httpx.Response(200, json={"accepted": 1, "rejected": 0})++ client = _client(monkeypatch, handler, service_token="svc-secret")+ result = await client.push_events(+ tenant_id=TENANT,+ connector_id=uuid.uuid4(),+ connector_type="crowdstrike",+ events=[{"severity": "high", "title": "t"}],+ )++ assert result["accepted"] == 1+ assert seen["authorization"] == "Bearer svc-secret"+ assert seen["x-tenant-id"] == str(TENANT)+++async def test_push_without_a_token_sends_no_authorization_header(monkeypatch: pytest.MonkeyPatch) -> None:+ # The client does not invent a credential, and does not fall back to an+ # unauthenticated push that looks successful. It sends what it has; the+ # ingest service refuses it.+ seen: dict[str, str] = {}++ def handler(request: httpx.Request) -> httpx.Response:+ seen.update(request.headers)+ return httpx.Response(401, text='{"error":"missing ingest credential"}')++ client = _client(monkeypatch, handler, service_token="")+ with pytest.raises(IngestClientError) as excinfo:+ await client.push_events(+ tenant_id=TENANT,+ connector_id=uuid.uuid4(),+ connector_type="crowdstrike",+ events=[{"severity": "high", "title": "t"}],+ )++ assert "authorization" not in seen+ # The error has to name the fix. A bare "401" sends an operator to the+ # connector's own credentials, which are not the problem.+ assert "AISOC_SERVICE_TOKEN" in str(excinfo.value)+++def test_service_token_precedence_matches_the_platform(monkeypatch: pytest.MonkeyPatch) -> None:+ monkeypatch.delenv("AISOC_INGEST_SERVICE_TOKEN", raising=False)+ monkeypatch.setenv("AISOC_SERVICE_TOKEN", "shared")+ assert resolve_service_token() == "shared"++ monkeypatch.setenv("AISOC_INGEST_SERVICE_TOKEN", "specific")+ assert resolve_service_token() == "specific"++ monkeypatch.setenv("AISOC_INGEST_SERVICE_TOKEN", "")+ assert resolve_service_token() == "shared"++ monkeypatch.setenv("AISOC_SERVICE_TOKEN", "")+ assert resolve_service_token() == ""diff --git a/services/ingest/internal/config/config.go b/services/ingest/internal/config/config.goindex 953761b38..d3db832d9 100644--- a/services/ingest/internal/config/config.go+++ b/services/ingest/internal/config/config.go@@ -24,6 +24,22 @@ type Config struct {JWTSecret stringMetricsPort int+ // /v1/ingest authentication.+ //+ // ServiceToken is the shared secret a trusted AiSOC service presents+ // when it pushes on behalf of many tenants (services/connectors polls+ // every tenant's connectors from one process). It identifies a+ // service, not a tenant, so a caller using it must also declare the+ // tenant it is acting for; see internal/ingestauth. Empty means the+ // service-token path is unavailable and only minted per-tenant push+ // tokens are accepted — there is no configuration that accepts an+ // unauthenticated push.+ ServiceToken string+ // IngestMaxBodyBytes caps a single /v1/ingest body. MaxBatchSize only+ // bounds the event count *after* the payload is decoded, so this is+ // what bounds the decode itself.+ IngestMaxBodyBytes int64+// Shodan enrichmentShodanAPIKey stringShodanEnrichEnabled bool@@ -171,6 +187,12 @@ func Load() (*Config, error) {JWTSecret: getEnv("JWT_SECRET", ""),MetricsPort: mustGetEnvInt("METRICS_PORT", 9090),+ // Per-service override wins over the shared platform token, the+ // same precedence app.security.tenant_scope.resolve_service_token+ // applies on the Python side.+ ServiceToken: getEnvFallback("AISOC_INGEST_SERVICE_TOKEN", "AISOC_SERVICE_TOKEN", ""),+ IngestMaxBodyBytes: int64(mustGetEnvInt("INGEST_MAX_BODY_BYTES", 10*1024*1024)),+// ShodanShodanAPIKey: getEnv("SHODAN_API_KEY", ""),ShodanEnrichEnabled: getEnv("SHODAN_ENRICH_ENABLED", "false") == "true",diff --git a/services/ingest/internal/handler/handler.go b/services/ingest/internal/handler/handler.goindex de9b99c94..f9da33208 100644--- a/services/ingest/internal/handler/handler.go+++ b/services/ingest/internal/handler/handler.go@@ -4,15 +4,18 @@ package handlerimport ("context""encoding/json"+ "errors""fmt"+ "io""net/http""sort"+ "strings""time""github.com/beenuar/aisoc/services/ingest/internal/config""github.com/beenuar/aisoc/services/ingest/internal/graph"+ "github.com/beenuar/aisoc/services/ingest/internal/ingestauth""github.com/beenuar/aisoc/services/ingest/internal/normalizer"- "github.com/beenuar/aisoc/services/ingest/internal/publisher""github.com/rs/zerolog/log")@@ -24,6 +27,15 @@ type GraphWriter interface {WriteEvent(ctx context.Context, ev *graph.Event) error}+// EventPublisher is the subset of *publisher.Publisher the HTTP path+// depends on. Declared as an interface for the same reason GraphWriter is:+// so a request can be driven end to end in a unit test — including which+// tenant its events were published for — without a Kafka broker.+type EventPublisher interface {+ PublishBatch(ctx context.Context, events []*normalizer.NormalizedEvent) error+ Ready(ctx context.Context) error+}+// SnapshotApplier mirrors *config_snapshot.Snapshotter.Apply. Defined as// an interface so the handler can be unit-tested without standing up a// real provider/cache pair, and so a nil applier is a clean "T1.2@@ -50,15 +62,16 @@ type SubscriptionStatus struct {// Handler holds handler dependenciestype Handler struct {norm *normalizer.Normalizer- pub *publisher.Publisher+ pub EventPublishergraph GraphWritersnapshot SnapshotAppliercfg *config.Config+ auth *ingestauth.Authenticatorsubscriptions map[string]func() SubscriptionStatus}// New creates a new Handler-func New(norm *normalizer.Normalizer, pub *publisher.Publisher, cfg *config.Config) *Handler {+func New(norm *normalizer.Normalizer, pub EventPublisher, cfg *config.Config) *Handler {return &Handler{norm: norm, pub: pub, cfg: cfg, subscriptions: map[string]func() SubscriptionStatus{}}}@@ -92,6 +105,17 @@ func (h *Handler) SetSnapshotApplier(s SnapshotApplier) {h.snapshot = s}+// SetAuthenticator wires in the /v1/ingest credential check.+//+// Unlike the other setters on this type, nil is not a "feature disabled"+// signal: a nil *ingestauth.Authenticator refuses every request. Ingest is+// a write path into tenant-owned data, so a wiring regression has to fail+// closed. There is no flag that turns this off — AISOC_DEV_MODE does not+// reach it, and tests/test_security_defaults.py exists to keep it that way.+func (h *Handler) SetAuthenticator(a *ingestauth.Authenticator) {+ h.auth = a+}+// IngestRequest is the API payload for submitting eventstype IngestRequest struct {ConnectorID string `json:"connector_id"`@@ -110,14 +134,45 @@ type IngestResponse struct {// IngestEvents handles POST /v1/ingestfunc (h *Handler) IngestEvents(w http.ResponseWriter, r *http.Request) {- tenantID := r.Header.Get(h.cfg.TenantHeaderKey)- if tenantID == "" {- writeError(w, http.StatusBadRequest, "missing tenant ID header")+ // Authenticate before touching the body. An unauthenticated caller+ // should not get to spend this process's memory budget, and the+ // credential is what decides the tenant, so nothing below can run+ // without it.+ identity, authErr := h.auth.Authenticate(r.Context(), r)+ if authErr != nil {+ writeAuthError(w, r, authErr)+ return+ }++ body, ok := h.readIngestBody(w, r)+ if !ok {+ return+ }++ if err := ingestauth.VerifySignature(r, identity, body); err != nil {+ writeAuthError(w, r, err)+ return+ }++ // The tenant header is honoured only where it agrees with what the+ // credential authorises. Naming another tenant narrows the scope to+ // nothing and is refused here, rather than reaching into that tenant+ // — which is precisely what this endpoint used to do for anyone who+ // could reach the port.+ tenantUUID, scopeErr := ingestauth.Resolve(identity.Principal, h.auth.DeclaredTenant(r))+ if scopeErr != nil {+ log.Warn().+ Str("subject", sanitizeForLog(identity.Principal.Subject)).+ Str("requested_tenant", sanitizeForLog(h.auth.DeclaredTenant(r))).+ Bool("delegated", identity.Principal.Delegated).+ Msg("ingest: refused a write outside the credential's tenant scope")+ writeError(w, http.StatusForbidden, scopeErr.Error())return}+ tenantID := tenantUUID.String()var req IngestRequest- if err := json.NewDecoder(r.Body).Decode(&req); err != nil {+ if err := json.Unmarshal(body, &req); err != nil {writeError(w, http.StatusBadRequest, "invalid request body: "+err.Error())return}@@ -319,6 +374,61 @@ func degradedSubscriptions(subs map[string]SubscriptionStatus) []string {return names}+// readIngestBody slurps the body under a size cap.+//+// The cap is new alongside authentication and belongs with it: MaxBatchSize+// is only checked after the payload has been decoded, so before this the+// only thing standing between the endpoint and a multi-gigabyte body was+// that nobody had sent one.+func (h *Handler) readIngestBody(w http.ResponseWriter, r *http.Request) ([]byte, bool) {+ limit := h.cfg.IngestMaxBodyBytes+ if limit <= 0 {+ limit = 10 * 1024 * 1024+ }+ r.Body = http.MaxBytesReader(w, r.Body, limit)+ body, err := io.ReadAll(r.Body)+ if err != nil {+ var maxErr *http.MaxBytesError+ if errors.As(err, &maxErr) {+ writeError(w, http.StatusRequestEntityTooLarge,+ fmt.Sprintf("body exceeds %d bytes", limit))+ return nil, false+ }+ writeError(w, http.StatusBadRequest, "failed to read request body: "+err.Error())+ return nil, false+ }+ return body, true+}++// writeAuthError renders an *ingestauth.Error with its own status, and logs+// the refusal. Anything that is not one of those is reported as 401 rather+// than leaking an internal message to an unauthenticated caller.+func writeAuthError(w http.ResponseWriter, r *http.Request, err error) {+ var authErr *ingestauth.Error+ status, msg := http.StatusUnauthorized, "unauthorized"+ if errors.As(err, &authErr) {+ status, msg = authErr.Status, authErr.Msg+ }+ log.Warn().+ Int("status", status).+ Str("remote_addr", sanitizeForLog(r.RemoteAddr)).+ Str("path", sanitizeForLog(r.URL.Path)).+ Msg("ingest: refused an unauthenticated or unauthorized push")+ writeError(w, status, msg)+}++// sanitizeForLog strips CR/LF and bounds length inline at the call site.+// Done inline rather than behind a helper call for the values that matter:+// the taint tracker does not follow a helper across the boundary, and these+// values are caller-controlled.+func sanitizeForLog(v string) string {+ s := strings.ReplaceAll(strings.ReplaceAll(v, "\r", ""), "\n", " ")+ if len(s) > 128 {+ return s[:128]+ }+ return s+}+func writeJSON(w http.ResponseWriter, status int, v interface{}) {w.Header().Set("Content-Type", "application/json")w.WriteHeader(status)diff --git a/services/ingest/internal/handler/ingest_auth_test.go b/services/ingest/internal/handler/ingest_auth_test.gonew file mode 100644index 000000000..393f07ba5--- /dev/null+++ b/services/ingest/internal/handler/ingest_auth_test.go@@ -0,0 +1,465 @@+// ingest_auth_test.go — the credential check on POST /v1/ingest[/batch].+//+// These tests exist because the endpoint used to have no authentication at+// all: it read a tenant out of a caller-supplied X-Tenant-ID header and+// wrote events for whatever that header said. The load-bearing property is+// therefore not "an authenticated caller can push" but "a credential for+// one tenant cannot write into another", so that is what most of this file+// asserts, driven through the real handler rather than against the+// resolver in isolation.+//+// Every cross-tenant case here first proves the target tenant genuinely+// exists and is genuinely writable by its own credential. Without that,+// a refusal is indistinguishable from the tenant simply not being there,+// and the test would keep passing if the check were deleted and replaced+// by an unrelated 404.+package handler++import (+ "bytes"+ "context"+ "crypto/hmac"+ "crypto/sha256"+ "encoding/hex"+ "encoding/json"+ "fmt"+ "net/http"+ "net/http/httptest"+ "sync"+ "testing"++ "github.com/beenuar/aisoc/services/ingest/internal/config"+ "github.com/beenuar/aisoc/services/ingest/internal/inbox"+ "github.com/beenuar/aisoc/services/ingest/internal/ingestauth"+ "github.com/beenuar/aisoc/services/ingest/internal/normalizer"+ "github.com/google/uuid"+)++// ── two tenants, seeded ────────────────────────────────────────────────+//+// "Acme" is the caller. "Umbra" is the outsider — the tenant Acme must not+// be able to reach. Both are real rows as far as the fakes are concerned:+// both resolve, both are active, and the tests below prove Umbra is+// writable by its own token before asserting that Acme cannot write to it.++var (+ acmeTenant = uuid.MustParse("11111111-1111-4111-8111-111111111111")+ umbraTenant = uuid.MustParse("22222222-2222-4222-8222-222222222222")+ ghostTenant = uuid.MustParse("33333333-3333-4333-8333-333333333333") // never seeded++ acmeToken = "aitnb_acme_push_token_aaaaaaaaaaaa"+ umbraToken = "aitnb_umbra_push_token_bbbbbbbbbbb"+)++const testServiceToken = "svc-token-for-trusted-internal-callers"++// fakeTokens is an in-memory stand-in for inbox.Store.+type fakeTokens struct {+ rows map[string]*inbox.Token+}++func (f *fakeTokens) Resolve(_ context.Context, token string) (*inbox.Token, error) {+ row, ok := f.rows[token]+ if !ok {+ return nil, inbox.ErrTokenNotFound+ }+ if row.Label == "revoked" {+ return nil, inbox.ErrTokenRevoked+ }+ return row, nil+}++// fakeTenants stands in for the tenants table. Only the service-token path+// consults it; a minted token's tenant is proved by the token row's own+// foreign key.+type fakeTenants struct{ active map[uuid.UUID]bool }++func (f *fakeTenants) IsActive(_ context.Context, id uuid.UUID) (bool, error) {+ return f.active[id], nil+}++// capturingPublisher records the tenant of every event that reaches Kafka,+// which is the only evidence that matters here: a refusal that still+// published would be worse than no refusal, because it would look fixed.+type capturingPublisher struct {+ mu sync.Mutex+ published []*normalizer.NormalizedEvent+}++func (p *capturingPublisher) PublishBatch(_ context.Context, events []*normalizer.NormalizedEvent) error {+ p.mu.Lock()+ defer p.mu.Unlock()+ p.published = append(p.published, events...)+ return nil+}++func (p *capturingPublisher) Ready(context.Context) error { return nil }++// tenantsWritten returns how many events landed for one tenant.+func (p *capturingPublisher) tenantsWritten(tenant uuid.UUID) int {+ p.mu.Lock()+ defer p.mu.Unlock()+ n := 0+ for _, e := range p.published {+ if e.TenantID == tenant.String() {+ n+++ }+ }+ return n+}++// testConfig is the minimum an ingest handler needs to normalize and+// publish. NormalizerMode is lenient so a plain vendor event maps without+// a per-vendor profile, which keeps these tests about the credential.+func testConfig() *config.Config {+ return &config.Config{+ TenantHeaderKey: "X-Tenant-ID",+ NormalizerMode: "lenient",+ MaxBatchSize: 500,+ IngestMaxBodyBytes: 1 << 20,+ }+}++func newAuthHandler(t *testing.T, serviceToken string) (*Handler, *capturingPublisher) {+ t.Helper()+ tokens := &fakeTokens{rows: map[string]*inbox.Token{+ acmeToken: {+ Token: acmeToken, TenantID: acmeTenant, TemplateID: ingestauth.PushTemplateID,+ },+ umbraToken: {+ Token: umbraToken, TenantID: umbraTenant, TemplateID: ingestauth.PushTemplateID,+ },+ "aitnb_revoked_cccccccccccccccccccc": {+ Token: "aitnb_revoked_cccccccccccccccccccc", TenantID: acmeTenant,+ TemplateID: ingestauth.PushTemplateID, Label: "revoked",+ },+ "aitnb_pagerduty_webhook_dddddddddd": {+ Token: "aitnb_pagerduty_webhook_dddddddddd", TenantID: acmeTenant,+ TemplateID: "pagerduty",+ },+ "aitnb_acme_signed_eeeeeeeeeeeeeeee": {+ Token: "aitnb_acme_signed_eeeeeeeeeeeeeeee", TenantID: acmeTenant,+ TemplateID: ingestauth.PushTemplateID, HMACSecret: "shared-signing-secret",+ },+ }}+ tenants := &fakeTenants{active: map[uuid.UUID]bool{+ acmeTenant: true,+ umbraTenant: true,+ }}++ cfg := testConfig()+ norm, err := normalizer.New(cfg)+ if err != nil {+ t.Fatalf("normalizer: %v", err)+ }+ pub := &capturingPublisher{}+ h := New(norm, pub, cfg)+ h.SetAuthenticator(ingestauth.New(tokens, tenants, serviceToken, cfg.TenantHeaderKey))+ return h, pub+}++// push builds and runs one ingest request. credential goes on+// Authorization; declaredTenant, when non-empty, goes on X-Tenant-ID.+func push(t *testing.T, h *Handler, credential, declaredTenant string, opts ...func(*http.Request)) *httptest.ResponseRecorder {+ t.Helper()+ body, err := json.Marshal(map[string]any{+ "connector_id": "edr-1",+ "connector_type": "crowdstrike",+ "source_format": "json",+ "events": []map[string]any{{+ "severity": "high",+ "title": "Encoded PowerShell from Office",+ "host": "WIN-FIN-01",+ }},+ })+ if err != nil {+ t.Fatalf("marshal: %v", err)+ }+ req := httptest.NewRequest(http.MethodPost, "/v1/ingest/batch", bytes.NewReader(body))+ req.Header.Set("Content-Type", "application/json")+ if credential != "" {+ req.Header.Set("Authorization", "Bearer "+credential)+ }+ if declaredTenant != "" {+ req.Header.Set("X-Tenant-ID", declaredTenant)+ }+ for _, opt := range opts {+ opt(req)+ }+ rec := httptest.NewRecorder()+ h.IngestEvents(rec, req)+ return rec+}++// ── the vulnerability, stated as a test ────────────────────────────────++func TestIngest_OneTenantsTokenCannotWriteIntoAnother(t *testing.T) {+ h, pub := newAuthHandler(t, "")++ // Vacuity guard, part one: Umbra is a real, active tenant whose own+ // token writes successfully. If this ever stops being true, the+ // refusal below stops proving anything.+ if rec := push(t, h, umbraToken, umbraTenant.String()); rec.Code != http.StatusOK {+ t.Fatalf("precondition: Umbra's own token must be able to write; got %d %s", rec.Code, rec.Body)+ }+ if got := pub.tenantsWritten(umbraTenant); got != 1 {+ t.Fatalf("precondition: expected 1 event for Umbra, got %d", got)+ }++ // Vacuity guard, part two: Acme's token is genuinely working — so a+ // refusal below is about the tenant it named, not about the token.+ if rec := push(t, h, acmeToken, acmeTenant.String()); rec.Code != http.StatusOK {+ t.Fatalf("precondition: Acme's own token must be able to write; got %d %s", rec.Code, rec.Body)+ }++ before := pub.tenantsWritten(umbraTenant)++ // The attack: a valid credential for Acme, naming Umbra's tenant.+ // This is exactly what an unauthenticated caller used to be able to+ // do with nothing but a UUID.+ rec := push(t, h, acmeToken, umbraTenant.String())+ if rec.Code != http.StatusForbidden {+ t.Fatalf("Acme's token naming Umbra must be refused with 403; got %d %s", rec.Code, rec.Body)+ }+ if after := pub.tenantsWritten(umbraTenant); after != before {+ t.Fatalf("a refused cross-tenant push still published %d event(s) into Umbra", after-before)+ }+ // And it must not have been silently redirected into Acme either:+ // narrowing to nothing means refusing, not falling back to the+ // credential's own tenant.+ if got := pub.tenantsWritten(acmeTenant); got != 1 {+ t.Fatalf("refused push should not publish anywhere; Acme has %d events, expected the 1 from the precondition", got)+ }+}++func TestIngest_ServiceTokenCannotReachAnUnseededTenant(t *testing.T) {+ h, pub := newAuthHandler(t, testServiceToken)++ // The delegated path works for a tenant that exists...+ if rec := push(t, h, testServiceToken, umbraTenant.String()); rec.Code != http.StatusOK {+ t.Fatalf("precondition: the service token must write for a real tenant; got %d %s", rec.Code, rec.Body)+ }+ if got := pub.tenantsWritten(umbraTenant); got != 1 {+ t.Fatalf("precondition: expected 1 event for Umbra, got %d", got)+ }++ // ...and refuses one that does not, rather than creating data under+ // a tenant id nobody owns.+ rec := push(t, h, testServiceToken, ghostTenant.String())+ if rec.Code != http.StatusForbidden {+ t.Fatalf("service token naming an unseeded tenant must be refused; got %d %s", rec.Code, rec.Body)+ }+ if got := pub.tenantsWritten(ghostTenant); got != 0 {+ t.Fatalf("published %d event(s) for a tenant that does not exist", got)+ }+}++func TestIngest_ServiceTokenMustDeclareTheTenantItActsFor(t *testing.T) {+ h, pub := newAuthHandler(t, testServiceToken)++ rec := push(t, h, testServiceToken, "")+ if rec.Code != http.StatusForbidden {+ t.Fatalf("a service token with no declared tenant must refuse, not widen; got %d %s", rec.Code, rec.Body)+ }+ if n := len(pub.published); n != 0 {+ t.Fatalf("an undeclared service push published %d event(s)", n)+ }+}++// A placeholder is not a tenant. The string "default" is the slug migration+// 001 seeds and the demo seed renames, so it identifies nothing — it must+// be read as "the caller did not name one" and resolve to the credential's+// own tenant, not treated as a tenant called "default".+func TestIngest_PlaceholderTenantRefResolvesToTheCredentialsOwnTenant(t *testing.T) {+ h, pub := newAuthHandler(t, "")++ for _, placeholder := range []string{"", "default", "none", "null"} {+ rec := push(t, h, acmeToken, placeholder)+ if rec.Code != http.StatusOK {+ t.Fatalf("placeholder %q should resolve to Acme, got %d %s", placeholder, rec.Code, rec.Body)+ }+ }+ if got := pub.tenantsWritten(acmeTenant); got != 4 {+ t.Fatalf("expected 4 events for Acme, got %d", got)+ }+}++// ── the unauthenticated hole itself ────────────────────────────────────++func TestIngest_RefusesWithNoCredential(t *testing.T) {+ h, pub := newAuthHandler(t, testServiceToken)++ // This is the exact request shape that used to succeed: a tenant UUID+ // in a header, nothing else.+ rec := push(t, h, "", umbraTenant.String())+ if rec.Code != http.StatusUnauthorized {+ t.Fatalf("an unauthenticated push must be 401; got %d %s", rec.Code, rec.Body)+ }+ if got := pub.tenantsWritten(umbraTenant); got != 0 {+ t.Fatalf("an unauthenticated push published %d event(s)", got)+ }+}++func TestIngest_RefusesWhenNoCredentialSourceIsConfigured(t *testing.T) {+ // No token store and no service token: the service cannot verify+ // anything, so it must refuse rather than accept unchecked. A+ // deployment that loses its database must not fail open.+ cfg := testConfig()+ norm, err := normalizer.New(cfg)+ if err != nil {+ t.Fatalf("normalizer: %v", err)+ }+ pub := &capturingPublisher{}+ h := New(norm, pub, cfg)+ h.SetAuthenticator(ingestauth.New(nil, nil, "", cfg.TenantHeaderKey))++ rec := push(t, h, acmeToken, acmeTenant.String())+ if rec.Code != http.StatusServiceUnavailable {+ t.Fatalf("unconfigured auth must refuse with 503; got %d %s", rec.Code, rec.Body)+ }+ if n := len(pub.published); n != 0 {+ t.Fatalf("unconfigured auth published %d event(s)", n)+ }+}++// A nil authenticator is a wiring regression, not a feature flag. It must+// refuse rather than read as "authentication not required here".+func TestIngest_NilAuthenticatorFailsClosed(t *testing.T) {+ cfg := testConfig()+ norm, err := normalizer.New(cfg)+ if err != nil {+ t.Fatalf("normalizer: %v", err)+ }+ pub := &capturingPublisher{}+ h := New(norm, pub, cfg)++ rec := push(t, h, acmeToken, acmeTenant.String())+ if rec.Code < 400 {+ t.Fatalf("a handler with no authenticator must refuse; got %d %s", rec.Code, rec.Body)+ }+ if n := len(pub.published); n != 0 {+ t.Fatalf("a handler with no authenticator published %d event(s)", n)+ }+}++// ── credential hygiene ─────────────────────────────────────────────────++func TestIngest_RevokedTokenIsRefused(t *testing.T) {+ h, pub := newAuthHandler(t, "")+ rec := push(t, h, "aitnb_revoked_cccccccccccccccccccc", acmeTenant.String())+ if rec.Code != http.StatusUnauthorized {+ t.Fatalf("a revoked token must be refused; got %d %s", rec.Code, rec.Body)+ }+ if n := len(pub.published); n != 0 {+ t.Fatalf("a revoked token published %d event(s)", n)+ }+}++// A token pasted into a vendor's webhook configuration is held by that+// vendor. It must not double as a general connector-push credential for+// the whole tenant, which is why the route is pinned to one template the+// same way /v1/inbox/cef and /v1/inbox/hec are.+func TestIngest_TokenMintedForAnotherTemplateIsRefused(t *testing.T) {+ h, pub := newAuthHandler(t, "")+ rec := push(t, h, "aitnb_pagerduty_webhook_dddddddddd", acmeTenant.String())+ if rec.Code != http.StatusForbidden {+ t.Fatalf("a pagerduty inbox token must not push to /v1/ingest; got %d %s", rec.Code, rec.Body)+ }+ if n := len(pub.published); n != 0 {+ t.Fatalf("a wrong-template token published %d event(s)", n)+ }+}++func TestIngest_SignedTokenRequiresAMatchingSignature(t *testing.T) {+ h, pub := newAuthHandler(t, "")+ const signed = "aitnb_acme_signed_eeeeeeeeeeeeeeee"++ if rec := push(t, h, signed, acmeTenant.String()); rec.Code != http.StatusUnauthorized {+ t.Fatalf("a token minted with an HMAC secret must require a signature; got %d %s", rec.Code, rec.Body)+ }++ wrong := func(r *http.Request) { r.Header.Set("X-Signature", "sha256=deadbeef") }+ if rec := push(t, h, signed, acmeTenant.String(), wrong); rec.Code != http.StatusUnauthorized {+ t.Fatalf("a bad signature must be refused; got %d %s", rec.Code, rec.Body)+ }+ if n := len(pub.published); n != 0 {+ t.Fatalf("unsigned/badly-signed pushes published %d event(s)", n)+ }++ // The happy path has to work, or the check above proves only that the+ // route is broken.+ sign := func(r *http.Request) {+ body := readAll(t, r)+ mac := hmac.New(sha256.New, []byte("shared-signing-secret"))+ mac.Write(body)+ r.Header.Set("X-Signature", "sha256="+hex.EncodeToString(mac.Sum(nil)))+ }+ if rec := push(t, h, signed, acmeTenant.String(), sign); rec.Code != http.StatusOK {+ t.Fatalf("a correctly signed push must succeed; got %d %s", rec.Code, rec.Body)+ }+ if got := pub.tenantsWritten(acmeTenant); got != 1 {+ t.Fatalf("expected the signed push to land 1 event for Acme, got %d", got)+ }+}++// readAll drains and restores a request body so a test option can sign it.+func readAll(t *testing.T, r *http.Request) []byte {+ t.Helper()+ buf := new(bytes.Buffer)+ if _, err := buf.ReadFrom(r.Body); err != nil {+ t.Fatalf("read body: %v", err)+ }+ body := buf.Bytes()+ r.Body = httptest.NewRequest(http.MethodPost, "/", bytes.NewReader(body)).Body+ return body+}++// ── the resolver's own contract ────────────────────────────────────────++func TestResolve_IsIntersectionOnly(t *testing.T) {+ acme := ingestauth.NewPrincipal("token:...aaaa", false, acmeTenant)++ if _, err := ingestauth.Resolve(acme, umbraTenant.String()); err == nil {+ t.Fatal("resolving a tenant outside the principal must fail")+ }+ got, err := ingestauth.Resolve(acme, acmeTenant.String())+ if err != nil || got != acmeTenant {+ t.Fatalf("resolving the principal's own tenant must succeed; got %v %v", got, err)+ }+ if _, err := ingestauth.Resolve(ingestauth.NewPrincipal("nobody", false), acmeTenant.String()); err == nil {+ t.Fatal("an empty principal must refuse rather than widen")+ }+ if _, err := ingestauth.Resolve(acme, "not-a-uuid"); err == nil {+ t.Fatal("a non-UUID tenant ref must be refused")+ }+}++// A credential that reaches several tenants must be made to name one,+// rather than having one picked for it.+func TestResolve_MultiTenantPrincipalMustNameATenant(t *testing.T) {+ both := ingestauth.NewPrincipal("service", true, acmeTenant, umbraTenant)+ if _, err := ingestauth.Resolve(both, ""); err == nil {+ t.Fatal("a multi-tenant principal with no named tenant must refuse")+ }+ for _, want := range []uuid.UUID{acmeTenant, umbraTenant} {+ got, err := ingestauth.Resolve(both, want.String())+ if err != nil || got != want {+ t.Fatalf("naming %v should resolve to it; got %v %v", want, got, err)+ }+ }+ if _, err := ingestauth.Resolve(both, ghostTenant.String()); err == nil {+ t.Fatal("a multi-tenant principal must still refuse a tenant outside its scope")+ }+}++func TestFingerprint_NeverReturnsTheCredential(t *testing.T) {+ for _, token := range []string{acmeToken, "short", ""} {+ fp := ingestauth.Fingerprint(token)+ if fp == token {+ t.Fatalf("fingerprint of %q returned the credential itself", token)+ }+ if len(token) > 8 && fmt.Sprintf("...%s", token[len(token)-8:]) != fp {+ t.Fatalf("unexpected fingerprint %q for %q", fp, token)+ }+ }+}diff --git a/services/ingest/internal/ingestauth/authenticator.go b/services/ingest/internal/ingestauth/authenticator.gonew file mode 100644index 000000000..1a4a96636--- /dev/null+++ b/services/ingest/internal/ingestauth/authenticator.go@@ -0,0 +1,304 @@+package ingestauth++import (+ "context"+ "crypto/hmac"+ "crypto/sha256"+ "crypto/subtle"+ "encoding/hex"+ "errors"+ "fmt"+ "net/http"+ "slices"+ "strings"++ "github.com/beenuar/aisoc/services/ingest/internal/inbox"+ "github.com/google/uuid"+)++// PushTemplateID is the template a token must be minted with before it can+// push to /v1/ingest.+//+// The route is pinned to one template for the same reason /v1/inbox/cef+// and /v1/inbox/hec are: an inbox token is pasted into a third party's+// webhook configuration, so PagerDuty holds one, Cloudflare holds another.+// Without the pin, any of those vendors could replay their own URL's token+// against /v1/ingest and write arbitrary connector events for the tenant.+// Minting a connector-push token is a separate, deliberate act.+//+// Like itsm-inbound, this id has no YAML in the normalizer's template+// directory — it names a credential purpose, not a payload mapping, and+// /v1/ingest normalizes through connectorProfiles rather than a template.+// scripts/check_inbox_templates.py records that exemption in both+// directions so the two sets cannot drift apart unnoticed.+const PushTemplateID = "connector-push"++// DefaultTenantHeaders are the headers a caller may use to name the tenant+// it is writing for. X-Tenant-ID is this service's own spelling and is what+// services/connectors already sends; X-AiSOC-Tenant-ID is the platform+// convention used by the Python services' tenant_scope. Both are only ever+// intersected with the credential's scope, never trusted on their own.+var DefaultTenantHeaders = []string{"X-Tenant-ID", "X-AiSOC-Tenant-ID"}++// TokenResolver is the subset of *inbox.Store this package needs, declared+// as an interface so the tenant-derivation logic can be tested without a+// Postgres pool.+type TokenResolver interface {+ Resolve(ctx context.Context, token string) (*inbox.Token, error)+}++// TenantDirectory answers whether a tenant exists and is active. Used only+// for the service-token path: a minted token's tenant_id carries a foreign+// key to tenants(id), so resolving the token has already proved the tenant+// exists, whereas a service token's asserted tenant is just a string until+// somebody checks.+type TenantDirectory interface {+ IsActive(ctx context.Context, id uuid.UUID) (bool, error)+}++// Error carries the status and the client-facing message for a refused+// request, so the handler does not have to re-derive either.+type Error struct {+ Status int+ Msg string+}++func (e *Error) Error() string { return e.Msg }++// Identity is the outcome of authenticating one request.+type Identity struct {+ Principal Principal+ // HMACSecret is non-empty when the presented token was minted with a+ // signature secret, in which case the body must carry a matching+ // X-Signature. Empty means the token itself is the only authenticator.+ HMACSecret string+}++// Authenticator resolves a credential into the set of tenants it may write+// for. A nil Authenticator refuses everything, which is the posture we want+// if wiring ever regresses: a missing authenticator must not read as an+// absent requirement.+type Authenticator struct {+ tokens TokenResolver+ tenants TenantDirectory+ serviceToken string+ tenantHeaders []string+}++// New builds an Authenticator.+//+// tokens and tenants may be nil when the service has no database — in that+// case only the service-token path can work, and if serviceToken is empty+// too the authenticator refuses every request with 503. That is deliberate:+// an ingest service that cannot check a credential must stop accepting+// writes, not accept them unchecked.+//+// tenantHeader is the deployment's configured spelling (TENANT_HEADER_KEY).+// It is tried before the defaults so that customising it moves both the+// credential's tenant declaration and the header we intersect against+// together — changing one without the other is how a header ends up+// silently ignored on one of the two paths.+func New(tokens TokenResolver, tenants TenantDirectory, serviceToken, tenantHeader string) *Authenticator {+ headers := make([]string, 0, len(DefaultTenantHeaders)+1)+ if h := strings.TrimSpace(tenantHeader); h != "" {+ headers = append(headers, h)+ }+ for _, h := range DefaultTenantHeaders {+ if !slices.Contains(headers, h) {+ headers = append(headers, h)+ }+ }+ return &Authenticator{+ tokens: tokens,+ tenants: tenants,+ serviceToken: strings.TrimSpace(serviceToken),+ tenantHeaders: headers,+ }+}++// DeclaredTenant returns the tenant the caller named, from whichever+// accepted header carries one. The value is never authoritative on its own+// — Resolve intersects it with the credential's scope.+func (a *Authenticator) DeclaredTenant(r *http.Request) string {+ headers := DefaultTenantHeaders+ if a != nil && len(a.tenantHeaders) > 0 {+ headers = a.tenantHeaders+ }+ for _, h := range headers {+ if v := strings.TrimSpace(r.Header.Get(h)); v != "" {+ return v+ }+ }+ return ""+}++// Configured reports whether any credential shape can be verified at all.+// main uses it to log the refusal loudly at startup rather than leaving an+// operator to discover it as a 503 per request.+func (a *Authenticator) Configured() bool {+ if a == nil {+ return false+ }+ return a.tokens != nil || a.serviceToken != ""+}++// Authenticate resolves the request's credential into an Identity.+//+// Two credential shapes reach this route, mirroring tenant_scope.py:+//+// tenant push token — a row in tenant_inbox_tokens minted with the+// connector-push template. It carries its own tenant_id, which is a+// foreign key into tenants(id), so the tenant is proved by the+// lookup rather than asserted by the caller.+// service token — the shared secret for service-to-service pushes+// (services/connectors polls on behalf of many tenants). It+// identifies a trusted service, not a tenant, so a caller presenting+// it must also declare which tenant it is acting for. The+// declaration is explicit and required: no tenant header resolves to+// an empty scope, and an empty scope refuses rather than widening.+func (a *Authenticator) Authenticate(ctx context.Context, r *http.Request) (Identity, error) {+ if a == nil || !a.Configured() {+ return Identity{}, &Error{+ Status: http.StatusServiceUnavailable,+ Msg: "ingest authentication is not configured on this deployment: set AISOC_SERVICE_TOKEN " ++ "for service-to-service pushes, or DATABASE_DSN so minted push tokens can be resolved",+ }+ }++ credential := CredentialFromRequest(r)+ if credential == "" {+ return Identity{}, &Error{+ Status: http.StatusUnauthorized,+ Msg: "missing ingest credential: send 'Authorization: Bearer <token>' with a token minted by " ++ "POST /api/v1/inbox/tokens using the connector-push template",+ }+ }++ if a.serviceToken != "" && subtle.ConstantTimeCompare([]byte(credential), []byte(a.serviceToken)) == 1 {+ return a.authenticateService(ctx, r)+ }++ if a.tokens == nil {+ return Identity{}, &Error{+ Status: http.StatusServiceUnavailable,+ Msg: "minted push tokens cannot be resolved on this deployment (no DATABASE_DSN)",+ }+ }++ tok, err := a.tokens.Resolve(ctx, credential)+ if err != nil {+ switch {+ case errors.Is(err, inbox.ErrTokenNotFound):+ return Identity{}, &Error{Status: http.StatusUnauthorized, Msg: "unrecognised ingest credential"}+ case errors.Is(err, inbox.ErrTokenRevoked):+ return Identity{}, &Error{+ Status: http.StatusUnauthorized,+ Msg: "this ingest token has been revoked; mint a new one",+ }+ default:+ return Identity{}, &Error{Status: http.StatusServiceUnavailable, Msg: "temporary credential lookup failure"}+ }+ }++ if tok.TemplateID != PushTemplateID {+ return Identity{}, &Error{+ Status: http.StatusForbidden,+ Msg: fmt.Sprintf("this token was minted for the %q template; /v1/ingest requires one minted "++ "with the %q template", tok.TemplateID, PushTemplateID),+ }+ }++ return Identity{+ Principal: NewPrincipal("token:"+Fingerprint(tok.Token), false, tok.TenantID),+ HMACSecret: tok.HMACSecret,+ }, nil+}++// authenticateService handles the trusted-service shape. The tenant comes+// from the header here — that is the point of a delegated credential — but+// it is checked against the tenants table before it becomes a scope, so a+// service token cannot write into a tenant that does not exist or has been+// deactivated.+func (a *Authenticator) authenticateService(ctx context.Context, r *http.Request) (Identity, error) {+ declared := a.DeclaredTenant(r)+ if declared == "" {+ return Identity{}, &Error{+ Status: http.StatusForbidden,+ Msg: "a service token must declare the tenant it is acting for on the " ++ a.tenantHeaders[0] + " header",+ }+ }+ id, err := uuid.Parse(declared)+ if err != nil {+ return Identity{}, &Error{Status: http.StatusBadRequest, Msg: "declared tenant is not a UUID"}+ }+ if a.tenants == nil {+ return Identity{}, &Error{+ Status: http.StatusServiceUnavailable,+ Msg: "cannot validate the declared tenant on this deployment (no DATABASE_DSN)",+ }+ }+ active, err := a.tenants.IsActive(ctx, id)+ if err != nil {+ return Identity{}, &Error{Status: http.StatusServiceUnavailable, Msg: "temporary tenant lookup failure"}+ }+ if !active {+ // One message for "no such tenant" and "deactivated": a service+ // token is trusted, but the response should still not be a probe+ // for which tenant UUIDs exist.+ return Identity{}, &Error{Status: http.StatusForbidden, Msg: "declared tenant is unknown or inactive"}+ }+ return Identity{Principal: NewPrincipal("service", true, id)}, nil+}++// VerifySignature enforces the optional HMAC-SHA256 body signature when the+// presented token was minted with a secret. Same headers and same+// constant-time comparison as the inbox routes, so an operator who has+// signed one push path already knows how to sign this one.+func VerifySignature(r *http.Request, id Identity, body []byte) error {+ if id.HMACSecret == "" {+ return nil+ }+ provided := r.Header.Get("X-Signature")+ if provided == "" {+ provided = r.Header.Get("X-Hub-Signature-256")+ }+ if provided == "" {+ return &Error{+ Status: http.StatusUnauthorized,+ Msg: "this token requires a body signature (set X-Signature: sha256=<hex>)",+ }+ }+ mac := hmac.New(sha256.New, []byte(id.HMACSecret))+ mac.Write(body)+ expected := hex.EncodeToString(mac.Sum(nil))+ if !hmac.Equal([]byte(strings.TrimPrefix(provided, "sha256=")), []byte(expected)) {+ return &Error{Status: http.StatusUnauthorized, Msg: "HMAC signature mismatch"}+ }+ return nil+}++// CredentialFromRequest pulls the presented credential from Authorization+// (Bearer / Splunk / bare) or X-Inbox-Token, matching tokenFromHeaders in+// the inbox package so both push paths accept the same header shapes.+func CredentialFromRequest(r *http.Request) string {+ if v := r.Header.Get("Authorization"); v != "" {+ parts := strings.Fields(v)+ switch len(parts) {+ case 1:+ return parts[0]+ case 2:+ return parts[1]+ }+ }+ return r.Header.Get("X-Inbox-Token")+}++// Fingerprint reduces a credential to something safe to log — the same+// trailing-8 form services/api uses when it records a mint.+func Fingerprint(token string) string {+ if len(token) > 8 {+ return "..." + token[len(token)-8:]+ }+ return "...<short>"+}diff --git a/services/ingest/internal/ingestauth/principal.go b/services/ingest/internal/ingestauth/principal.gonew file mode 100644index 000000000..fdb6307a7--- /dev/null+++ b/services/ingest/internal/ingestauth/principal.go@@ -0,0 +1,122 @@+// Package ingestauth resolves which tenant a /v1/ingest request may write+// for, from the caller's credential rather than from a header the caller+// chose.+//+// Why this exists+// ---------------+// POST /v1/ingest/batch — the endpoint the README tells users to push+// telemetry to, and the one `make smoke` exercises — took its tenant from+// the X-Tenant-ID header and authenticated nothing. Any caller who could+// reach the port could write alerts into any tenant by typing that tenant's+// UUID. Compose binds the port to 127.0.0.1, which contains it locally, but+// ingesting real telemetry means exposing it, and nothing said so at the+// moment the operator did.+//+// Validating the header's *value* does not fix that. A UUID that parses is+// still a UUID the caller chose. The scope has to come from somewhere the+// caller does not control, which means the credential.+//+// This is a Go port of the semantics in services/api/app/security/+// tenant_scope.py, which the Python services already use for exactly this+// problem. Same two credential shapes, same intersection-only rule, same+// refusal on an empty scope. Keeping the reasoning identical across the two+// runtimes matters more than sharing code we cannot share.+package ingestauth++import (+ "fmt"+ "strings"++ "github.com/google/uuid"+)++// Principal is the set of tenants one credential may write for, and what+// kind of credential said so.+//+// tenantIDs is authoritative and exhaustive. Nothing downstream may widen+// it, and no code path may substitute "every tenant" for an empty one —+// every cross-tenant leak this codebase has had took that shape, a scope+// that was absent rather than narrow and a write that read absent as+// "no filter".+type Principal struct {+ tenantIDs map[uuid.UUID]struct{}+ // Subject names the credential for logs. It is never the credential+ // itself: minted tokens are reduced to a trailing fingerprint.+ Subject string+ // Delegated is true when a service token asserted the tenant rather+ // than the credential carrying it. Surfaced so logs can tell a+ // trusted internal push apart from a tenant's own.+ Delegated bool+}++// NewPrincipal builds a principal over the given tenants. Passing none+// yields the empty principal, which refuses everything.+func NewPrincipal(subject string, delegated bool, ids ...uuid.UUID) Principal {+ set := make(map[uuid.UUID]struct{}, len(ids))+ for _, id := range ids {+ set[id] = struct{}{}+ }+ return Principal{tenantIDs: set, Subject: subject, Delegated: delegated}+}++// IsEmpty reports whether this credential authorises no tenant at all.+func (p Principal) IsEmpty() bool { return len(p.tenantIDs) == 0 }++// Covers reports whether this credential authorises writes for id.+func (p Principal) Covers(id uuid.UUID) bool {+ _, ok := p.tenantIDs[id]+ return ok+}++// Size is the number of tenants this credential reaches.+func (p Principal) Size() int { return len(p.tenantIDs) }++// placeholderTenantRefs are values that mean "the caller did not name a+// tenant" rather than naming one. Migration 001 seeds the canonical tenant+// with the *slug* "default" and the demo seed renames it, so the literal+// identifies nothing anywhere; treating it as a tenant named "default"+// would refuse every caller who simply left the field alone.+var placeholderTenantRefs = map[string]struct{}{+ "": {}, "default": {}, "none": {}, "null": {},+}++// ScopeError is returned when a write was attempted without a resolved+// tenant scope, or for a tenant outside the credential's scope. Callers+// surface it as 403: it means a write was about to run untenanted, or+// into somebody else's data.+type ScopeError struct{ msg string }++func (e *ScopeError) Error() string { return e.msg }++// Resolve returns the one tenant this request may write for, or refuses.+//+// Intersection only. A requested tenant inside the principal's scope is+// honoured — that is how a trusted service names the tenant it is acting+// for. A requested tenant outside it narrows to nothing and raises, rather+// than reaching outside. An empty requested value means "the caller's own+// tenant", which is the common case and the safe default.+func Resolve(p Principal, requested string) (uuid.UUID, error) {+ if p.IsEmpty() {+ return uuid.Nil, &ScopeError{"refusing to ingest with an empty tenant scope"}+ }++ if _, isPlaceholder := placeholderTenantRefs[strings.ToLower(strings.TrimSpace(requested))]; isPlaceholder {+ if p.Size() != 1 {+ return uuid.Nil, &ScopeError{+ fmt.Sprintf("credential reaches %d tenants; the request must name one", p.Size()),+ }+ }+ for id := range p.tenantIDs {+ return id, nil+ }+ }++ wanted, err := uuid.Parse(strings.TrimSpace(requested))+ if err != nil {+ return uuid.Nil, &ScopeError{"requested tenant is not a UUID"}+ }+ if !p.Covers(wanted) {+ return uuid.Nil, &ScopeError{"requested tenant is outside the credential's authorised scope"}+ }+ return wanted, nil+}diff --git a/services/ingest/internal/ingestauth/tenants.go b/services/ingest/internal/ingestauth/tenants.gonew file mode 100644index 000000000..921350b40--- /dev/null+++ b/services/ingest/internal/ingestauth/tenants.go@@ -0,0 +1,98 @@+package ingestauth++import (+ "context"+ "errors"+ "fmt"+ "sync"+ "time"++ "github.com/google/uuid"+ "github.com/jackc/pgx/v5"+ "github.com/jackc/pgx/v5/pgxpool"+)++// PgTenantDirectory checks a declared tenant against the tenants table,+// with a short-TTL cache in front.+//+// Both outcomes are cached, not just the hit. A forged tenant UUID is+// exactly the traffic a service-token holder would generate if it were+// compromised or misconfigured, and an uncached miss turns each one into a+// database round-trip — so the negative cache is the part that keeps a+// flood of bad UUIDs from becoming a second outage on top of the first.+type PgTenantDirectory struct {+ pool *pgxpool.Pool++ mu sync.RWMutex+ cache map[uuid.UUID]cachedTenant+ ttl time.Duration+ max int+}++type cachedTenant struct {+ active bool+ expires time.Time+}++// NewTenantDirectory wraps a pgx pool. The 60s TTL matches the inbox token+// cache: a tenant deactivated in the console stops being writable within a+// minute, which is the same staleness window an operator already accepts+// when they revoke an inbox token.+func NewTenantDirectory(pool *pgxpool.Pool) *PgTenantDirectory {+ return &PgTenantDirectory{+ pool: pool,+ cache: make(map[uuid.UUID]cachedTenant),+ ttl: 60 * time.Second,+ max: 4096,+ }+}++// IsActive reports whether the tenant exists and has not been deactivated.+//+// A lookup failure is returned as an error rather than as "not active", so+// the caller answers 503 instead of 403. Telling a correctly-credentialled+// service that its tenant is unknown, when the truth is that Postgres+// blinked, sends an operator to the wrong problem.+func (d *PgTenantDirectory) IsActive(ctx context.Context, id uuid.UUID) (bool, error) {+ d.mu.RLock()+ entry, ok := d.cache[id]+ d.mu.RUnlock()+ if ok && time.Now().Before(entry.expires) {+ return entry.active, nil+ }++ var active bool+ err := d.pool.QueryRow(ctx,+ `SELECT COALESCE(is_active, TRUE) FROM tenants WHERE id = $1`, id,+ ).Scan(&active)+ if err != nil {+ if errors.Is(err, pgx.ErrNoRows) {+ d.remember(id, false)+ return false, nil+ }+ return false, fmt.Errorf("ingestauth: tenant lookup failed: %w", err)+ }++ d.remember(id, active)+ return active, nil+}++func (d *PgTenantDirectory) remember(id uuid.UUID, active bool) {+ d.mu.Lock()+ defer d.mu.Unlock()+ if len(d.cache) >= d.max {+ now := time.Now()+ for k, v := range d.cache {+ if now.After(v.expires) {+ delete(d.cache, k)+ }+ }+ if len(d.cache) >= d.max {+ for k := range d.cache {+ delete(d.cache, k)+ break+ }+ }+ }+ d.cache[id] = cachedTenant{active: active, expires: time.Now().Add(d.ttl)}+}diff --git a/services/ingest/internal/server/server.go b/services/ingest/internal/server/server.goindex f6eef27d1..d3d9ba8af 100644--- a/services/ingest/internal/server/server.go+++ b/services/ingest/internal/server/server.go@@ -86,10 +86,18 @@ func New(cfg *config.Config, h *handler.Handler, inboxHandler *inbox.Handler, gr// Allow-list is resolved from AISOC_CORS_ORIGINS (canonical) / CORS_ORIGINS// (legacy) with a safe default that covers local dev only; deployed// origins are expected to set the env var.- // AllowCredentials stays false here — /v1/ingest is token-authenticated- // per request, not session-cookie-authenticated, so we don't need the- // browser to attach cookies cross-origin and we keep the spec-mandated- // rejection of "*"+credentials safely impossible.+ // AllowCredentials stays false here. Every route on this service is+ // authenticated by a credential the caller presents per request — a+ // minted push token or a service token on /v1/ingest, an inbox token+ // on /v1/inbox/*, the shared secret on /v1/ingest/k8s-audit — and+ // never by a session cookie, so the browser has no reason to attach+ // one cross-origin and the spec-mandated rejection of+ // "*"+credentials stays safely impossible.+ //+ // This comment previously asserted that /v1/ingest was+ // token-authenticated per request. It was not: the handler read a+ // caller-supplied X-Tenant-ID header and checked nothing. The claim+ // is true as of the credential check in internal/ingestauth.r.Use(cors.Handler(cors.Options{AllowedOrigins: resolveCORSOrigins(),AllowedMethods: []string{"GET", "POST", "OPTIONS"},diff --git a/services/ingest/main.go b/services/ingest/main.goindex 742461408..2f8d3c0bc 100644--- a/services/ingest/main.go+++ b/services/ingest/main.go@@ -19,6 +19,7 @@ import ("github.com/beenuar/aisoc/services/ingest/internal/graph_ws""github.com/beenuar/aisoc/services/ingest/internal/handler""github.com/beenuar/aisoc/services/ingest/internal/inbox"+ "github.com/beenuar/aisoc/services/ingest/internal/ingestauth""github.com/beenuar/aisoc/services/ingest/internal/normalizer""github.com/beenuar/aisoc/services/ingest/internal/publisher""github.com/beenuar/aisoc/services/ingest/internal/server"@@ -163,42 +164,81 @@ func main() {// to find the matching template. Both are optional in dev (no// DATABASE_DSN means /v1/inbox/* is disabled but /v1/ingest still// works, so the connector path keeps running).- var inboxHandler *inbox.Handler- if cfg.InboxEnabled && cfg.DatabaseDSN != "" {+ // One Postgres pool serves two consumers: the inbox token resolver and+ // the /v1/ingest credential check. It is opened whenever DATABASE_DSN+ // is set rather than only when the inbox is enabled, because turning+ // the inbox off must not also remove the ability to authenticate a+ // connector push.+ var dbPool *pgxpool.Pool+ if cfg.DatabaseDSN != "" {poolCtx, poolCancel := context.WithTimeout(context.Background(), 10*time.Second)pool, err := pgxpool.New(poolCtx, cfg.DatabaseDSN)poolCancel()if err != nil {- log.Warn().Err(err).Msg("Failed to connect to Postgres for inbox; /v1/inbox/* disabled")+ log.Error().Err(err).+ Msg("Failed to connect to Postgres; minted ingest tokens cannot be resolved and /v1/inbox/* is disabled")} else {defer pool.Close()- store := inbox.NewStore(pool)- registry := inbox.NewRegistry()- // Embedded first — these ship in the binary and are the set the- // service is tested against. The on-disk directory is an operator- // override layered on top, and is allowed to be absent.- if err := registry.LoadEmbedded(); err != nil {- log.Error().Err(err).- Msg("Failed to load embedded inbox templates; /v1/inbox/* will return 503 for every template")- }- if err := registry.Load(cfg.InboxTemplatesDir); err != nil {- log.Warn().Err(err).Str("dir", cfg.InboxTemplatesDir).- Msg("Failed to load inbox template overrides from disk")- }- log.Info().- Strs("templates", registry.IDs()).- Int64("max_body_bytes", cfg.InboxMaxBodyBytes).- Float64("rate_requests_per_second", cfg.InboxRateRequestsPerSecond).- Float64("rate_events_per_second", cfg.InboxRateEventsPerSecond).- Msg("inbox: universal-capture push paths enabled")- inboxHandler = inbox.NewHandler(store, registry, pub, cfg.InboxMaxBodyBytes).- WithLimiter(inbox.NewLimiter(- cfg.InboxRateRequestsPerSecond,- cfg.InboxRateRequestBurst,- cfg.InboxRateEventsPerSecond,- cfg.InboxRateEventBurst,- ))+ dbPool = pool+ }+ }++ // /v1/ingest credential check. Before this the endpoint read a tenant+ // out of a header and authenticated nothing, so anyone who could reach+ // the port could write alerts into any tenant.+ var (+ tokenStore *inbox.Store+ tokenResolver ingestauth.TokenResolver+ tenantDirectory ingestauth.TenantDirectory+ )+ if dbPool != nil {+ tokenStore = inbox.NewStore(dbPool)+ tokenResolver = tokenStore+ tenantDirectory = ingestauth.NewTenantDirectory(dbPool)+ }+ auth := ingestauth.New(tokenResolver, tenantDirectory, cfg.ServiceToken, cfg.TenantHeaderKey)+ h.SetAuthenticator(auth)+ if auth.Configured() {+ log.Info().+ Bool("minted_tokens", tokenResolver != nil).+ Bool("service_token", cfg.ServiceToken != "").+ Msg("ingest: /v1/ingest requires an authenticated, tenant-scoped credential")+ } else {+ // Loud, and at error: this deployment will refuse every push. A+ // warning here would be indistinguishable from the ordinary+ // startup chatter an operator scrolls past.+ log.Error().+ Msg("ingest: no credential source configured — /v1/ingest will refuse every request. " ++ "Set DATABASE_DSN so minted push tokens resolve, or AISOC_SERVICE_TOKEN for service-to-service pushes")+ }++ var inboxHandler *inbox.Handler+ if cfg.InboxEnabled && tokenStore != nil {+ registry := inbox.NewRegistry()+ // Embedded first — these ship in the binary and are the set the+ // service is tested against. The on-disk directory is an operator+ // override layered on top, and is allowed to be absent.+ if err := registry.LoadEmbedded(); err != nil {+ log.Error().Err(err).+ Msg("Failed to load embedded inbox templates; /v1/inbox/* will return 503 for every template")+ }+ if err := registry.Load(cfg.InboxTemplatesDir); err != nil {+ log.Warn().Err(err).Str("dir", cfg.InboxTemplatesDir).+ Msg("Failed to load inbox template overrides from disk")}+ log.Info().+ Strs("templates", registry.IDs()).+ Int64("max_body_bytes", cfg.InboxMaxBodyBytes).+ Float64("rate_requests_per_second", cfg.InboxRateRequestsPerSecond).+ Float64("rate_events_per_second", cfg.InboxRateEventsPerSecond).+ Msg("inbox: universal-capture push paths enabled")+ inboxHandler = inbox.NewHandler(tokenStore, registry, pub, cfg.InboxMaxBodyBytes).+ WithLimiter(inbox.NewLimiter(+ cfg.InboxRateRequestsPerSecond,+ cfg.InboxRateRequestBurst,+ cfg.InboxRateEventsPerSecond,+ cfg.InboxRateEventBurst,+ ))} else if !cfg.InboxEnabled {log.Info().Msg("inbox: disabled via INBOX_ENABLED=false")} else {diff --git a/tests/e2e/golden_pipeline/run_golden_pipeline.py b/tests/e2e/golden_pipeline/run_golden_pipeline.pyindex 4025f44b3..427054a9e 100755--- a/tests/e2e/golden_pipeline/run_golden_pipeline.py+++ b/tests/e2e/golden_pipeline/run_golden_pipeline.py@@ -22,13 +22,23 @@ Usagepython3 tests/e2e/golden_pipeline/run_golden_pipeline.py-Environment (all optional; defaults match `docker compose up`):-- AISOC_INGEST_URL default http://localhost:8081- AISOC_API_URL default http://localhost:8000- AISOC_TENANT_ID default the seeded canonical tenant+Environment:++ AISOC_INGEST_TOKEN required — the credential /v1/ingest/batch needs.+ `make smoke` mints it for you; by hand it is+ `docker compose run --rm -T api \+ python -m app.scripts.mint_ingest_token --quiet`+ AISOC_INGEST_URL default http://localhost:8081+ AISOC_API_URL default http://localhost:8000+ AISOC_TENANT_ID default the seeded canonical tenantAISOC_GOLDEN_TIMEOUT seconds to wait for the alert (default 90)+The token is required rather than optional, and there is no unauthenticated+fallback. /v1/ingest/batch used to accept anything that named a tenant, and+this test was one of the callers relying on that. Letting it keep working+without a credential would mean the gate no longer exercises the path a real+push takes.+Exit code is 0 only when every stage passes."""@@ -47,6 +57,7 @@ INGEST_URL = os.environ.get("AISOC_INGEST_URL", "http://localhost:8081").rstrip(API_URL = os.environ.get("AISOC_API_URL", "http://localhost:8000").rstrip("/")TENANT_ID = os.environ.get("AISOC_TENANT_ID", "00000000-0000-0000-0000-000000000001")TIMEOUT_SECONDS = int(os.environ.get("AISOC_GOLDEN_TIMEOUT", "90"))+INGEST_TOKEN = os.environ.get("AISOC_INGEST_TOKEN", "").strip()#: Unique per run so a re-run cannot pass by finding the previous run's alert#: — the failure mode that makes an end-to-end test permanently green.@@ -72,11 +83,19 @@ class Report:return all(ok for _, ok, _ in self.stages)-def _request(method: str, url: str, body: dict | None = None, timeout: float = 20.0) -> tuple[int, str]:+def _request(+ method: str,+ url: str,+ body: dict | None = None,+ timeout: float = 20.0,+ headers: dict[str, str] | None = None,+) -> tuple[int, str]:data = json.dumps(body).encode() if body is not None else Nonereq = urllib.request.Request(url, data=data, method=method)req.add_header("Content-Type", "application/json")req.add_header("X-Tenant-ID", TENANT_ID)+ for name, value in (headers or {}).items():+ req.add_header(name, value)try:with urllib.request.urlopen(req, timeout=timeout) as resp: # noqa: S310 - fixed local URLsreturn resp.status, resp.read().decode("utf-8", "replace")@@ -130,8 +149,36 @@ def main() -> int:if not r.record("api service is reachable", status == 200, f"HTTP {status}" if status != 200 else ""):return _finish(r)- # ── 2. Raw telemetry is accepted ─────────────────────────────────────+ # ── 2. Raw telemetry is accepted, with a credential ──────────────────+ if not r.record(+ "an ingest credential is available",+ bool(INGEST_TOKEN),+ "" if INGEST_TOKEN else "AISOC_INGEST_TOKEN is unset",+ ):+ print("\n /v1/ingest/batch requires a credential. Mint one:")+ print(" docker compose run --rm -T api python -m app.scripts.mint_ingest_token")+ print(" then re-run, or just use `make smoke`, which does both.")+ return _finish(r)++ # The same push with no credential must be refused. This lives in the+ # golden pipeline, not only in the Go unit tests, because it is the one+ # check that observes the deployed service from outside — and because+ # the happy path below would go on passing if authentication were+ # removed tomorrow.status, body = _request("POST", f"{INGEST_URL}/v1/ingest/batch", golden_event(), timeout=30)+ r.record(+ "an unauthenticated push is refused",+ status in (401, 403),+ f"HTTP {status} {body[:100]}",+ )++ status, body = _request(+ "POST",+ f"{INGEST_URL}/v1/ingest/batch",+ golden_event(),+ timeout=30,+ headers={"Authorization": f"Bearer {INGEST_TOKEN}"},+ )accepted = 0if status == 200:try:@@ -143,6 +190,9 @@ def main() -> int:status == 200 and accepted == 1,f"HTTP {status} {body[:140]}",):+ if status in (401, 403):+ print("\n The credential was refused. Mint a current one:")+ print(" docker compose run --rm -T api python -m app.scripts.mint_ingest_token --rotate")# The single most common cause, worth naming rather than making the# reader search: the broker refuses the first publish when the topic# does not exist and cannot be auto-created.