Commit Graph
7 Commits
Author SHA1 Message Date
Beenu Arora 76570487f5 fix(wave6): retract what is not built, and remove routes that cannot run (#1119)
* fix(wave6): retract what is not built, and remove routes that cannot run

Item 6.1 — detection lifecycle. `detection_rule_versions`,
`detection_shadow_matches` and `shadow_until` have zero readers in
`services/`, and the only `rollback` in the detection endpoints is a
database transaction rollback. So a rule set to `dev` still raises alerts and
a future `shadow_until` still pages. The docs page marks four sections schema
only; README and CHANGELOG say which half works. Separation of duties on
`/detection-proposals/{id}/decide` is real and its claim stands.

Item 6.2 — enterprise IAM. `workload_identities`, `privilege_grants` and
`permission_conditions` have zero readers; `narrow_by_conditions` has zero
callers. Narrowed, keeping API-key rotation, which does work.

Item 6.3 — three intro.md overclaims. Qdrant holds the MITRE technique corpus
for lookup, which is a reference index and not agent memory; no route
recommends rules for uncovered techniques; `GET /taxii/collections` calls
`_demo_only()`.

Item 6.4 — the phishing playbook's "Retract phishing email fleet-wide" step
posts to `${EMAIL_GATEWAY_URL}`, set by nothing, under
`on_failure: continue`.

Item 6.5 — removed `detection_loop.py`. It named `aisoc_alerts`,
`aisoc_detection_rules` and `alerts.evidence`, none of which exist, so a
rename could not fix it; its own test built a fake row for the missing table.
Emptying `KNOWN_MISSING_TABLES` then surfaced three more callers: the
business-context preview (which swallowed the error and silently showed
built-in samples), the case timeline, and the identity timeline — whose
`evidence` and `mitre_technique` are really `raw_event` and
`mitre_techniques`, so it had reported no alerts for every identity on every
deployment. All three repointed. Added a guard refusing promotion of a
comment-only rule body and defaulted the auto-tuner off.

* fix(wave6): CI follow-ups, and make the openapi drift message diagnostic

The playbook step schema allows no `description`, so the retraction
explanation moved into the step name and the playbook description. The
marketplace index is regenerated for the edited pack.

`check_python_route_state` is a shrink-only ratchet and removing
`detection_loop.py` discharged its `_SUGGESTIONS` entry, which the gate
correctly reported as a stale exemption.

The openapi drift was environmental, not a missed regeneration: this venv had
pydantic 2.8.2 against the lockfile's 2.13.5, and 2.13 emits
`additionalProperties: true` on bare `dict` responses where 2.8 did not --
252 lines of diff across the spec, nothing to do with the change. The gate's
advice was to run the command that produced the rejected file, which is the
least useful place it could leave somebody, so it now names a generator
version that disagrees with the lockfile, prints the `pip install` that fixes
it, and shows the first few differing paths. Proven by downgrading pydantic and
reading the message.

* docs(wave6): record the detection-loop route removal as BREAKING

Three paths and three schemas leave the published spec, so every generated SDK
client loses those operations and the policy requires it stated under its own
heading. The migration note is that there is none: the routes queried two
tables and a column that no migration creates, so any caller was already
receiving an error.
2026-10-04 09:12:15 -07:00
Beenu AroraandBeenu Arora e78f31768c Move all fourteen ruff declarations to 0.16, and stop the lint gate at services/ (#861)
* Reformat the tree under ruff 0.16, excluding the subtree nobody may edit

Mechanical. `ruff format` with no other change, so the diff can be read as
"the formatter moved" rather than reviewed line by line: 218 files, 862
insertions against 1075 deletions, almost all of it collapsing calls that
0.4.10 wrapped and 0.16 fits inside the 140-column limit.

`plans/` is excluded in `ruff.toml` rather than reformatted. It is the
archived prototype subtree that `.github/workflows/codeql.yml` already
excludes and `scripts/check_mypy_baseline.py` excludes from every coverage
direction, and the project rules forbid editing anything under it -- so
formatting it would be a diff nobody may take. 844 lint findings and ~280
unformatted files live there. They are excluded because they cannot be
fixed, which is a different statement from saying the code is clean.

* Move all fourteen ruff declarations to 0.16, and stop the lint gate at services/

The bump alone reds every open pull request: `ruff format --check` is a hard
gate on the required `Python - Lint & Type-check` job and 0.16 formats
differently from 0.4.10. The reformat is the previous commit; this one moves
the pin, fixes the findings, and answers the scope question.

Fourteen declarations now read `>=0.16.8,<0.17` -- seven manifests, three
workflows, `.devcontainer/Dockerfile`, and the three `poetry.lock` files that
resolve it (now 0.16.9, which is byte-identical to 0.16.8 on both format and
lint across this tree).

The three findings 0.16 reports on `services/` are fixed, not suppressed: two
`C420` comprehensions become `dict.fromkeys` (both values are string literals,
so the shared-value hazard does not apply) and one `UP031` percent-format
becomes an f-string in a test that counts characters. All three rewrites were
asserted equal to the originals before being kept.

Scope. `ruff check services/` left `scripts/` -- every CI gate in this
repository, the code the rest of its claims are verified by -- linted by
nothing. Lint now covers `services/ scripts/ tests/ tools/`, the trees the
root `ruff.toml` governs that nothing else lints, and `ruff format --check .`
covers everything, because formatting has no semantic content and `.` needs
no edit when a tree is added. That surfaced 17 findings outside `services/`,
each fixed at the source: two `B007` loops switched to `.values()`, a `B904`
re-raise in `security_audit.py` now chains `from exc`, two `E402` imports
that genuinely follow a `sys.path` mutation carry a reason next to the
marker, and two over-length lines were wrapped.

`E501` is ignored for the two detection-spec data modules. Both open their
rule table with `# fmt: off`, so the formatter is already opted out of that
layout deliberately, and all 199 long lines are single dict or string
literals -- 72 positive fixtures, 66 negative, 50 `match_when` clauses, 11
descriptions. Two named files, not `scripts/`.

`packages/` and `plugins/` stay outside the lint gate, and the gap is a
number rather than a shrug: 91 findings and 2. Two of the five packages are
linted by their own workflows under their own configs, and bringing the
three published SDKs under this gate means behaviour-touching fixes that
belong in a change reviewed as such.

* Make packages/aisoc-detections clean under the ruff its own workflow now installs

`python-detections.yml` lints `aisoc_detections detections tests` under the
pin this PR moved, so the package has to be clean under 0.16 too. Two
findings, both fixed at the source rather than silenced: `Callable` moves to
`collections.abc`, and a `# noqa: BLE001` that 0.16 correctly reports as
unused becomes the sentence it was standing in for -- a detection module is
third-party content, so any exception at import is the author's and becomes a
DetectionError naming the file.

---------

Co-authored-by: Beenu Arora <beenu@MacBook-Pro-3.local>
2026-09-24 19:36:59 -07:00
Beenu AroraandBeenu Arora f3348223a8 Five gates said OK over nothing; the probe that found them is now a gate (#823)
* Five gates said OK over nothing; the probe that found them is now a gate

Copying scripts/ into an empty git repository and running every wired check
found five reporting OK over a tree containing nothing: the detection
validator behind the rule count on the front page certifying zero rules as
valid, a dashboard check that failed on an empty directory and passed on a
missing one, "OK: 0 published Go module path(s)", every self-link healthy
over zero files, and a health-probe audit printing a table header and
exiting 0. Those five were fixed. The probe was a one-off, so the next gate
written could reintroduce the defect freely.

scripts/check_gate_contract.py is that probe made permanent. It runs all 69
inventoried checks the way a workflow runs each one, inside a git repository
holding only scripts/, and requires each to exit non-zero. The inventory
comes from check_gate_coverage.py rather than a second scanner here, because
two scanners drift the first time either learns something the other has not.
A run that failed for a reason the empty tree did not cause is INCONCLUSIVE
and fails rather than counting as a refusal. Every way CI runs a script is
probed and the worst result decides, because four subcommands under one name
are four gates.

Two properties come with it, both enforced with empty exception lists: a
root resolved through git rather than from __file__, and a declared
--self-test. Sixty of sixty-nine did the former; fifty-four lacked the
latter. scripts/gate_toolkit.py holds the single implementation of both.

Found while building it:

- check_gate_coverage.py decided "inspects the repository" partly by looking
  for Path(__file__) -- the idiom being migrated away from -- so moving six
  gates onto the shared resolver dropped them out of the inventory.
- The first spelling of the root property matched repo_root anywhere in the
  text, and check_gate_coverage.py emits it as a JSON key, so a gate rooted
  at __file__ read as compliant on a key in its own output.
- check_route_tenant_scope.py printed "scanned 0 routes across 0 files" and
  then "OK: every route taking a tenant identifier authenticates" against a
  services/ tree with no routes in it.
- security_audit.py's pnpm, python and go arms each printed "0 findings"
  over a tree with no manifests, and get_repo_root() fell back to cwd.

* Make every gate find gate_toolkit however it is loaded

Five CI jobs failed with ModuleNotFoundError: No module named 'gate_toolkit'.
Sixteen test modules load a gate with importlib.util.spec_from_file_location,
which executes the file without putting its directory on sys.path — so the
scripts were importable as programs and not as modules, and the scripts that
already import a sibling carry the same tweak for the same reason.

Each gate now inserts its own directory before the import. Also corrects the
claim-to-gate tally in the compliance evidence pack, which quotes it in prose
and was the second place the figure lives.

---------

Co-authored-by: Beenu Arora <beenu@MacBook-Pro-3.local>
2026-09-24 08:08:57 -07:00
Beenu AroraandBeenu Arora a145132f7b Thirty routes that let the caller name the tenant they were reading (#813)
* Thirty routes that let the caller name the tenant they were reading

`/fusion/entity-risk/*` took `tenant_id` as a query parameter with no auth
dependency on the route, on both the API gateway and the fusion service. The
console reaches fusion directly through a Next rewrite when `FUSION_URL` is
set, so those routes were reachable from any browser and an anonymous request
naming another tenant's UUID returned that tenant's entity-risk queue, stats
and per-entity detail. Reproduced against the previous commit with two seeded
tenants: 2 of tenant A's entities returned to a caller holding no credential
at all.

The engine's docstring asserted the missing control — "the tenant_id is part
of the key prefix and the API service re-checks tenant on read" — and the
second half was not true on either side. Key prefixing isolates whichever
tenant it is handed, and validating the parameter's value fixes nothing: a
UUID that parses is still a UUID the caller chose.

An AST pass over all 600 routes under `services/` found 30 taking a tenant
identifier, in two flavours. No authentication at all: six entity-risk routes,
five in `services/agents` (`/triage/{run_id}`, `/cases/{id}/triage`,
`/cases/{id}/investigate`, `/investigations`, `/explain`) and six in
`services/osquery-tls`. Authenticated but never intersected with the caller's
scope: `honeytokens`, `purple-team` and `ueba`, where a router-level service
token proved the caller was a trusted service but said nothing about which
tenant it was acting for.

The tenant now comes from the credential. `app/security/tenant_scope.py`,
vendored into six services, resolves either a console session (the first-party
HS256 access token, whose verified `tenant_id` claim is authoritative) or a
trusted service declaring the tenant it acts for on `X-AiSOC-Tenant-ID`. A
`tenant_id` on the request survives only as a filter, intersected with that
scope, so an MSSP operator can narrow to one managed customer while naming an
outside tenant returns 403. A service token declaring no tenant resolves to an
empty scope and is refused: absent is never all. HS256 verification is
stdlib-only, mirroring services/realtime/src/auth.ts, and rejects `alg: none`,
a refresh token presented for access, and expired or wrongly-signed tokens.

Closing these surfaced a worse variant the parameter audit could not see:
eight routes matched on an id with no tenant predicate at all, so any caller
could read, revoke or delete another tenant's honeytoken, overwrite another
tenant's detection outcome, or acknowledge away another tenant's anomaly by
naming its UUID. All eight now filter on the caller's tenant as well.

`services/osquery-tls` enrolled every node under the literal "default", which
resolves to no tenant on any seeded deployment: migration 001 seeds the
canonical tenant with slug `default` and the demo seed renames it to `demo`,
so the literal matched neither the UUID nor the slug. FIM events were written
under a string the console could never ask for. `tenant_resolver.py` resolves
the placeholder to the canonical seed tenant by its stable UUID, falls back to
the sole tenant of a single-tenant install, and refuses enrolment for an
unknown ref rather than filing the node somewhere unreadable.

`false_positive_rate` and `escalation_rate` published 0.0 on an empty
denominator — the same defect as the means that shipped a NULL average as a
confident 0.0, and the flattering direction: a tenant that had resolved
nothing and gated nothing scored 0% false positives and 0% escalations. Both
now travel with the count of rows they were computed over and the console
renders "not measured".

Gated by `scripts/check_route_tenant_scope.py`, which fails in both
directions and whose `--self-test` injects a violation of each kind plus a
stale exemption. `tests/isolation/test_route_tenant_scope.py` seeds two
tenants through the real EntityRiskEngine, asserts both genuinely hold rows,
then asserts an anonymous caller, an undeclared service token and a console
session for B are each refused A's data.

* ci(isolation): install the fusion router's module-level import chain

The two-tenant replay drives the real services/fusion router, which is the
point — a stubbed router proves nothing about the shipped one — so its
module-level imports have to resolve. aiokafka arrives via app.workers.consumer,
asyncpg via the alert and DLQ sinks, and cryptography via app.memory.pack.

The heavier ML and lake deps are deliberately absent: lightgbm, scikit-learn,
numpy and clickhouse-driver are all imported inside functions, so adding them
would cost minutes for nothing. Verified by installing exactly this list into a
clean venv and running the suite, rather than by guessing from a static walk —
the static walk is what missed cryptography.

* fix: close the CodeQL findings this change introduced

Nine py/log-injection and four py/clear-text-logging-sensitive-data, and the
log-injection ones are real rather than heuristic noise: `principal.subject`
carries the JWT `sub` claim and `ref` arrives on the X-AiSOC-Tenant header,
so both are attacker-influenced strings reaching a logger that records a
refused cross-tenant read. A forged newline there could fabricate a second log
line next to a genuine security event.

Sanitised inline at each call site rather than through a shared helper. The
tracker does not follow a helper across the call boundary, and this repository
has already learned that once; the inline chain also makes the property
visible to the next reader.

The clear-text-logging four were the documented false positive: the constant
was named IN_BAND_SECRET_ROUTES and holds route keys and function names, never
a credential value, but a `secret`-shaped identifier flowing into `print`
trips the heuristic — the same way a counter named `secret*` did in an earlier
pass. Renamed to IN_BAND_CREDENTIAL_ROUTES, with the reason recorded on the
docstring so nobody renames it back.

* test: give each vendored tenant_scope copy its own tests, and authenticate the route tests

CI surfaced three things a local run had not.

The honeytokens coverage gate dropped from 10% to 7.3%: the vendored resolver
added 136 statements of security-critical code that no test in that service
touched. The fix is the test, not the threshold — test_tenant_scope.py now
travels with the module through the same sync script, so each of the six
copies is exercised where it lives rather than trusting that the one covered
by tests/isolation stands in for the rest. honeytokens goes 7% -> 36%.

The osquery-tls harness created only that service's own tables, so it modelled
a deployment that does not exist: the service shares the platform database and
the resolver reads the tenants table from it. The harness now seeds the
canonical tenant with slug 'demo' rather than 'default', which is what a
seeded deployment actually looks like and forces the lookup to go by stable
UUID. The resolver also treats an unreachable tenants table as a named
refusal rather than a 500, because an operator who pointed this service at a
standalone database needs to be told that.

The agents triage and explain tests called their routes with no credential and
a free-text tenant. test_get_with_mismatched_tenant_returns_404 was the
clearest case: it passed tenant_id for both sides of the comparison, so all it
proved was that the route compared a value against a copy of itself — which a
caller enumerating run IDs can always satisfy. Tenant B now arrives holding
tenant B's own credential.

One behaviour change fell out of that. Several request models default
tenant_id to the literal "default", which names no tenant on any deployment.
resolve_scoped_tenant treats that and the other placeholders as absent rather
than as a request for a tenant of that name, so a caller who leaves the field
alone reads their own data instead of getting a 403.

* ci(isolation): align the new job's pins with every other install path

check_dependency_pins caught two ranges I had widened without noticing there
was a canonical one: cryptography >=42 against the repo's >=46, and fastapi
>=0.109 against >=0.117. Both reasons in the gate's output are load-bearing —
the cryptography floor is the Fernet token format shared between the service
that writes vault tokens and the ones that read them, and below fastapi 0.117
a `-> None` handler under PEP 563 trips the '204 must not have a response
body' assert, so the service cannot be imported at all.

pydantic-settings moved to the declared >=2.1 for the same reason. The suite
was re-run against exactly this set in a clean 3.12 venv, not just the gate.

* ci(isolation): allow on-demand runs, matching isolation-live.yml

The job is path-filtered, so a maintainer investigating a tenant-isolation
question cannot run it without touching a file that happens to match. Its
live-container sibling already carries workflow_dispatch.

* gate: recognise the playbook-step dispatch resolver

PR #814 landed a route taking a tenant on its request body while I was
working, and the gate flagged it — which is the drift-in-the-direction-
things-change case it exists for. The route is already correct: it uses the
same named local resolver as alert_writeback, where a session's tenant comes
from the session and a service caller must name one explicitly. What was
missing was the gate's knowledge of that helper, so this registers it with
its reason rather than touching another workstream's file.

---------

Co-authored-by: Beenu Arora <beenu@MacBook-Pro-3.local>
2026-09-24 04:22:30 -07:00
Beenu Arora d7b1c6eea8 chore: remove decorative gimmicks across docs, UI, scripts, and CI
Strip emoji, hyperbolic marketing language, rant tone, gradient/glow
decoration, and unused animations. Replace decorative symbols with
plain text while keeping functional UI affordances (close buttons,
star ratings, status indicators, keyboard shortcuts).

- docs: README, CHANGELOG, MIGRATION, PROGRESS, ROADMAP, intro,
  benchmark, quickstart, architecture, playbooks concepts
- web UI: Hero, landing pages, cases, alerts, copilot, detections,
  hunt, marketplace, playbooks, settings, responder shell, compliance
- styles: drop unused .bg-grid/.glow-blue/.glow-red/.glass and
  unused tailwind extensions (gradient-radial, grid patterns,
  glow shadows, fade-in/slide-up/shimmer/orbit animations)
- scripts: factual logging in aisoc-demo, aisoc-doctor, backup,
  restore, lab, eval_mitre_accuracy, validate_detections,
  export_openapi, inject_scenario
- ci: drop emoji from workflow step summaries
- packages: TimelineEvent loses decorative icons; CLI logs cleaned
2026-05-04 12:04:34 -07:00
Beenu Arora ebe2d5ea03 docs: rebrand to AiSOC community + fix repo URLs and metadata
Sweep the repository for stale Cyble Inc. authorship/branding,
outdated cyble-inc/AiSOC GitHub URLs, demo email/workspace strings,
and missing environment-variable docs. External integration
references (e.g. Cyble Vision threat-intel client) are intentionally
preserved as legitimate vendor product names.

Highlights:
- LICENSE, package.json, services/*/pyproject.toml, services/mcp,
  packages/sdk-{py,ts}/README, packages/types, packages/ui:
  copyright + author lines moved to AiSOC contributors / community.
- Service file headers (Python, Go, TypeScript) updated.
- README.md, ROADMAP.md, SECURITY.md, AGENTS.md, CONTRIBUTING.md,
  CHANGELOG.md: trim Cyble-only voice; reflect current OSS state.
- apps/docs/* (Docusaurus): config + docs pages refreshed,
  cyble-inc/AiSOC -> beenuar/AiSOC across links, deployment env-vars
  doc filled in for the realtime service.
- apps/web: layout/metadata, settings panel ("About AiSOC"), demo
  banner, copilot, alerts, cases workspace, marketplace view, footer,
  hero, sidebar, logo asset — Cyble-marketing strings replaced with
  open-source community framing.
- Plugins (plugins/*/plugin.yaml): homepage URLs corrected;
  marketplace/index.json regenerated from yamls.
- infra/ (docker-compose, helm chart, terraform): images and
  metadata aligned.
- schemas/playbook.schema.json: $id updated to new repo URL.
- scripts/export_openapi.py: header reauthored.
- services/api: main.py service description, demo_mode middleware,
  v1 endpoints (api_keys, plugins, graph, services, config) and
  default org/email values point at the OSS project.
- services/threatintel: client headers (CISA KEV, MISP, OTX, TAXII,
  STIX parsers, storage backends) re-attributed to community.
2026-05-04 10:18:32 -07:00
Beenu Arora 8bfcc953d5 feat: ship v4.1 + v5.0 + v5.1 — UEBA, Honeytokens, Purple Team & enterprise governance
## v5.1.0 — Purple Team Adversary Emulation
- New `services/purple-team` service: Atomic Red Team loader, Caldera integration,
  ATT&CK coverage heatmap, tabletop session tracker
- Kubernetes Helm template with HPA, PDB, Atomic Red Team volume mount
- Purple Team UI page (`/purple-team`) with Coverage, Executions, Tabletop tabs
- Alembic migrations for purple_team_atomic_tests, executions, tabletop_sessions

## v5.0.0 — Honeytoken Deception Platform
- New `services/honeytokens` service: URL/file/AWS credential/email tokens
- HMAC-SHA256 signed tokens, public tracking endpoint → alert pipeline
- Webhook delivery with HMAC signing for external integrations
- Honeytokens UI page (`/honeytokens`) with token management and event timeline

## v4.1.0 — Enterprise Security & Governance
- UEBA behavioral analytics: Welford's online baseline + z-score anomaly detection
  consuming Kafka `security.events`, publishing to `security.anomalies`
- Granular RBAC with `require_permission` FastAPI dependency
- PostgreSQL Row-Level Security (multi-tenant isolation via `rls.py`)
- SAML 2.0 + OIDC SSO with group→role mapping
- API keys CRUD with scoped permissions
- Immutable audit log (append-only, DB-level trigger)
- Compliance controls + evidence tracking (SOC 2, ISO 27001, NIST CSF)
- SLA tracking: `tenant_sla_config` + `alert_sla_events`
- OpenTelemetry traces/metrics/logs (OTLP export to Tempo/Jaeger)
- Backup/restore scripts with AES-256-GCM encryption
- Multi-region deployment runbook + DR runbooks via `generate_runbook.py`
- GraphQL endpoint with Strawberry (`/graphql`)

## Infrastructure & DX
- Helm: UEBA, Honeytokens, Purple Team deployments with HPA + PDB
- GitHub Actions: check-openapi, deploy-docs, sync-marketplace, validate-detections
- Community marketplace index (`marketplace/index.json`)
- Plugin SDKs: Python (`packages/plugin-sdk-py`), Go (`packages/plugin-sdk-go`)
- Client SDKs: Python (`packages/sdk-py`), TypeScript (`packages/sdk-ts`), Go (`packages/sdk-go`)

## Documentation
- README.md: complete rewrite for v5.1.0 with full architecture, API, quick-start
- CHANGELOG.md: detailed entries for 5.1.0, 5.0.0, 4.1.0
- docs/openapi.yaml: v5.1.0 spec with x-tagGroups for all endpoint families
- Docusaurus site: intro, quickstart, architecture, env-vars, REST/GraphQL/WebSocket API,
  detection rules, plugin overview all updated for v5.1.0
2026-05-03 10:44:02 -07:00