mirror of
https://github.com/beenuar/AiSOC.git
synced 2026-12-02 18:39:39 +08:00
f4cea19023c331c052d1585e45ec76cc4f7fcab7
7
Commits
| Author | SHA1 | Message | Date | |
|---|---|---|---|---|
|
|
3364706565 |
docs: correct the statements recent work made false (#1229)
* docs: correct the statements recent work made false
A sweep of the 375 tracked Markdown/MDX files outside `plans/`, plus every
URL they ship. 50 files corrected, 0 deleted. The ranking is by how wrong a
statement was, not by how visible the page is.
Capabilities described as absent that now exist. The depth wave gave readers
to ABAC conditions, time-boxed elevation and workload identities, shipped
console TOTP, and made the playbook `approval` step a durable pause — and
five documents still said none of that existed. The buyer-facing security
questionnaire was the worst of them: four gap-list rows and two prose answers
telling a prospect that controls they were evaluating us on were absent. Its
own sibling page `access-governance.md` documented those controls and was
missing from the pack index, which is how the contradiction survived.
Capabilities described that do not exist. `faq.md` answered "can I delete a
user's data on request?" with "Yes" and a route — `DELETE
/api/v1/identity/{user_id}/data` — that appears nowhere in the code or in
`docs/openapi.yaml`, while `data-handling.md` says in as many words that no
such route is in the tree. `live-actions.md` called `POST
/api/v1/live-actions/dispatch` "one entry point" for the agent layer; the API
deliberately proxies only `/dry-run`, and its handler says so. The same page
documented `tenant_id` and `requested_by` as caller-supplied fields.
Counts re-derived from the tree, not carried over: executable detections
2,603 -> 2,529 (down, because rules that could not fire stopped being
counted), unreachable 119 -> 45, windowed 5 -> 72, YAML under `detections/`
7,016 -> 7,022, `/metrics` coverage 5-of-17 -> 5-of-19, connectors 69/84 ->
87, marketplace 7,155 -> 7,158, playbook step types 9 -> 25.
Links: every external URL fetched. `docs.tryaisoc.com` does not resolve at
all and was linked from two example pages — sentences rewritten, hostname
allow-list entries removed rather than re-counted, since the exemption had
claimed they were "accurate as written". Sigstore, Wazuh and MITRE CAR links
repointed at destinations that answer 200. Nine internal links fixed,
including two to `PROGRESS.md`, which is gitignored and has never been
committed.
Self-contradictions resolved in place: `observability.md` said both that the
Kafka spine's ends are instrumented and that they are not — the limitation is
real but its stated cause changed, and the bullet now gives the current one.
* docs: carry the corrected detection figure through every surface
#1226 landed the 3.3 corpus correction and the executable figure moved
again, 2529 -> 2511, for the same reason as the first move: rules that
cannot fire stopped being counted as capable of it.
Seventeen documents still carried the old number — the architecture page,
the glossary, the intro, the FAQ, the detections concept page, three
design briefs, two contributing guides, the repository-reality audit and
the claim matrix. A figure copied into prose goes stale silently, which is
why it is re-derived here rather than edited by hand in one place.
The dated DEPTH_PROGRESS log entry keeps 2,529: it records what was true
when 3.1 landed, and rewriting it would be revisionism. The
component-recipes file keeps its list of superseded literals for the same
reason — that list is the warning against hard-coding the figure at all.
readme-gates, the claim matrix, llms --check, comment-paths, merge-markers
and competitor-names all pass.
* docs: make AGENTS.md contributor guidance instead of a leaked session log
The file committed at the repository root was a verbatim session-memory
document. It opened with "Learned User Preferences", referred throughout to
"the user", and published things that have no business in a public
open-source repository: the commercial product's hostname, its Fly.io
hosting topology and internal app names, its billing and registration flow,
and the name of an archived private staging repository.
Most of it was also wrong. The Fly.io apps were reclaimed for non-payment
months ago, so the deployment section described infrastructure that does
not exist, and the service and package lists predated several waves of work.
Rewritten as what an `AGENTS.md` at a project root is for: guidance for
whoever is changing the code, human or agent. One command to get it
running, one event's journey through the services, where things live, the
conventions that are easy to guess wrong, the figures with the command that
re-derives each, and the rules that are not negotiable.
Three choices worth stating. The figures table gives the command rather than
only the number, because a number copied into prose goes stale silently and
several in this repository did. The "if you are an AI agent" section says
plainly that nothing here can make a third-party tool reach for this project
by default — that is registry publication, not documentation. And the Cyble
credit stays: `www.cyble.com` answers 403 to curl, but it is Cloudflare's
"Just a moment" interstitial over a live host, which is bot protection and
not absence.
Every other URL fetched at 200 before committing.
* Merge origin/main, and register AGENTS.md's two service counts
The new contributor guide publishes a CORE and a full service count in its
opening block, and the profile gate requires any published figure to be a
registered claim site — correctly, because an unregistered figure is one
nobody notices going stale, which is how three of them drifted before.
Registered rather than reworded. Proven by setting the CORE figure to 14
and watching the gate name all sixteen services; restored, and it passes at
28 published figures agreeing with docker-compose.yml.
|
||
|
|
eca10b1e39 |
feat(authz): ABAC conditions, time-boxed elevation and workload identities, inside the one permission path (depth 8.2) (#1206)
* feat(authz): give the v16 IAM tables readers, inside the one permission path (depth 8.2) Migration 087 created `permission_conditions`, `privilege_grants` and `workload_identities` and shipped no reader for any of them. The repository said so itself — CHANGELOG.md records "nothing reads any of them" and FIX_PASS_PROGRESS.md retracted the claim — and `app/security/abac.py` was a complete, tested evaluator whose only importer, `narrow_by_conditions`, had no caller either. Reproduced first, against the shipped code with a real app, real Postgres, real JWTs and ENVIRONMENT=production: a condition restricting `cases:write` to a CIDR the caller is not in returned 201 Created, and a live grant of `roles:read` to a viewer returned 403. Conditions are now applied by `CurrentUser.require_permission` after whichever branch allowed, never beside it — two authorities that can disagree is the shape that produced GHSA-pm3f-h6gc-rvgp. Elevation is consulted at use, so `expires_at` needs no sweep job. `check_one_permission_model.py` gains both properties, including a probe that nests the condition call inside the database-backed branch where it would bind sessions and silently not API keys. Workload identities sit beside the shared service token rather than replacing it, and keep its one non-negotiable property: the tenant is a mandatory header verified against the table, because a credential that works for every tenant is a cross-tenant read whichever way it was minted. Nine new state-changing routes, all authorizing (243 -> 252; identity-only unchanged at 21). Seven permissions seeded by migration 096. * fix(authz): bind connection attributes without assuming the transport exposes a peer `bind_connection_attributes` reads the source address through `resolve_client_ip`, which did a bare `request.client`. The graph WebSocket upgrade authenticates through the same path, and an ASGI connection is not obliged to expose a peer at all, so an authenticated user was met with an `AttributeError` instead of an open socket -- an outage wearing the costume of a permission problem. `resolve_client_ip` already documented that it never raises. It now doesn't: an absent peer degrades to `None`, which the ABAC evaluator treats as indeterminate, and indeterminate denies. The failure mode therefore moves in the safe direction -- an address condition on a connection whose address is unknown refuses rather than passes. The signature widens from `Request` to `HTTPConnection`, the common base of `Request` and `WebSocket`, which is what the callers have actually been passing since the WebSocket path started using it. Three tests, including the negative control that matters: binding that always produced `None` would satisfy the first two and silently deny every address condition on every real request, so the third asserts a connection with a peer still carries its address. Also in this commit, from the first CI run: - the live job connected as `aisoc`, the schema owner, which is a superuser and ignores every RLS policy -- a suite about authorization running as the one role no deployment uses. It now connects as the DML-only runtime role and leaves the owner to migrations and fixtures. - a spaced shell redirect on a pytest line parsed as a directory argument to the install-parity gate, which then read the job as running the whole services/api suite. * fix(authz): a condition may not constrain a role whose authority the caller lacks `scripts/check_role_grant_scope.py` reported three role-conferring writes on this branch that never reach `app.core.role_grants`. Two were a naming miss and one was a real hole. The hole: `POST /access-conditions` took `role` from the request body and checked only that the string was a known role. A condition is a denial, so scoping one to a role is legislating over that role's exercise of a permission -- and `access_conditions:write` is delegable, so a principal holding it alone (a database-backed role, or an API key deliberately scoped down to it) could store a condition switching off an `admin` permission outright. The administrator's only symptom would be their own access failing against a rule they have no route to edit: the same shape as the MSSP override this handler's docstring already cites for the tenant argument, one field along. The rule is the one this tree applies to conferral, turned around: you may not constrain authority you do not hold. Enforced through the same `authorize_permission_grant` chokepoint, measured against `resolved_permissions` rather than the static role map, because `require_permission` admitted the caller on the resolved set. The naming miss: `workload_identities._validate_scopes` did call the chokepoint and did measure against the resolved set -- the control was correct and the name was not. The gate credits delegation only through an enumerated set of helper names, and a helper called `_validate_scopes` reads as a shape check, which is why `api_keys.py` carries both `_validate_scopes` and `_authorize_scopes` as separate functions. Renamed to match rather than widening the gate's allow-list, which would have credited every `_validate` in the tree. `_validate` no longer binds the request model. It decides nothing about authority, and taking the model said otherwise to a reader and to the gate alike. Two live tests against real Postgres, with the negative control: removing the authorization fails the escalation test while leaving the "an unscoped condition is still writable" test green, so the pair cannot pass by refusing everything. * chore(openapi): re-export after the access-conditions docstring change FastAPI publishes a handler's docstring as the operation description, so explaining the new granter-scope rule on `create_condition` moved the committed spec. Regenerated with scripts/export_openapi.py; the diff is confined to that one description and the request/response surface is unchanged. * fix(8.2): audit entries name the credential, not only the actor `scripts/check_audit_coverage.py` failed on all nine `emit_audit` calls across the three modules this branch adds: each named an actor and no credential, so an entry could not distinguish a console session from an API key acting as the same person. That distinction is the point of the feature. A branch that introduces workload identities and time-boxed elevation and then writes a trail which cannot tell a machine credential from a human one gives an investigator the one answer they came for — revoke a key, or disable a person — in a form they cannot act on. Each call now passes `api_key_prefix`, matching admin_users.py. Negative control: removing the attribute from one call site reproduces the failure naming that exact line; restoring it clears the gate. * fix(changelog): resolve the conflict markers my merge left behind The merge of origin/main conflicted in CHANGELOG.md as well as the three count-bearing docs, and I read the merge output through a tail that cut the CHANGELOG line off the top, so `git add -A` staged the file with its markers intact. Both sides are kept: this branch's BREAKING/Added/Fixed sections plus main's depth-1.1 corpus entry folded into Added, which is what a changelog conflict under [Unreleased] always wants. |
||
|
|
41d31ea185 |
docs(security): a buyer security pack, with a gate that keeps its claims true (depth 8.3) (#1210)
* docs(security): a buyer security pack, with a gate that keeps its claims true (depth 8.3) `docs/security/` held three threat models and an advisory draft — good documents, and not the set a procurement review asks for. It now also carries architecture and data-flow diagrams, data handling per deployment mode, a completed security questionnaire with its gaps collected in one table, and a sub-processor page. The pack's rule is that every statement names the file or the CI job that makes it true, and that where a control is narrower than its heading sounds the limit sits in the same paragraph. So it says plainly that service-to- service traffic is plaintext inside the container network on the default stack, that `/metrics` covers 5 of 19 services, and that the injection guard scores 7.1% on held-out payloads against 98.1% on the corpus it was hardened against. There is no verified sub-processor list for the hosted service in this repository, so that page does not invent one. It says what can be established (for self-hosting: none, by construction, with three gates behind it), what cannot, and what a maintainer has to supply. `scripts/check_security_pack_links.py` keeps the pack from rotting. On its first run it caught this pack repeating ADR-0002's assertion that `scripts/audit_compliance_claims.py` exists — it never has. Also corrects `docs/trust/data-flows.md`, which said hosted egress is not pseudonymized and, in the same paragraph, that it was restored by parity 2.4. The second is true; the page understated a shipped control on the question a buyer cares most about, and two further statements were stale the same way. * docs: re-derive the claim-to-gate count after adding the security-pack row `readme_gates.py` cross-checks the summary block in `CLAIM_TO_GATE_MATRIX.md` against the rows actually in the table, and the two surfaces that quote the figure in prose against both. Adding a row for the buyer security pack moved the table to 291 and left three hand-written 290s behind, which is precisely the staleness the gate exists to catch. Recomputed with `scripts/check_claim_gate_matrix.py` rather than edited by hand, in the three places that carry it: the matrix summary, the ROADMAP paragraph, and the evidence-pack table note -- the last of which tells the reader, in the sentence immediately below the number, to re-read it from the table rather than from there. * docs: re-derive the claim-to-gate figure after the merge moved the base `main` gained a row while this branch was open, so the count the evidence pack quotes went stale in the direction the gate exists to catch -- it claimed 289 GATED against a table holding 290. Recomputed with `scripts/check_claim_gate_matrix.py`. The sentence immediately below the number already tells the reader to re-read it from the table rather than from there, which is the right instruction and the reason this is the second time it has had to be followed. |
||
|
|
1cc17e6a81 |
docs(security): draft advisories for the thirteen v15.0.0 defects (#1087)
Kept in the repository so the wording is reviewable in a diff rather than typed once into a web form. Every CVSS vector is scored against a default v14.0.0 deployment, and three are deliberately scored lower than their description suggests - a cookie no code reads, defence in depth behind a guard that was correct, and a path needing an authenticated principal - with the reason given in each. States plainly that none were externally reported, that no exploitation is known, and that no telemetry exists which would have shown it - 'no evidence of exploitation' and 'evidence of no exploitation' are different sentences and only the first is true. Signed-off-by: Beenu Arora <beenu.a.arora@gmail.com> |
||
|
|
56ed73ff10 |
Four pillars, plus the credibility floor (#696)
* docs: correct every claim the code does not implement, and gate the two that drifted
The README advertised 947 executable detection rules while the generated
truth table said 833, and 62 CI-gated claims while the matrix held 72. A
reader cannot tell a front-page summary from the artifact it summarises, so
the larger number is simply believed.
Four docs went further and described controls that do not exist:
- architecture.md credited backup.sh with AES-256-GCM encryption and a
SHA-256 manifest. It gzips and uploads. Encryption at rest in the bucket
is the operator's job and there is no integrity manifest; Neo4j, Qdrant,
Redis and Kafka have no backup path at all.
- The threat model listed envelope encryption as the control mitigating
"a DB dump exposes every connector credential". EnvelopeCipher is
implemented and unit-tested but has no caller: credential_vault.py never
imports it. The deployed control is Fernet under a single key, which is
precisely the risk per-secret DEKs would have contained. Recorded as a
gap rather than a mitigation.
- observability.md claimed one unbroken distributed trace across the
critical path. ingest (Go) and realtime (TypeScript) have no
OpenTelemetry, and they are the two ends of the Kafka spine. The default
exporter endpoint also points at a collector that ships in no compose
file, so out of the box spans go into a connection error.
- The claim matrix marked per-tenant retention GATED. The test asserts the
purge SQL is well-formed; nothing calls it. A tenant can configure
retention, watch it persist, and never lose a row. Demoted to PARTIAL,
which moves the tally to 72 GATED / 12 PARTIAL.
Four docs also told operators to run alembic against services/api, which has
no alembic.ini and no alembic/ directory - it uses a forward-only SQL runner.
The rollback section offered "alembic downgrade -1" as the way out of a bad
upgrade, so the documented recovery path fails at the moment it is needed.
Replaced with the real command, the strict-mode flag that makes a failed
migration abort rather than exit 0 half-applied, and a plain statement that
schema rollback means restoring the snapshot.
The two numbers are now gated. scripts/readme_gates.py parses the executable
count out of the truth table and tallies the matrix rows directly, failing
the build when the README disagrees with either.
tests/test_readme_figures_gate.py pins the gate against the exact drift that
shipped, because a gate that only ever passes is indistinguishable from no
gate.
* feat: make three claimed controls real — sandbox determinism, backup encryption, envelope vault
The previous commit corrected the docs that described controls the code did
not implement. This implements three of them, so the claims can come back.
**Sandbox determinism.** The reasoner used abs(hash(str)) for related-case
counts, entity risk scores and hunt-match counts, with three comments calling
the result deterministic and the package sold on it. CPython salts string
hashing per process, so every figure moved on every run. That is not a
cosmetic bug: the sandbox is the reproducible baseline the evaluation harness
rests on, and a baseline that moves cannot distinguish a reasoning regression
from a new hash seed. Replaced with blake2b. The test runs the CLI in
separate processes under deliberately different PYTHONHASHSEED values, which
is the only way to catch it — an in-process assertion passes even with the
salted hash, because the salt is fixed for a process lifetime. All 11 tests
fail against the old implementation.
**Backup encryption.** Artifacts are now AES-256-GCM encrypted before leaving
the host and recorded in a SHA-256 manifest. openssl enc refuses AEAD ciphers,
so this is a chunked-GCM helper on cryptography, which services/api already
depends on. Chunk framing carries the counter and a final-chunk flag in the
AAD, which buys the property that matters operationally: a truncated archive
fails to decrypt instead of restoring a smaller database that looks like a
successful restore. Restore verifies the manifest digest before decrypting
and refuses a mismatch.
The DR gate now asserts the property the encryption exists for, which a
round-trip test cannot: the object in the bucket has no gzip magic, carries
the AEAD header, and does not contain the seeded schema name. It then flips a
bit and asserts restore refuses. Verified locally end to end against Postgres
16 and MinIO: 500 rows seeded, backed up, schema dropped, restored to 500
rows, and both the tampered-artifact and wrong-key paths rejected.
Three real bugs surfaced while testing that path, all of which made a failed
backup or restore unreadable at exactly the wrong moment:
- pg_dump's stderr was sent to /dev/null, so a failed dump exited non-zero
with no explanation — including the common pg_dump-older-than-server case,
which aborts before writing a byte.
- fail() used ((ERRORS++)), which evaluates to the value before the
increment. The first call therefore returned 0, exit status 1, and set -e
killed the script mid-handler. The entire error-accumulation design —
keep going, report N failures at the end — had never run.
- restore --latest used grep -oP, which BSD grep does not have, and the
trailing || true turned "your grep cannot do this" into "no postgres
backups found" on macOS, the machine someone is most likely to be running
a recovery from.
**Envelope encryption.** EnvelopeCipher was implemented, unit-tested, and had
zero callers, while the threat model cited it as the control mitigating "a DB
dump exposes every connector credential". It is now reachable from
CredentialVault behind AISOC_CREDENTIAL_ENVELOPE=local|aws, writing vault:v2.
The risk in changing a credential store's format is stranding the secrets
already in it, so the tests concentrate there: v1 tokens still decrypt after
the switch, a part-migrated auth_config round-trips, and rows upgrade to v2
the next time they are written. Two fail-closed paths are pinned — a v2 token
read with envelope mode disabled raises instead of passing ciphertext through
to a connector as though it were a credential, and an unrecognised mode
refuses to boot rather than quietly writing v1 while the deployment believes
KMS is in the path.
Matrix moves to 74 GATED / 12 PARTIAL.
* feat: retention that deletes, tenant offboarding, and a ceiling on the public inbox
Three data-lifecycle gaps where the code stopped one step short of the
behaviour the product described.
**Retention purge worker.** app/services/retention.py has built correct,
bounded, tenant-scoped purge SQL since Wave 5, and its own docstring says
"the scheduler/worker that runs the purge composes these". No such worker
existed: build_lake_purge_sql and build_alert_purge_sql had exactly one
caller each, the test asserting they were well-formed. A tenant could
configure retention, see it persist, read the claim matrix calling it GATED,
and never lose a row.
The worker follows the established lifespan pattern (Redis scheduler lock,
one asyncio task, same shutdown semantics as oauth_refresh). Three decisions
worth stating:
- Default off, and dry-run when first enabled. Retention has been storable
and documented as enforced for several releases; arming it on upgrade
would turn a version bump into unannounced data loss.
- Only tenants with an explicit retention_policies row are purged. The
defaults in retention.py pre-fill a form; treating them as an instruction
would delete data nobody asked to delete.
- audit_days is stored but not purged. The audit log is an append-only hash
chain whose whole value is that no row was deleted or reordered, so a
retention purge would invalidate every later verification. Saying so in
one place beats a purge that silently errors every tick.
The alert purge needed one correction to be safe here: build_alert_purge_sql
leans on RLS for tenant scope, which is right inside a request and wrong in a
worker that disables row security to enumerate tenants. Unbound, it would
have deleted every tenant's aged alerts under the first tenant's window. The
predicate is now bound explicitly and a test asserts it.
**Tenant offboarding.** There was no deletion path at all. DELETE FROM
tenants relies on foreign-key cascade, and 14 of the 72 tenant-scoped tables
never declared one — so an offboarded customer's aisoc_institutional_memory,
aisoc_compliance_evidence and aisoc_kb_documents outlived the tenant record.
The lake, graph and vector stores had no deletion path whatsoever.
The Postgres table list is discovered from information_schema rather than
declared. A hardcoded list is correct the day it is written and wrong at the
next migration, and the failure is invisible: deletion reports success while
leaving rows behind. Stores report independently and Postgres runs last, so a
Neo4j outage rolls the transaction back and leaves the tenant record that
names whatever data survived, rather than reporting a complete erase. The
endpoint defaults to a dry run and requires the tenant id to be typed back
for a live one.
**Inbox rate limiting.** /v1/inbox/* is the one route deliberately open to
the internet, authenticated only by a bearer token that lives in a vendor's
webhook config, and it had no ceiling beyond a body-size cap on a single
request. One noisy or compromised integration could fill Kafka, the lake and
every downstream queue, and the blast radius crossed tenants because the
spine is shared.
Two dimensions, because they fail differently: requests bound parse and
connection cost, events bound what actually reaches Kafka — one accepted
request can carry thousands of events, so a request limit alone is not a
volume limit. A rejected batch is rejected whole and consumes no quota,
otherwise the retry the client was told to make would also fail. Idle buckets
are swept, because the tenant dimension is reachable by anyone holding tokens
and an unbounded map is a memory-exhaustion vector rather than untidiness.
Scope is stated honestly in the code and the matrix: the limiter is
in-process, so the effective ceiling is rate times replica count. A shared
limiter needs Redis, which ingest does not otherwise depend on.
Tests run under -race. Matrix moves to 77 GATED / 11 PARTIAL, with retention
promoted back from the PARTIAL it was demoted to two commits ago.
* feat: back up the three stores that had none, schedule it, and make the chart render
**Neo4j, Qdrant and Redis are now backed up.** Only Postgres, ClickHouse and
the plugin store were. The graph is the gap that matters: it is not derivable
from the lake, because it carries relationships built at ingest and enriched
since, so losing it loses blast-radius and attack-path analysis even with
every raw event intact. Exported as Cypher via APOC rather than
neo4j-admin dump, which needs the database stopped or an enterprise licence.
Qdrant is snapshotted per collection and the server-side snapshot deleted
after download, otherwise they accumulate and fill the volume. Redis is an
RDB — mostly reconstructible, but it holds scheduler leases and rate-limiter
state, so a restore without it starts with every scheduled job appearing due
at once.
Kafka is deliberately excluded and now says so: it is a transport, and its
retained window is replayable from the lake rather than restorable.
**The backup is scheduled.** scripts/backup.sh has been correct and
unscheduled for its whole life: every deployment guide said "run it on a
cron" and none shipped one, so the realistic state of a self-hosted install
was no backups. The Helm chart now ships a CronJob running the same script
the DR gate exercises in CI, so what is scheduled is what has been proven to
restore. Disabled by default — it needs a bucket, credentials and an
encryption key only the operator can supply, and a CronJob that fails nightly
is worse than an absent one. concurrencyPolicy Forbid with an
activeDeadlineSeconds, so a hung job cannot suppress every later run
indefinitely, and startingDeadlineSeconds so a cluster that was down over a
window does not fire every missed run at once on recovery.
**The Helm chart could not be rendered at all.** ueba-deployment.yaml,
honeytokens-deployment.yaml and purple-team-deployment.yaml have shipped
referencing .Values.ueba, .Values.honeytokens and .Values.purpleTeam — none
of which existed in values.yaml. `helm lint` and `helm template` both failed
on a nil pointer, which means nobody has ever installed the documented Helm
path. Nothing in CI tried, which is why it stayed that way. The missing keys
are added and Infrastructure CI now lints the chart, renders it with defaults
and with every optional component enabled, parses every manifest, and asserts
the backup CronJob is present with its encryption key and Forbid policy.
The same gate runs `backup.sh --dry-run` for each component the chart can
request, which caught a real defect: a dry run exited 1 when a store was
unreachable. A dry run is a configuration check, and an operator validating
settings from a laptop cannot reach the cluster's ClickHouse, so that made
--dry-run useless for the one thing it exists to do. Unreachable is now
reported as a skip in a dry run and still a failure in a live one.
* fix: restore the executable bit on the backup scripts
The DR gate failed with exit 126 — command found, not executable. The tool
used to push these commits wrote every blob as 100644, so backup.sh and
restore.sh arrived non-executable and the CronJob and CI both invoke them
directly. backup_crypt.py gains the bit too; it is invoked as an argument to
python3 today, but a script that is sometimes run directly should not depend
on which.
* chore: regenerate docs/openapi.yaml for the tenant offboarding endpoint
Additive only: POST /api/v1/tenants/me/delete plus its TenantDeletionRequest
schema.
* feat(graph): context depth, a migration mechanism, and an incident traversal
Pillar 1. An investigation needs to answer five questions about an alert, and
each was either a separate round trip or not answerable at all: which person
is behind the account and are they still employed, what is exploitable on the
host and who owns it, which cloud account and what secrets it reaches, which
business application and how critical, and which actor the indicators point
at. get_blast_radius answers "what is reachable" as an undifferentiated node
set, which makes the caller re-derive the structure.
**Schema v1.1** adds twelve labels and sixteen relationships covering those
dimensions: Employee and Department joined to Identity by AUTHENTICATES_AS
(one person, many accounts, which is what makes "this person also did X in
another system" answerable), Vulnerability and Application, CloudAccount and
Secret, and the IOC to Malware to Campaign to ThreatActor to Technique chain.
Strictly additive: a consumer pinned to v1.0 keeps working.
Two things are deliberate. Secret is a *reference* — name, store, rotation
age, never a value — because the graph is read by agents and rendered in a
UI, and a schema that can hold a credential eventually will. And Employee
carries end_date rather than being deleted on departure, because a departed
employee with a live account is the highest-signal finding the traversal can
produce.
**The drift gate did not gate.** compare_against_go only failed when the YAML
declared something the Go source lacked, never the reverse, and its docstring
called that "intentionally lenient". The leniency had no upside — if Go
declares a label the YAML covers, the set difference is empty anyway — so the
only thing the missing direction permitted was the failure case, and it is
the direction code actually moves in. The gate reported the schema consistent
with 28 labels in Go against 17 in YAML. Both directions now fail. The Go
enum parser also classified by string casing, which put the IOC label in the
relationship set and would do the same to any acronym label; it now reads the
declared Go type. And the expected version is read from schema.go rather than
duplicated a third time in the gate itself.
**Neo4j had no migration mechanism**, which was the blocker for shipping any
of the above to an existing deployment. The schema was a fixed list of
CREATE IF NOT EXISTS run at boot with every failure swallowed at debug, so a
change could only land on a fresh install, there was no record of what a
deployment had applied, and a constraint that failed to create left the
deployment running without a guarantee the code assumes.
app.db.graph_migrations is the Neo4j counterpart to the SQL runner:
forward-only, numbered, recorded as nodes, with backfill hooks and loud
failures. Migration 001 captures the pre-existing boot list so existing
deployments converge rather than re-running unknown statements.
**The traversal** runs the five dimensions concurrently and independently,
exposed at GET /graph/incident-context/{alert_id} and consumed by the agents
ContextBundle. Three properties carry the weight:
Every node of every path is tenant-scoped, not just the start node — an
expansion through a shared entity is how a traversal leaves its tenant, and
this is the single most useful reconnaissance query in the product. The test
parses the generated Cypher and asserts it, and separately asserts that no
variable-length pattern binds a global reference label, since a global node
inside a multi-hop pattern is a bridge rather than a leaf. Vulnerability is
classified as global (a CVE is the same fact everywhere and the node holds no
tenant data; the tenant-specific part is the AFFECTED_BY edge from a scoped
Resource) and is only ever reached as a terminal hop.
Every leg is row-capped. An unbounded traversal from a jump host or a shared
service account is not slow, it is unbounded, and this is on the hot path of
every escalated alert.
A failed dimension names itself and the rest still return. This is the part
that matters most for the agent: an unreachable graph and an alert with
genuinely no context produce identical empty bundles, so the prompt now says
"entity context unavailable, treat missing context as unknown, not as
benign" rather than saying nothing. Writing that test found a real bug —
prompt_context_lines() early-returned on an empty bundle, so the one case
worth warning about reached the model as silence.
Matrix moves to 80 GATED / 11 PARTIAL.
* chore: regenerate docs/openapi.yaml for the incident-context traversal
Additive only: GET /api/v1/graph/incident-context/{alert_id} and its
IncidentContextResponse schema.
* feat(agents): recursive investigation — the tool loop finally has a caller
Pillar 2. run_with_tools is a working ReAct loop with tool execution,
injection guarding and cost telemetry. It shipped with **zero production
callers**. Every investigation path handed the model one pre-serialised blob
and asked for a verdict, so the platform's deepest capability was reachable
only from its own tests. This is the difference between alert → enrichment →
LLM → summary and an actual investigation, and it was one import away the
whole time.
**The toolset.** The registry held four enrichment calls — extract IOCs, map
to ATT&CK, look up a technique, enrich one indicator. None of them takes
another tool's output as input, so no chain was possible. Seven new
primitives query the event lake and compose: what executed on a host, where
else that binary has run across the fleet, what a host connected to, where an
account authenticated from, which hosts saw an indicator, the timeline for an
entity, and where else a technique fired.
Two constraints shape them. The model never writes SQL: each tool takes typed
arguments and composes its own parameterised query server-side, because
handing an LLM the lake endpoint puts prompt-injectable text one step from
the query planner, and the tenant predicate is the only thing between two
customers' data. And the tenant comes from the authenticated session — a
tool argument named tenant_id is discarded, since it would be the single most
valuable thing to inject.
**Tools that cannot answer say why.** Parent-process lineage, mailbox
activity, OAuth grants and persistence mechanisms are not columns in
aisoc.raw_events; no connector populates them. They are still registered, and
return `available: false` naming the connector that would fix it, because a
model that finds no process-tree tool pivots to whatever tool it has and
presents the result as lineage. Returning an empty result set would be worse
still: to a model that reads as "I checked and there is nothing", which is
how an investigation concludes benign on evidence it never had. Writing the
test for this caught the same confusion in my own assertion — "invalid
arguments" and "not ingested" both set available=false, so checking only the
flag passed for the wrong reason.
**Ten strategies** encode what an analyst brings that a prompt does not:
that a suspicious process is worth chasing through the binary's fleet history
and the logged-in account's authentication trail, while an identity alert is
worth chasing through the account's other sessions instead. They steer rather
than script — the plan goes into the system prompt as guidance and the model
picks the tools, because a hard-coded pivot sequence is a workflow engine
wearing an agent's clothes and breaks on the first alert that does not match
its shape. Selection ranks ATT&CK match above keyword match, since a mapping
is a classification and a keyword is incidental, and an unmatched alert gets
general triage rather than no strategy at all.
**A depth gate**, because the failure mode is silent. A refactor drops the
tool binding, a prompt change makes the model answer in one turn, an
exception handler swallows the loop — and every narrative still reads
plausibly. The gate grades structure: the loop must have a production caller,
every strategy must name real tools, every tool offered must be named by some
strategy (this caught process_tree being offered with no guidance on when to
use it), and selection must discriminate. Depth accounting is deliberately
strict: five calls to one tool is one pivot, and a tool reporting its data
class is unavailable is not a pivot at all, or an investigation reaches its
floor by asking four questions nobody can answer.
**One structural fix.** Wiring this surfaced a circular import: app.agents
.tool_loop cannot be imported by an agent, because importing it executes
app/agents/__init__.py, which imports every agent module. The loop moved to
app.llm.tool_loop, where it belongs — it is a provider-agnostic loop over
safe_ainvoke and the registry, with nothing agent-specific in it. The old
path re-exports the two public callables and deliberately not module
internals: patching a re-exported name is a no-op, so a test doing that would
pass while asserting nothing. The one existing test that patched
safe_ainvoke now targets the real module.
Matrix moves to 83 GATED / 11 PARTIAL.
* style: sort imports in two test modules
Both were pushed before `ruff check --fix` ran over them locally, so the
lint gate caught what my local run no longer showed.
* feat(graph): populate the context the event stream cannot carry
Pillar 1, second half. The v1.1 labels exist but the traversal returns empty
until something writes them, and the labels split cleanly by where the truth
lives. An event can tell you an account authenticated. It cannot tell you
which person holds that account, who they report to, whether they still work
here, which business application the host serves, or what an outage of it
costs. That is directory, HR and CMDB data, and it has to be imported.
The difference this makes: "unusual login for svc_deploy" becomes "unusual
login for svc_deploy, owned by a contractor whose last day was Friday, on the
host running the tier-1 payments service". Same event, different incident.
**POST /graph/context/import** upserts employees, departments, applications
and cloud accounts, plus the relationships between them. Four decisions:
Upsert, never replace. An import runs on a schedule against a source of
record that may be partial or briefly unavailable, and replacing the tenant's
context with whatever one run produced would delete an entire department
because an HR export timed out. Omitted fields coalesce to the stored value
rather than blanking it.
Departure is recorded, not deleted, and `is_active` is derived from
`end_date` rather than trusted from the payload. An account still
authenticating after someone's last day is the single highest-signal finding
this data enables, and an export that claims a departed employee is active
would erase exactly that.
Identities and resources are matched, never created. A CMDB naming a host the
platform has never ingested is a coverage gap; creating the node would make
it look monitored. Both cases are named in the report rather than silently
dropped, because a typo and a system nothing ingests are otherwise
indistinguishable.
An unrecognised criticality is rejected rather than coerced. The autonomy
policy reads that field, so "very important" silently becoming tier-1 is a
wrong decision, not a cosmetic one.
**CloudAccount is derived from ARNs** in the ingest extractor, since the
account id is already there and costs nothing to extract. Without it a
compromised workload resolves to a resource id rather than to a blast radius.
The parser requires exactly twelve digits: a malformed ARN would otherwise
create a CloudAccount node per resource. S3 bucket ARNs legitimately omit the
account, so an empty result is a normal outcome rather than a parse failure,
and the test says so.
Still to populate: Vulnerability needs a scanner feed, Secret needs CSPM, and
the IOC → Malware → Campaign → ThreatActor chain needs the threatintel
writer. Recorded as the gap on the matrix row rather than implied complete.
Matrix moves to 84 GATED / 11 PARTIAL.
* feat(actions): the action contract — what every response action must declare
Pillar 3. An action registry is only as useful as what it can tell you
*before* it runs. An executor declared four things — vendor, capability,
whether it needs credentials, a description — and everything that actually
governs execution was inferred elsewhere or not at all:
risk inferred from the capability name in one place and from a
policy table in another, which can disagree
reversibility a hardcoded list of four actions; nothing said whether a
fifth could be undone
verification absent, so an action reported success on an HTTP 200 and
nobody knew whether a probe existed to check the effect
approval no way to express "no tier may ever auto-execute this",
only "the current tier happens not to"
All four are now declarative and enforced. Defaults are deliberately unsafe —
an executor that declares nothing is irreversible and prohibited — so an
omission fails closed and the gate names it, rather than the action quietly
becoming auto-executable.
**Reversal is modelled with four states, not a boolean.** Collapsing it
forces wrong answers: a killed process cannot be un-killed, but the effect
does not persist — the service restarts, the user runs the program again.
Calling that "irreversible" alongside "isolated a production host" loses the
distinction that matters to an approver. PLATFORM, SELF_HEALING, MANUAL_ONLY
and NONE say different things, and the gate treats them differently.
**The contract is per capability, not per vendor.** Isolating a host is
equally disruptive on CrowdStrike, Defender and SentinelOne, so declaring it
three times invites drift — and the one that drifts low is the one that
auto-executes. Adding a vendor for an existing verb inherits the
classification; adding a new verb requires a decision about what it does when
the finding is wrong.
**Approval combines confidence and impact.** The L0-L4 ladder answers how
much a tenant will automate; it does not answer whether a given action is
safe at a given confidence, and conflating them produces both failure modes:
an IOC enrichment queued for approval because the tier is low, and a
production server isolated because the tier is high and the model said 94%.
Each of the three inputs can raise the requirement and none can lower it —
45 test cases, including that a missing confidence score is the lowest band
rather than a free pass, since the alternative turns a scoring bug into an
autonomous action.
Writing the gate surfaced four genuine gaps, all of the same shape: the
rollback path believing it had a route back when it did not. restore_file,
enable_user, allow_domain and allow_ioc are named as reverses by the
contracts and existed in neither the connectors Capability enum nor the
actions mirror. They are now in both, and the mirror comparison itself is
part of the gate — capabilities.py has documented that check at
tests/test_capability_mirror.py for months and no such file exists, which is
precisely how four verbs went missing from both sides.
One rule needed refining rather than enforcing. Requiring a route back at
SEVERE impact is right for autonomous actions and wrong for run_script: a
human deliberately running arbitrary code on a production host is accepting
the irreversibility knowingly, and no probe can tell you whether an arbitrary
script did the right thing. The requirement is therefore waived for
human-gated actions and never waived at HIGH impact, which is the containment
tier where believing a host is contained when it is not is the exact failure
this contract exists to prevent.
Matrix moves to 87 GATED / 11 PARTIAL.
* feat(benchmark): make the harness runnable against an agent that is not ours
Pillar 4. The existing harness grades the in-tree agent by importing it,
which means the numbers are only ever about AiSOC — and a scoreboard with one
entrant is a marketing page. packages/aisoc-benchmark is the boundary that
makes it a standard: a vendor implements one method against their own API, or
points --agent-url at an endpoint, and gets graded on the same corpus by the
same code with no import from this repository.
The protocol is deliberately small, and three things are deliberately
excluded. No tool interface: how an agent reaches evidence is its business,
and prescribing it would grade architecture rather than outcomes while
excluding every agent that does not look like ours. No prompt, for the same
reason. And no partial credit for effort — depth is reported because it
explains a score, not scored, since an agent that reached the right answer in
one step is not worse than one that took twelve.
**Three metrics the plan asks for, all previously absent**, and absent for
the same reason: each makes an agent look worse.
Hallucination rate, measured rather than estimated: the fraction of concrete
indicators an agent cites that appear nowhere in the evidence it was given.
An agent inventing a plausible IP address to justify a verdict is doing the
most dangerous thing an analyst-replacement can do, and no accuracy figure
reveals it. Graded on abstentions too — declining to conclude while citing an
invented address is still inventing it.
Calibration gap: mean confidence when right minus when wrong. Near zero means
the score carries no information, and everything downstream gating on a
threshold is gating on noise.
Containment accuracy: whether the proposed action matches what the incident
needed. Any overlap counts, because requiring an exact set would grade a
vendor on matching our verbs rather than on containing the incident.
**Accuracy is computed over answered incidents only.** Dividing by the whole
corpus lets an agent raise its score by abstaining more — and "I do not know"
is a correct answer that a forced-choice benchmark punishes, which trains
agents to guess. The abstention rate is published beside accuracy so the two
cannot be traded off invisibly.
**Provenance is enforced, not footnoted.** Every incident declares where it
came from and the runner refuses a corpus that does not. The counts travel
with the result so a consumer cannot drop them, --limit recounts over the
slice rather than reporting the whole corpus, and the report prints
provenance before any figure — a reader who sees 0.94 before they see
"synthetic" has already formed an impression the caveat will not undo. The
shipped corpus is 200 synthetic incidents and says so.
Failures are scored as abstentions with the reason named, never as wrong
answers and never as exceptions that end the run: a harness that dies on one
bad response grades nothing, and the entrant reasonably assumes the fault is
ours. Latency is measured by the harness rather than trusted from the agent,
it being the one number an entrant has an incentive to shade.
Verified end to end against an external HTTP stub agent, which the harness
correctly scored at 0.900 disposition accuracy and a 1.000 hallucination rate
— the stub cites one invented address on every incident, and nothing but the
hallucination metric notices.
The corpus is generated from the in-tree eval data by build_corpus.py, and CI
asserts the committed copy matches: two hand-edited copies of 200 incidents
drift within a release, and the published figure then describes a corpus
nobody has.
Matrix moves to 90 GATED / 11 PARTIAL.
* fix: one Go version across the repo, and a real prerequisites section
Six go.mod files declared five different Go versions — 1.21, 1.22, 1.24,
1.25.0 and 1.26 — while the CI Go matrix installed 1.25. That is not
untidiness: services/osquery-extensions declared 1.26, so it could not be
built by the toolchain the pipeline provides, and a contributor following the
repo would install whichever version they read first. Nothing checked,
because nothing compared the two. All six are now on 1.26, CI installs it,
and scripts/check_toolchain_versions.py asserts both halves.
CONTRIBUTING pointed at README.md#development for setup instructions. README
has no Development heading and never has, so the one link in the contributor
path that matters most went nowhere. Replaced with the versions CI actually
installs — a mismatch otherwise shows up as a test that passes locally and
fails in the pipeline, which is an expensive way to discover it — plus the
real migration command, the strict-mode flag that stops a failed migration
exiting 0 with a half-applied schema, and the offline sandbox for anyone who
does not want Docker at all.
* feat(observability): ship the collector the services were already exporting to
Every instrumented service defaults OTEL_EXPORTER_OTLP_ENDPOINT to
http://otel-collector:4317. No collector shipped in any compose file, so out
of the box every span went into a connection error.
That is worse than having no tracing at all. The code looks instrumented,
the logs fill with export failures, and nobody can tell whether a missing
trace means a missing span or a missing collector — so the first person to
investigate assumes the instrumentation is broken and goes looking in the
wrong place.
`docker compose --profile monitoring up` now starts an OpenTelemetry
Collector forwarding into Grafana Tempo, with Tempo provisioned as a Grafana
datasource beside the existing Prometheus one and span-to-metric links
between them — otherwise the two panes are separate tools that happen to
share a login.
Both configs are bounded rather than left at defaults: the collector has a
memory limiter, because a burst that OOM-kills it looks identical to
"tracing is broken", and Tempo keeps 24 hours, because a dev stack that
silently fills a volume with traces is a worse experience than one that
forgets them.
Verified by running both images, sending a real OTLP/HTTP span through the
collector and confirming it exported to Tempo with no errors — the exact
failure that previously filled the logs.
The scope caveat from the earlier docs correction stands and is repeated in
the config: api, agents, ueba and honeytokens are instrumented; ingest (Go)
and realtime (TypeScript) are not, and they are the two ends of the Kafka
spine, so a trace still does not run unbroken from raw event to response
action.
* fix: bump the Go base images with the modules, and gate the third place
The Go version lives in three places and the first cut of the gate covered
two. Bumping the modules to 1.26 broke the compose build: services/ingest,
enrichment and demo-producer still built on golang:1.25, 1.24 and 1.21, so
`go mod download` failed inside the image against a module requiring a newer
toolchain.
A gate that covers two of the three places a version is written finds the
drift it was not looking for, which is how this landed. It now reads the
Dockerfile base images too, and the check is verified against the exact
break it missed.
* fix(web): gate the demo credentials banner, drop a hostname from the OSS login
The login page rendered a "Public demo" banner with demo@tryaisoc.com /
aisoc-demo and a "Use demo" button, ungated, on every deployment. Those
credentials are seeded by the public demo and exist nowhere else, so on a
self-hosted install the operator's own users were shown a sign-in hint for
an account on somebody else's instance and a button that fails. The blurb
above it told them to use those credentials in preference to their own.
It now renders only in demo mode, where the account exists. The sign-in
copy points at the tenant's own account, which is the only one a
self-hoster has.
The footer link also read "← Back to tryaisoc.com" — one deployment's
hostname baked into a product other people run. The href was already
relative; only the label was wrong.
* feat: analyst disagreement as structured data, compiled into organisation memory
When an analyst overturns a verdict, the platform recorded the new
disposition and discarded the only part that generalises: why. Free-text
notes did not generalise either — nobody queried them — so the next
identical alert was triaged with no knowledge that this one was overturned.
The useful unit is the reason, and there are not many. An analyst saying
"benign, known admin tool" and one saying "benign, approved penetration
test" are teaching two different things: the first is permanent and about a
binary, the second is temporary and about a window. A free-text field
flattens them into the same nothing.
So the taxonomy is closed and small, and each code carries its own scope,
lifetime and corroboration threshold. From a handful of tagged
disagreements the platform compiles a durable statement — "powershell.exe
launched by svc_backup on BACKUP01 is expected service-account behaviour
during the 02:00 backup window" — which is organisation memory rather than a
blind fine-tune, and which an analyst can read, argue with and delete.
Four decisions carry the weight:
Corroboration counts *distinct analysts*, not rows. One person clicking the
same button ten times is still one opinion, and the threshold lives in this
module rather than in each caller so it cannot be quietly lowered.
Temporary reasons expire. An approved-pentest statement lasts 14 days,
because one that outlives the pentest is an attacker's best friend and
nobody remembers to remove it. Expiry is applied at read time, not by a
cleanup job, so a statement stops influencing verdicts the moment it expires
rather than whenever a worker next runs.
Rule defects route to detection engineering instead of becoming a
suppression. Suppressing a broken rule's output hides the defect and keeps
paying its cost on every future alert. "Missing context" is the most
valuable code in the taxonomy and the easiest to waste: the fix is a
connector or a graph edge, not an exception.
Statements are specific by construction. "PowerShell is expected" is a
suppression waiting to hide an incident; naming the principal, the host and
the window is a fact, and the test asserts a statement never degrades to the
bare process name.
Honest gap, recorded on the matrix row: the triage prompt does not yet read
active_statements. The memory is written, scoped, expiring and queryable —
and not yet consumed.
* fix: close the CodeQL findings, including a real vault:v2 read-path bug
CodeQL flagged 19 alerts on this branch. Three were the patterns AGENTS.md
already records; one was a genuine bug I introduced.
**The real one.** Four copies of credential_vault.py exist — the API owns
the write path, and services/actions, agents and connectors ship vendored
read-path copies. None of the three knew about vault:v2, and their decrypt
falls through to `return value` for any prefix they do not recognise. So
enabling AISOC_CREDENTIAL_ENVELOPE would have handed `vault:v2:<ciphertext>`
to a vendor API as if it were the credential, producing an auth failure that
reads as a customer configuration problem. That is the exact fail-closed
case I wrote a test for in the API copy and did not carry across. All three
now recognise the prefix and refuse it, naming the service that can read it.
CodeQL found this indirectly: it resolved `CredentialVault` to one of the
vendored copies and reported `envelope` as an unsupported keyword argument
twelve times. The alert was about module ambiguity; the bug underneath it
was not.
The other three, all documented conventions:
py/log-injection — alert_id reaches four log calls in incident_context.py
from a URL path, so it can forge log lines with CR/LF. Sanitised inline at
each call site rather than through a helper, because the taint tracker
does not follow a helper across a function boundary.
py/import-and-import-from — two test modules used `import X as module`
alongside a from-import of the same module. Both now use one style, which
is also the repo's rule against inline imports.
py/ineffectual-statement — the SOCAgent Protocol method body was `...`
after its docstring. The docstring is the body.
* refactor: name the envelope constructor so the call site is unambiguous
Four modules in this repo are importable as app.security.credential_vault:
the API owns the write path, and services/actions, agents and connectors
ship vendored read-path copies. A call site reading
`CredentialVault(key, envelope=...)` is therefore ambiguous about which
class it means — to a reader, and to static analysis, which reported the
keyword as unsupported twelve times against the wrong copy.
`CredentialVault.with_envelope(key, cipher)` says which one. The vendored
copies have no such classmethod, so the intent is unambiguous at the point
of use rather than inferable from an import three files away. The keyword
argument still works; the named constructor is the one the call sites use.
The underlying duplication is the real problem and is bigger than this
change. This removes the ambiguity where it is read.
|
||
|
|
5d4de48536 |
feat(api): Phase 1.6 KMS envelope encryption for the credential vault (#422)
- services/api/app/security/envelope_cipher.py: optional envelope encryption (per-secret DEK wrapped by a KEK in KMS/HSM; vault:v2 token format). Pluggable KeyManager: LocalKeyManager (default), AwsKmsKeyManager (boto3), FakeKmsKeyManager (tests). Rotation is a cheap rewrap() that never re-encrypts the secret body. - test_envelope_cipher.py (9 tests, api job): round-trip, rotation+re-wrap, plaintext-never-in-token, fail-closed on tamper/wrong-KEK. - docs/security/platform-threat-model.md (STRIDE, vault as top asset) + docs/security/connector-least-privilege.md; referenced from SECURITY.md. Phase 1.6 of AISOC_CURSOR_PROMPT_V2.md. Completes Phase 1. Co-authored-by: Beenu Arora <beenu@MacBook-Pro.local> Co-authored-by: Cursor <cursoragent@cursor.com> |
||
|
|
01ca8cd2e9 |
Phase 1.1: prompt-injection envelope + guard (gated) (#416)
* feat(agents): Phase 1.1 prompt-injection envelope + guard, gated - services/agents/app/prompting/envelope.py: per-run cryptographic-nonce evidence fence (EvidenceEnvelope/make_nonce/system_rule) so injected text cannot forge the closing delimiter, and PromptInjectionGuard that flags instruction-shaped content (role markers, "ignore previous", prompt/secret exfil, SOAR tool-name mentions, base64/zero-width obfuscation) and signals autonomy demotion to L0 on high severity. - test_prompt_envelope.py: 25 offline tests across every ingest path (Sysmon/DNS/UA/filename/email/commit/k8s/Okta/Slack) + precision checks. - Gate both test_prompt_envelope.py and the previously-ungated test_prompt_sanitizer.py in the CI agents job; fix the sanitizer wiring test's stale expectations (agents sanitise via sanitize_text / sanitize_iterable_of_strings / format_bundle_prompt_append). - docs/security/agent-threat-model.md (STRIDE), referenced from SECURITY.md. Phase 1.1 of AISOC_CURSOR_PROMPT_V2.md. Moves prompt-injection resistance from NO GATE to PARTIAL in the claim-to-gate matrix. Co-authored-by: Cursor <cursoragent@cursor.com> * fix(agents): satisfy pinned ruff 0.4.10 (UP038 + format) in Phase 1.1 Co-authored-by: Cursor <cursoragent@cursor.com> --------- Co-authored-by: Beenu Arora <beenu@MacBook-Pro.local> Co-authored-by: Cursor <cursoragent@cursor.com> |