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
feat(v7.1.0): Cloud Security Coverage Wave (#54)
Beenu Arora63ebcbafae14
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 62d3838c0..2120f5a95 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -5,6 +5,175 @@ All notable changes to AiSOC will be documented in this file.The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).+## [7.1.0] — 2026-05-10++### Added — Cloud Security Coverage Wave++Six new connectors, three documentation backfills, and one new ingest template.+Closes the biggest cloud-security gap in the connector catalogue: every Tier-1+cloud workload protection platform (Wiz, Prisma Cloud, Orca, Lacework, AWS+Security Hub) now has a first-class integration, AWS gets three native data+sources (GuardDuty, CloudTrail, VPC Flow Logs), and Kubernetes audit logs land+through a dual-mode connector that works on both managed and air-gapped+clusters.++#### Track A — Documentation backfill++- **`apps/docs/docs/connectors/wiz.md`**: Documented the Wiz GraphQL connector+ end-to-end — service-account creation, scope (`read:issues`,+ `read:vulnerabilities`), token rotation, normalised severity mapping, and a+ worked example of a Wiz `Issue` collapsing to `category=cloud_alert` in the+ inbox.+- **`apps/docs/docs/connectors/aws-security-hub.md`**: Documented IAM role vs.+ static-key auth, the `securityhub:GetFindings` permission model, and the+ `BLOCK_IP`/`ALLOW_IP` capabilities backed by+ `services/actions/app/clients/aws_security_groups.py` (i.e. how a SOC analyst+ can quarantine an attacker IP from the Security Hub finding without leaving+ the case workspace).+- **`apps/docs/docs/connectors/lacework.md`**: Documented the Lacework API+ token flow, `api_url` regional variants, and the alert→event severity map.+- **`apps/docs/sidebars.ts`**: Registered all three new docs pages under the+ `Connectors` category, plus the four new connector pages from Tracks B–D+ (`prisma-cloud`, `orca`, `aws-guardduty`, `aws-cloudtrail`, `aws-vpc-flow`,+ `kubernetes-audit`).++#### Track B — New CNAPP connectors++- **`services/connectors/app/connectors/prisma_cloud.py`** —+ `PrismaCloudConnector` with full Prisma Cloud (CSPM/CWPP) coverage. JWT auth+ via `POST /login`, paginated `GET /alert/v1/alert` with `time.from`/`time.to`+ windowing, severity collapse (`critical/high → high`, `medium → medium`,+ `low/informational → low`), and a `compute_url` override for self-hosted+ Compute Edition. Capability: `PULL_ALERTS`. Manifest: `plugins/prisma-cloud/plugin.yaml`,+ docs at `apps/docs/docs/connectors/prisma-cloud.md`, tests in+ `services/connectors/tests/test_prisma_cloud.py`.+- **`services/connectors/app/connectors/orca.py`** — `OrcaConnector` hitting+ `https://api.orcasecurity.io/api/alerts` with an `api_token` field, severity+ collapse (`critical/high/hazardous → high`, `medium → medium`,+ `informational/low → low`). Manifest, docs, and tests follow the same+ pattern. Capability: `PULL_ALERTS`.++#### Track C — Native AWS connectors++- **`services/connectors/app/connectors/aws_guardduty.py`** —+ `AWSGuardDutyConnector` mirroring `AWSSecurityHubConnector`'s shape:+ boto3-based, supports IAM-role or static-key auth, calls+ `guardduty.list_findings` + `get_findings` per detector. Normalises+ GuardDuty's continuous numeric severity scale (`0.1`–`10.0`) into AiSOC's+ four-tier `info|low|medium|high` ladder (`>= 7.0 → high`, `>= 4.0 → medium`,+ `>= 1.0 → low`, else `info`). Capability: `PULL_ALERTS`.+- **`services/connectors/app/connectors/aws_cloudtrail.py`** —+ `AWSCloudTrailConnector` using `cloudtrail.lookup_events`. Ships with a+ curated default allow-list of 21 high-signal event names covering identity+ abuse (`ConsoleLogin`, `AssumeRoleWithSAML`, `GetSessionToken`,+ `GetFederationToken`, `CreateAccessKey`, `CreateLoginProfile`,+ `CreateUser`), persistence (`AttachUserPolicy`, `PutUserPolicy`,+ `CreateRole`, `AttachRolePolicy`), data-plane abuse (`PutBucketPolicy`,+ `PutBucketAcl`, `DeleteBucketPolicy`, `PutObjectAcl`), network exposure+ (`AuthorizeSecurityGroupIngress`, `RevokeSecurityGroupIngress`,+ `ModifyDBInstance`), and trail tampering (`DeleteTrail`, `StopLogging`,+ `UpdateTrail`). Allow-list is overridable via the `event_names` config+ field. Pagination handled via `NextToken` with a hard cap to keep poll+ latency bounded. Capability: `PULL_LOGS`.+- **`services/connectors/app/connectors/aws_vpc_flow.py`** —+ `AWSVPCFlowLogsConnector` using `cloudwatch_logs.filter_log_events`. Parses+ both v2 (default 14-field) and v5 (header-defined) flow-log formats. Default+ `filter_pattern` is `?REJECT` to surface dropped traffic only — keeps volume+ manageable while flagging external-facing security groups that are getting+ scanned. Public-IP heuristic (`_is_public_ip`) is RFC-5735-aware, treating+ RFC1918/loopback/link-local/multicast/CGNAT/TEST-NET as private. Severity+ heuristic: public-IP REJECTs → `medium`, internal REJECTs → `low`,+ ACCEPT-only flows → `info`. Capability: `PULL_LOGS`.++#### Track D — Kubernetes audit logs (dual-mode)++- **`services/connectors/app/connectors/kubernetes_audit.py`** —+ `KubernetesAuditConnector` shipping with two delivery modes selected via the+ `mode` config field:+ - **`webhook` (recommended)** — Kubernetes API server pushes audit events+ to AiSOC's new dedicated `POST /v1/ingest/k8s-audit/{tenant_id}` route,+ authenticated with a shared secret in the `X-AiSOC-K8s-Token` header+ (compared in constant time so partial-prefix matches still fail). The+ legacy `/v1/inbox/{token}` path with the `k8s-audit` template is kept+ around as a fallback for control planes that cannot inject custom+ headers into the audit-webhook kubeconfig.+ - **`file_tail`** — AiSOC's connector pod tails a local `audit.log` file+ using a byte-position cursor (atomically written to a `.aisoc-cursor`+ sidecar), with rotation/truncation detection and a hard per-poll byte cap+ so a backlog can't blow up a single poll cycle.+- **`services/ingest/internal/handler/k8s_audit.go`** — New Go handler for+ the dedicated webhook route. Caps body size via `K8S_AUDIT_MAX_BODY_BYTES`+ (default 16 MiB), rejects oversized batches with `413` so the apiserver+ shrinks `--audit-webhook-batch-max-size` and retries, and publishes each+ `EventList.items[]` entry through the existing normalizer + Kafka publisher+ using `connector_type: kubernetes_audit`. The route is disabled (returns+ `503`) until an operator sets `K8S_AUDIT_SHARED_SECRET`, so a fresh+ install never accidentally accepts unauthenticated audit traffic.+- **`services/ingest/internal/normalizer/normalizer.go`** — Added the+ `kubernetes_audit` connector profile. Maps `auditID` to `external_id`,+ `verb` to `activity_name`, `user.username` to `actor.user.name`,+ `objectRef.{namespace,resource,name}` to a composite `target.resource.name`,+ and translates the connector's string severity (`critical|high|medium|low|+ info`) into OCSF integer severities (5/4/3/2/1).+- **`services/ingest/internal/normalizer/templates/k8s-audit.yaml`** — New+ inbox template (legacy path) that maps Kubernetes apiserver `Event`+ payloads (`apiVersion: audit.k8s.io/v1`) onto AiSOC's normalised event+ shape:+ - `external_id ← auditID`+ - `vendor ← "Kubernetes"`, `product ← "apiserver-audit"`,+ `category ← "k8s_audit"`+ - `actor ← user.username` (plus `user.groups` carried through metadata)+ - `target ← objectRef.namespace + "/" + objectRef.resource + "/" ++ objectRef.name`+ - `severity` is derived in the connector's `_classify_severity` heuristic,+ not in the template, so the same logic applies to both delivery modes.+- **Severity heuristic** (`_classify_severity` in `kubernetes_audit.py`):+ - `high` — `exec`/`attach`/`portforward` on a Pod, `create` on+ `ClusterRoleBinding`, `impersonate` verb, `update` on+ `serviceaccounts/token`, any `RequestResponse` event where+ `responseStatus.code >= 500` on a sensitive verb.+ - `medium` — `create`/`patch`/`delete` on `Secret`/`ConfigMap`/+ `ClusterRole`/`Role`, `escalate` verb, failed authentication+ (`responseStatus.code == 401|403`) on a write verb.+ - `low` — successful reads on sensitive resources (`get` on `Secret`),+ successful writes on routine resources.+ - `info` — everything else (health probes, list/watch on benign resources,+ successful low-impact reads).+- **`plugins/kubernetes-audit/plugin.yaml`** — Manifest with a 4-field config+ schema (`mode`, `cluster_name`, `inbox_token`, `audit_log_path`,+ `cursor_path`), `category: cloud`, capabilities `pull_audit` + `pull_alerts`.+- **`apps/docs/docs/connectors/kubernetes-audit.md`** — Includes a complete+ sample `AuditPolicy` (omitStages on RequestReceived for verbosity control;+ Metadata level for routine reads, RequestResponse for writes on Secret /+ ConfigMap / ClusterRoleBinding) and a sample `AuditSink` pointing at AiSOC's+ inbox URL.++#### Cross-cutting++- **`marketplace/index.json` + `apps/web/public/marketplace/index.json`** —+ Rebuilt via `pnpm marketplace:sync`. Plugin count rose from 43 → 49 (+6+ cloud connectors). Total marketplace entries: `total=7104 detections=6993+ playbooks=62 plugins=49 mitre_techniques=493`.+- **`apps/web/package.json`** — Version bumped from `7.0.3` to `7.1.0`; the+ sidebar and landing-page footer both surface the new version automatically.++#### Test footprint++- 43 unit tests for `KubernetesAuditConnector` covering both delivery modes,+ cursor persistence, rotation/truncation, byte-cap drain semantics, and the+ full severity-heuristic decision table.+- 27 unit tests for `AWSVPCFlowLogsConnector` covering v2/v5 parsing,+ public-IP classification edge cases (RFC1918, CGNAT, TEST-NET-1/2/3), and+ the default REJECT filter pattern.+- Mirroring tests for `PrismaCloudConnector`, `OrcaConnector`,+ `AWSGuardDutyConnector`, `AWSCloudTrailConnector` covering schema,+ normalise, pagination, and auth-error paths.+- Full `services/connectors` suite passes at 364 tests; schema-introspection+ tests in `services/api` also pass with the six new connectors added to+ `_CONNECTOR_CLASSES`.++---+## [7.0.3] — 2026-05-10### Fixed — Hydration mismatch, font preload warningsdiff --git a/README.md b/README.mdindex 8699b5896..70d42b095 100644--- a/README.md+++ b/README.md@@ -9,7 +9,7 @@ An open-source, self-hostable AI SOC. The agent's prompts, tool calls, and ratio[](https://opensource.org/licenses/MIT)[](apps/docs/docs/benchmark.md)[](CONTRIBUTING.md)-[](CHANGELOG.md)+[](CHANGELOG.md)[Live demo](https://tryaisoc.com) · [How AiSOC compares](#how-aisoc-compares) · [Public eval harness](apps/docs/docs/benchmark.md) · [Deploy in 60 seconds](#deploy-in-60-seconds) · [Deployment options](#deployment-options) · [Architecture](#architecture) · [Docs](apps/docs/)@@ -123,7 +123,7 @@ Full guide: [docs/integrations/mcp](apps/docs/docs/integrations/mcp.md). Source:AiSOC bundles the components a SOC normally pieces together from separate vendors:-- **Connect data sources in three clicks** — a 45-connector click-and-connect catalog spans EDR/XDR (CrowdStrike Falcon, SentinelOne, Microsoft Defender XDR, Palo Alto Cortex XDR, Cortex XSIAM, VMware Carbon Black, Trellix Helix, Trend Vision One), SIEM (Splunk, Microsoft Sentinel, Elastic, Sumo Logic, Datadog Cloud SIEM, Google Chronicle, Rapid7 InsightIDR), cloud (AWS Security Hub, Azure Activity, Azure Defender, GCP Cloud Audit, GCP SCC, Wiz, Lacework, Tenable), identity (Okta, Microsoft Entra, Auth0, Duo Security, 1Password), SaaS (Microsoft 365 audit, Google Workspace, Cloudflare, Proofpoint, Mimecast, ServiceNow, Jira, Slack audit, Salesforce, Email inbox), VCS (GitHub, Snyk), endpoint fleet (osctrl, FleetDM for fleet-wide osquery), and network (Tailscale, Zscaler, Cisco Umbrella). Each connector renders a schema-driven form, runs a live `Test connection` round-trip before save, encrypts every secret with the application-layer `CredentialVault` (Fernet AES-128-CBC + HMAC-SHA256), and starts polling on a per-instance schedule. Walkthrough: [docs/connectors](apps/docs/docs/connectors/index.md). Threat model + key rotation: [docs/operations/credentials](apps/docs/docs/operations/credentials.md).+- **Connect data sources in three clicks** — a 51-connector click-and-connect catalog spans EDR/XDR (CrowdStrike Falcon, SentinelOne, Microsoft Defender XDR, Palo Alto Cortex XDR, Cortex XSIAM, VMware Carbon Black, Trellix Helix, Trend Vision One), SIEM (Splunk, Microsoft Sentinel, Elastic, Sumo Logic, Datadog Cloud SIEM, Google Chronicle, Rapid7 InsightIDR), cloud + CNAPP (AWS Security Hub, AWS GuardDuty, AWS CloudTrail, AWS VPC Flow Logs, Azure Activity, Azure Defender, GCP Cloud Audit, GCP SCC, Wiz, Lacework, Tenable, Prisma Cloud, Orca), identity (Okta, Microsoft Entra, Auth0, Duo Security, 1Password), SaaS (Microsoft 365 audit, Google Workspace, Cloudflare, Proofpoint, Mimecast, ServiceNow, Jira, Slack audit, Salesforce, Email inbox), VCS (GitHub, Snyk), endpoint fleet (osctrl, FleetDM for fleet-wide osquery), container + orchestration (Kubernetes audit logs via apiserver webhook or `audit.log` tail), and network (Tailscale, Zscaler, Cisco Umbrella). Each connector renders a schema-driven form, runs a live `Test connection` round-trip before save, encrypts every secret with the application-layer `CredentialVault` (Fernet AES-128-CBC + HMAC-SHA256), and starts polling on a per-instance schedule. Walkthrough: [docs/connectors](apps/docs/docs/connectors/index.md). Threat model + key rotation: [docs/operations/credentials](apps/docs/docs/operations/credentials.md).- **Own your endpoint telemetry** — first-party `aisoc-osquery-tls` FastAPI service (`services/osquery-tls/`) and `aisoc-direct` lightweight agent connector ship a self-hosted osquery TLS plugin, FleetDM-compatible config/log endpoints, and a direct-from-agent ingest path that bypasses third-party SaaS. Built-in **file integrity monitoring (FIM)** endpoint (`services/osquery-tls/app/api/v1/endpoints/fim.py`) ingests `file_events` and synthesizes alerts on writes to `/etc/passwd`, `/etc/shadow`, sshd configs, sudoers, and Windows registry hives; bundled osquery packs cover incident response, OSquery-ATT&CK, and FIM out of the box. **16 native osquery detections** (`detections/endpoint/osquery-*.yaml`, IDs `det-endpoint-281..296`) cover credential access, persistence, lateral movement, defense evasion, and discovery — paired with positive/negative test fixtures (`detections/fixtures/osquery_*.json`) and CI-gated against the Detection Validation workflow. **Live-query playbook step** (`osquery_live_query`) lets responders push allowlisted distributed queries to single hosts or fleet-wide via osctrl/FleetDM with HMAC-signed ChatOps approval. **5 custom Go-based virtual tables** (`services/osquery-extensions/`) extend the agent with `aisoc_browser_extensions`, `aisoc_kernel_modules`, `aisoc_attck_persistence`, `aisoc_pending_actions`, and `aisoc_alert_cache` for richer endpoint visibility and bidirectional response. Walkthroughs: [docs/connectors/osctrl](apps/docs/docs/connectors/osctrl.md), [docs/connectors/fleetdm](apps/docs/docs/connectors/fleetdm.md).- **Ingest** events from any connector into a Kafka spine.- **Correlate** them in real time with deduplication, ML scoring, per-alert confidence scoring, and Sigma/YARA detection.@@ -878,11 +878,12 @@ terraform apply## Roadmap-The public roadmap lives in [ROADMAP.md](ROADMAP.md). All releases through **v7.0.3** have shipped, including:+The public roadmap lives in [ROADMAP.md](ROADMAP.md). All releases through **v7.1.0** have shipped, including:- **v6.0 / v6.1** — Investigation Ledger, Ambient Copilot, Responder PWA, public eval harness, MCP server, one-shot demo, autonomous triage agents, investigation chat, coverage advisor, shifts, EASM, MSSP dashboard, STIX/TAXII publishing, automated compliance evidence, AI-generated incident reports.- **v7.0** — v1.0 buyer-value plan (16 workstreams): SBOM/SLSA supply chain, threat-intel attribution, executive digest PDF, BYOK per-tenant LLM credentials, air-gap appliance, WCAG 2.2 AA accessibility, ChatOps, telemetry/analytics opt-in, one-click Render deploy.- **v7.0.1 — v7.0.3** — Endpoint telemetry wave: `osctrl` and `FleetDM` connectors, `aisoc-osquery-tls` FastAPI service, `aisoc-direct` agent connector, 16 native osquery detections (`det-endpoint-281..296`), live-query playbook step, osquery packs + FIM pipeline, 5 custom osquery virtual tables; plus 42 CodeQL alert resolutions and the `ClientOnly`/font-preload hydration fixes.+- **v7.1.0** — Cloud Security Coverage Wave: documentation backfill for Wiz, AWS Security Hub, and Lacework; two new CNAPP connectors (Prisma Cloud, Orca); three native AWS connectors (GuardDuty, CloudTrail, VPC Flow Logs); dual-mode Kubernetes audit log connector (apiserver webhook + file_tail) with a new `k8s-audit` ingest template.Next (**v8.0** — see [ROADMAP.md](ROADMAP.md)):diff --git a/ROADMAP.md b/ROADMAP.mdindex 28234ffdd..b3e280d79 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -265,6 +265,118 @@ the v7.0 release window and then patched through 7.0.1 → 7.0.3.---+## v7.1.0 — Shipped ✅ (2026-05-10) — Cloud Security Coverage Wave++Six new connectors, three documentation backfills, and a new ingest template+closing the biggest cloud-security gap in the connector catalogue. Every Tier-1+cloud workload protection platform now has a first-class AiSOC integration,+AWS gets three native data sources, and Kubernetes audit logs land via a+dual-mode connector that works on both managed and air-gapped clusters.++### Track A — Documentation backfill for existing cloud connectors++- [x] **`apps/docs/docs/connectors/wiz.md`** — Service-account creation,+ `read:issues` + `read:vulnerabilities` scopes, token rotation, normalised+ severity map, worked Wiz `Issue` → inbox event example.+- [x] **`apps/docs/docs/connectors/aws-security-hub.md`** — IAM-role vs.+ static-key auth, `securityhub:GetFindings` permission, and the+ `BLOCK_IP`/`ALLOW_IP` capability documented end-to-end against+ `services/actions/app/clients/aws_security_groups.py`.+- [x] **`apps/docs/docs/connectors/lacework.md`** — API-token flow, `api_url`+ regional variants, alert → event severity collapse.+- [x] **`apps/docs/sidebars.ts`** — All three backfilled pages + the four new+ Track B–D pages registered under the `Connectors` category.++### Track B — New CNAPP connectors++- [x] **`PrismaCloudConnector`** (`services/connectors/app/connectors/prisma_cloud.py`)+ — Full CSPM/CWPP coverage. JWT auth via `POST /login`, paginated+ `GET /alert/v1/alert` with windowed `time.from`/`time.to`, severity collapse,+ `compute_url` override for self-hosted Compute Edition.+- [x] **`OrcaConnector`** (`services/connectors/app/connectors/orca.py`) —+ `https://api.orcasecurity.io/api/alerts` with `api_token` auth, severity+ collapse with Orca-specific `hazardous → high` rule.+- [x] Manifests at `plugins/prisma-cloud/plugin.yaml` and `plugins/orca/plugin.yaml`,+ docs at `apps/docs/docs/connectors/{prisma-cloud,orca}.md`, full test+ suites under `services/connectors/tests/test_{prisma_cloud,orca}.py`.++### Track C — Native AWS connectors++- [x] **`AWSGuardDutyConnector`** (`services/connectors/app/connectors/aws_guardduty.py`)+ — boto3-based, supports IAM-role + static-key auth via `_resolve_session`,+ iterates detectors with `list_findings` + `get_findings`. Collapses+ GuardDuty's continuous numeric severity scale (`0.1`–`10.0`) into AiSOC's+ four-tier `info|low|medium|high` ladder.+- [x] **`AWSCloudTrailConnector`** (`services/connectors/app/connectors/aws_cloudtrail.py`)+ — `cloudtrail.lookup_events` with a curated 21-event allow-list covering+ identity abuse, persistence, data-plane abuse, network exposure, and trail+ tampering. Allow-list overridable via the `event_names` field.+- [x] **`AWSVPCFlowLogsConnector`** (`services/connectors/app/connectors/aws_vpc_flow.py`)+ — `cloudwatch_logs.filter_log_events`, v2 + v5 format parsing,+ RFC-5735-aware public-IP heuristic, default `?REJECT` filter pattern,+ severity heuristic (`public REJECT → medium`, `internal REJECT → low`,+ `ACCEPT → info`).+- [x] Manifests + docs + tests for all three connectors. 27 unit tests for+ `AWSVPCFlowLogsConnector` covering v2/v5 parsing and public-IP edge cases.++### Track D — Kubernetes audit logs (dual-mode)++- [x] **`KubernetesAuditConnector`** (`services/connectors/app/connectors/kubernetes_audit.py`)+ ships with two delivery modes selected via the `mode` config field:+ - **`webhook` (recommended)** — apiserver pushes audit events to AiSOC's+ new dedicated `POST /v1/ingest/k8s-audit/{tenant_id}` route,+ authenticated with a shared secret in the `X-AiSOC-K8s-Token` header+ (constant-time compared so a partial-prefix attacker can't shave+ bytes off via timing). Legacy `/v1/inbox/{token}` path with the+ `k8s-audit` template is kept as a fallback for control planes that+ cannot inject custom headers into the audit-webhook kubeconfig.+ - **`file_tail`** — AiSOC's connector pod tails a local `audit.log` using+ a byte-position cursor (atomically written via `os.replace` to a+ `.aisoc-cursor` sidecar) with rotation/truncation detection and a hard+ per-poll byte cap so a backlog can't blow up a single poll cycle.+- [x] **`services/ingest/internal/handler/k8s_audit.go`** — Dedicated Go+ handler for the webhook route. Caps body size via+ `K8S_AUDIT_MAX_BODY_BYTES` (default 16 MiB), rejects oversized batches+ with `413` so the apiserver shrinks `--audit-webhook-batch-max-size`+ and retries, and publishes each `EventList.items[]` entry through the+ existing normalizer + Kafka publisher using+ `connector_type: kubernetes_audit`. The route is disabled (returns+ `503`) until an operator sets `K8S_AUDIT_SHARED_SECRET`, so a fresh+ install never accidentally accepts unauthenticated audit traffic.+- [x] **`kubernetes_audit` normalizer profile**+ (`services/ingest/internal/normalizer/normalizer.go`) — Maps `auditID`+ to `external_id`, `verb` to `activity_name`, `user.username` to+ `actor.user.name`, `objectRef.{namespace,resource,name}` to a+ composite `target.resource.name`, and translates the connector's+ string severity (`critical|high|medium|low|info`) into OCSF integer+ severities (5/4/3/2/1).+- [x] **`k8s-audit` inbox template**+ (`services/ingest/internal/normalizer/templates/k8s-audit.yaml`) —+ maps apiserver `Event` payloads onto AiSOC's normalised event shape+ for the legacy inbox-token path; severity is derived in the+ connector's `_classify_severity` heuristic so the same logic applies+ to both delivery modes.+- [x] **Severity heuristic** — `exec`/`attach`/`portforward` on Pod and+ `create` on `ClusterRoleBinding` → `high`; writes to `Secret`/`ConfigMap`/+ `ClusterRole`/`Role` → `medium`; successful reads on sensitive resources+ → `low`; everything else → `info`.+- [x] **`plugins/kubernetes-audit/plugin.yaml`** — 4-field config schema+ (`mode`, `cluster_name`, `inbox_token`, `audit_log_path`, `cursor_path`),+ `category: cloud`, capabilities `pull_audit` + `pull_alerts`.+- [x] **`apps/docs/docs/connectors/kubernetes-audit.md`** — Sample `AuditPolicy`+ + sample `AuditSink` for both managed and self-hosted clusters.++### Cross-cutting++- [x] **`pnpm marketplace:sync`** — `marketplace/index.json` ++ `apps/web/public/marketplace/index.json` rebuilt; plugin count rose+ `43 → 49`. Total: `total=7104 detections=6993 playbooks=62 plugins=49+ mitre_techniques=493`.+- [x] **`apps/web/package.json`** bumped to `7.1.0`; sidebar and landing-page+ footer surface the new version dynamically.++---+## v8.0 — Planned- Mobile responder console (React Native) — triage and acknowledge from phonediff --git a/apps/docs/docs/connectors/aws-cloudtrail.md b/apps/docs/docs/connectors/aws-cloudtrail.mdnew file mode 100644index 000000000..13cdf3e03--- /dev/null+++ b/apps/docs/docs/connectors/aws-cloudtrail.md@@ -0,0 +1,202 @@+---+sidebar_position: 22+title: AWS CloudTrail+description: Native AWS CloudTrail audit-event ingestion with a curated high-signal allow-list — IAM grants, trail tampering, public-S3 changes, KMS destruction, and more.+---++# AWS CloudTrail++The AWS CloudTrail connector polls **management-plane API events** from+the CloudTrail event history. Unlike a raw CloudTrail-to-S3 firehose,+this connector ships with a **curated allow-list of ~80 high-signal+event names** chosen to align 1:1 with AiSOC's bundled cloud detection+content.++That choice is deliberate. A busy production AWS account emits **tens+of thousands of CloudTrail events per minute**, the vast majority of+which are read-only describes / lists from AWS services themselves.+Blindly ingesting all of them would saturate the alert pipeline without+producing any net new detection signal. The allow-list keeps ingest+volume tractable while still surfacing every event the bundled+detections actually fire on.++Use the [AWS GuardDuty](/docs/connectors/aws-guardduty) connector for+ML-based threat detection. Use this CloudTrail connector for+**deterministic detection of sensitive AWS API calls** — IAM grants,+trail tampering, public-S3 changes, KMS key destruction, cross-account+sharing, console logins, and so on.++## What you get++| Source | CloudTrail API | Notes |+|---|---|---|+| Management events | `LookupEvents` | One filtered call per event-name in the allow-list |++Events are normalized with `source: aws_cloudtrail` and+`category: cloud`. The full embedded `CloudTrailEvent` payload is+preserved on `raw_event` so detection rules and playbooks can inspect+`requestParameters`, `responseElements`, and the full `userIdentity`+shape.++## Capabilities++| Capability | Backed by | Notes |+|---|---|---|+| `PULL_ALERTS` | `cloudtrail:LookupEvents` | Default — every connector instance |++CloudTrail is read-only. To **block** a malicious IP that surfaces in a+CloudTrail event (e.g. a `ConsoleLogin` from an unexpected geography),+route the alert through a playbook that uses the+[AWS Security Hub](/docs/connectors/aws-security-hub) connector's+`BLOCK_IP` capability or any other network-control connector.++## Prerequisites++- AWS CloudTrail **enabled** in the region you want to monitor — the+ default `Management events: Read/Write` trail that AWS provisions+ on every account is enough.+- IAM permissions:+ - `cloudtrail:LookupEvents`+ - `cloudtrail:DescribeTrails` (used by `Test connection`)+ - `sts:AssumeRole` (only if you target a role in another account)+- One of:+ - **Static access key** (`AccessKeyId` + `SecretAccessKey`) for a dedicated+ IAM user, **or**+ - **No credentials at all** — AiSOC falls back to the **runtime IAM role+ / instance profile** of the host running the `connectors` service.++The runtime-IAM-role path is strongly preferred for production deployments.++## Setup walkthrough++### 1. (Optional) Create a least-privilege IAM user++If you cannot use an instance role, create a dedicated IAM user with+**only** the policy below, and capture an access key for it:++```json+{+ "Version": "2012-10-17",+ "Statement": [+ {+ "Sid": "AiSOCCloudTrailRead",+ "Effect": "Allow",+ "Action": [+ "cloudtrail:LookupEvents",+ "cloudtrail:DescribeTrails"+ ],+ "Resource": "*"+ }+ ]+}+```++### 2. Add the connector in AiSOC++1. **Connectors → Add connector → AWS CloudTrail**.+2. Set **AWS Region** (e.g. `us-east-1`).+3. Leave **Access Key ID** and **Secret Access Key** **blank** to use the+ runtime IAM role. Otherwise paste the static credentials from step 1.+4. Leave **Event allow-list** blank to use AiSOC's curated default+ (recommended). See [Customising the allow-list](#customising-the-allow-list)+ below if you need to override it.+5. **Test connection** — AiSOC calls `DescribeTrails` to verify auth.+6. **Save**.++## Polling details++- Default interval: **300 seconds**.+- Each poll iterates the configured event allow-list and issues one+ paginated `LookupEvents` call per event name, filtered by+ `LookupAttributes={EventName=<name>}` and the time window+ `(now - 300s, now)`.+- Per-event-name results are capped at **100 events per poll** to bound+ memory and respect the AWS CloudTrail rate limit+ (**2 transactions per second per region per account**).+- Failures on any single event-name lookup are logged and skipped — one+ bad attribute does not halt the rest of the poll.++## Severity mapping++CloudTrail events do **not** carry intrinsic severity, so AiSOC labels+each event by sensitivity:++| Event class | Examples | AiSOC severity |+|---|---|---|+| Trail/detection tamper, KMS destruction, root account use, org tampering | `DeleteTrail`, `StopLogging`, `DisableSecurityHub`, `ScheduleKeyDeletion`, `RemoveAccountFromOrganization`, `LeaveOrganization` | `high` |+| Mutating IAM / network / public-S3 / config | `CreateAccessKey`, `AttachUserPolicy`, `PutBucketPolicy`, `AuthorizeSecurityGroupIngress`, `PutKeyPolicy` | `medium` |+| Read-only recon | `GetAccountAuthorizationDetails`, `ListAccessKeys`, `GetSecretValue` | `low` |++If the event has an `errorCode` set (the API call was denied), AiSOC+**bumps the severity up one tier**. A denied destructive action is+often the loudest signal in the account — for example, an attacker+trying `StopLogging` against a trail they don't have permission to+modify.++## Customising the allow-list++The `event_names` field accepts three modes:++- **Blank** (default) — use AiSOC's curated detection-aligned default+ list. This is the right answer for ~95% of operators.+- **Comma-separated event names** — replace the default with your own+ list. Example: `ConsoleLogin,CreateAccessKey,PutBucketPolicy,DeleteTrail`.+ Useful when you've added custom detection content and want to+ surface a narrower set than the default.+- **`*`** — disable filtering entirely. AiSOC will pull every+ CloudTrail event in the time window. **High volume warning** — only+ use this in lab/staging accounts or when you have downstream+ rate-limiting in place. A single production account on `*` can+ generate millions of events per day.++The default list is curated against the bundled+`detections/cloud/aws-*.yaml` rules — every event name in it is+referenced by at least one detection rule.++## Multi-account / multi-region++CloudTrail's management-event history is per-region. To cover an+account globally, add **one connector instance per region** that hosts+production workloads. The connector emits an `aws_region` field on+every event so playbooks can branch on origin.++For multi-account topologies, prefer one connector per+account × region pair, each with its own IAM credentials. CloudTrail+does not have a delegated-administrator pattern equivalent to+GuardDuty.++## Troubleshooting++**`AccessDenied` on `LookupEvents`** — the IAM user / role is missing+`cloudtrail:LookupEvents`. Reattach the policy from step 1.++**Test connection succeeds but no events appear** — confirm the+allow-list is not over-narrow for your account, and that the events+you expect are actually firing in the AWS console under+**CloudTrail → Event history**. Try setting `event_names` to `*`+temporarily (in lab) to confirm the connection works.++**Events arrive several minutes late** — CloudTrail is **eventually+consistent**. AWS publishes a typical end-to-end delivery latency of+~15 minutes. AiSOC polls a 5-minute window every 300 seconds with no+high-water-mark cursor, so events that arrive late will be picked up+on the next poll cycle.++**Rate-limit / `ThrottlingException`** — the allow-list iteration can+hit the 2-TPS-per-region CloudTrail limit if the list is very large+or polling is set very aggressively. Reduce the allow-list, increase+the poll interval, or split the load across multiple connector+instances per region.++**`boto3 is required` at runtime** — boto3 is bundled with the+`services/connectors` Docker image. If you are running the service+outside Docker, install it: `pip install boto3`.++## Related++- [AWS GuardDuty](/docs/connectors/aws-guardduty) — ML-based threat+ detection layered on top of CloudTrail, VPC Flow Logs, and DNS.+- [AWS Security Hub](/docs/connectors/aws-security-hub) — multi-source+ finding aggregator with `BLOCK_IP` / `ALLOW_IP` containment.+- [AWS VPC Flow Logs](/docs/connectors/aws-vpc-flow) — raw network+ telemetry to cross-reference against CloudTrail events.diff --git a/apps/docs/docs/connectors/aws-guardduty.md b/apps/docs/docs/connectors/aws-guardduty.mdnew file mode 100644index 000000000..6c9140ad1--- /dev/null+++ b/apps/docs/docs/connectors/aws-guardduty.md@@ -0,0 +1,168 @@+---+sidebar_position: 21+title: AWS GuardDuty+description: Native AWS GuardDuty findings — VPC flow, DNS, CloudTrail, EKS, S3, RDS, and Lambda threat detection without going through Security Hub.+---++# AWS GuardDuty++The AWS GuardDuty connector pulls **findings directly from the GuardDuty+API** — no Security Hub aggregation in between. This gives AiSOC the+**richest possible per-finding context** (network connection action,+runtime details, EKS audit, S3 access patterns) in exactly the shape+AWS publishes them.++Use this connector when you want first-class GuardDuty alerts. Use the+[AWS Security Hub](/docs/connectors/aws-security-hub) connector instead+(or in addition) when you want **one connector for many providers**.++## What you get++| Source | GuardDuty API | Notes |+|---|---|---|+| Active findings | `ListFindings` + `GetFindings` | All detector types — VPC, DNS, CloudTrail, EKS, S3, RDS, Lambda |++Events are normalized with `source: aws_guardduty` and the original+GuardDuty finding is preserved on `raw_event` for downstream playbooks+and detection content.++## Capabilities++| Capability | Backed by | Notes |+|---|---|---|+| `PULL_ALERTS` | `guardduty:GetFindings` | Default — every connector instance |++GuardDuty is read-only in this release. To **block** a malicious IP the+connector surfaces, route the alert through a playbook that uses the+[AWS Security Hub](/docs/connectors/aws-security-hub) connector's+`BLOCK_IP` capability or any other network-control connector.++## Prerequisites++- AWS GuardDuty **enabled** in the region you want to monitor (one+ connector instance per region).+- IAM permissions:+ - `guardduty:ListDetectors`+ - `guardduty:ListFindings`+ - `guardduty:GetFindings`+ - `sts:AssumeRole` (only if you target a role in another account)+- One of:+ - **Static access key** (`AccessKeyId` + `SecretAccessKey`) for a dedicated+ IAM user, **or**+ - **No credentials at all** — AiSOC falls back to the **runtime IAM role+ / instance profile** of the host running the `connectors` service.++The runtime-IAM-role path is strongly preferred for production deployments.++## Setup walkthrough++### 1. Enable GuardDuty (if not already)++In the AWS console, **GuardDuty → Get Started → Enable GuardDuty** in+the region you want to monitor. GuardDuty creates a single detector per+region. Repeat per region; each region needs its own AiSOC connector+instance.++### 2. (Optional) Create a least-privilege IAM user++If you cannot use an instance role, create a dedicated IAM user with+**only** the policy below, and capture an access key for it:++```json+{+ "Version": "2012-10-17",+ "Statement": [+ {+ "Sid": "AiSOCGuardDutyRead",+ "Effect": "Allow",+ "Action": [+ "guardduty:ListDetectors",+ "guardduty:ListFindings",+ "guardduty:GetFindings"+ ],+ "Resource": "*"+ }+ ]+}+```++### 3. Add the connector in AiSOC++1. **Connectors → Add connector → AWS GuardDuty**.+2. Set **AWS Region** (e.g. `us-east-1`).+3. Leave **Access Key ID** and **Secret Access Key** **blank** to use the+ runtime IAM role. Otherwise paste the static credentials from step 2.+4. **Test connection** — AiSOC calls `ListDetectors` and confirms the+ call returns 200. The response also reports how many detectors were+ discovered (typically `1` per region).+5. **Save**.++## Polling details++- Default interval: **300 seconds**.+- Each poll:+ 1. `ListDetectors` to discover every detector in the region.+ 2. `ListFindings` per detector with criteria+ `updatedAt >= (now - 300s)` and `service.archived == false`, capped+ at **500 IDs per detector** to bound memory.+ 3. `GetFindings` in batches of **50 IDs** (the GuardDuty hard limit).+- Archived findings are skipped — if you re-archive in the GuardDuty+ console, AiSOC stops surfacing them on the next poll.++## Severity mapping++GuardDuty publishes severity as a **float in the range 1.0–8.9**. AiSOC's+canonical ladder is `info | low | medium | high`. We bucket using AWS's+own published thresholds:++| GuardDuty score | AiSOC severity |+|---|---|+| `< 1.0` (rare — sample / test findings) | `info` |+| `1.0 – 3.9` | `low` |+| `4.0 – 6.9` | `medium` |+| `7.0 – 8.9` | `high` |++The original float severity is preserved on `raw_event.Severity`.++## Multi-account / multi-region++GuardDuty can be operated in a **delegated administrator** account that+aggregates member-account findings into a single detector. AiSOC supports+both topologies:++- **Aggregator account** — point one connector at the delegated admin's+ region and credentials. You'll see member-account findings via the+ `accountId` field on each finding.+- **Per-account** — one connector instance per account × region pair, each+ with its own IAM credentials.++For multi-region without a delegated admin, add **one connector per+region** (each region runs an independent GuardDuty detector).++## Troubleshooting++**`AccessDenied` on `ListDetectors`** — the IAM user / role is missing+`guardduty:ListDetectors`. Reattach the policy from step 2.++**`Test connection` succeeds with `detector_count: 0`** — GuardDuty is+not enabled in this region. Enable it in the AWS console; the next poll+will pick up the new detector automatically.++**No findings appear in AiSOC even though GuardDuty shows them** — by+default AiSOC filters out **archived** findings. Verify the findings+in question are still in the `unarchived` state.++**`boto3 is required` at runtime** — boto3 is bundled with the+`services/connectors` Docker image. If you are running the service+outside Docker, install it: `pip install boto3`.++## Related++- [AWS Security Hub](/docs/connectors/aws-security-hub) — aggregator+ alternative; covers GuardDuty + Inspector + Macie + third-party+ finding providers in one connector, plus inline `BLOCK_IP` /+ `ALLOW_IP` containment.+- [AWS CloudTrail](/docs/connectors/aws-cloudtrail) — high-signal API+ events for AWS-native detections.+- [AWS VPC Flow Logs](/docs/connectors/aws-vpc-flow) — raw network+ telemetry that GuardDuty itself analyses.diff --git a/apps/docs/docs/connectors/aws-security-hub.md b/apps/docs/docs/connectors/aws-security-hub.mdnew file mode 100644index 000000000..9d484adbd--- /dev/null+++ b/apps/docs/docs/connectors/aws-security-hub.md@@ -0,0 +1,165 @@+---+sidebar_position: 17+title: AWS Security Hub+description: AWS Security Hub findings (GuardDuty, Inspector, Macie, third-party) with optional inline IP block / allow via EC2 security groups.+---++# AWS Security Hub++The AWS Security Hub connector pulls **findings from AWS Security Hub**+into AiSOC and unlocks **inline containment** by writing ingress / egress+rules onto an EC2 security group.++Security Hub aggregates findings from native AWS services+(**GuardDuty**, **Inspector**, **Macie**, **IAM Access Analyzer**,+**Config**) and from any **third-party finding provider** that publishes+to ASFF. One connector instance covers them all.++## What you get++| Source | Security Hub API | Notes |+|---|---|---|+| Active findings | `GetFindings` with `WorkflowStatus = NEW \| NOTIFIED` | All providers, deduped by Security Hub |++Events are normalized with `source: aws_security_hub` and the original+ASFF finding is preserved on `raw_event` for downstream playbooks.++## Capabilities++| Capability | Backed by | Notes |+|---|---|---|+| `PULL_ALERTS` | `securityhub:GetFindings` | Default — every connector instance |+| `BLOCK_IP` | `ec2:AuthorizeSecurityGroupIngress` via `services/actions/app/clients/aws_security_groups.py` | Requires playbook step that supplies an `aws_security_group_id` |+| `ALLOW_IP` | `ec2:RevokeSecurityGroupIngress` | Same playbook step, opposite direction |++The Security Hub connector itself only authenticates the **read** path;+the Block / Allow actions reuse the same credentials at action-execution+time via the actions service.++## Prerequisites++- AWS Security Hub **enabled** in at least one region.+- IAM permissions:+ - `securityhub:GetFindings` (required for `PULL_ALERTS`)+ - `ec2:AuthorizeSecurityGroupIngress` and+ `ec2:RevokeSecurityGroupIngress` (only if you want `BLOCK_IP` / `ALLOW_IP`)+ - `sts:AssumeRole` (only if you target a role in another account)+- One of:+ - **Static access key** (`AccessKeyId` + `SecretAccessKey`) for a dedicated+ IAM user, **or**+ - **No credentials at all** — AiSOC falls back to the **runtime IAM role+ / instance profile** of the host running the `connectors` service.++The runtime-IAM-role path is strongly preferred for production deployments.++## Setup walkthrough++### 1. Enable Security Hub (if not already)++In the AWS console, **Security Hub → Enable Security Hub** in the region+you want to monitor. Repeat per region; each region needs its own connector+instance.++### 2. (Optional) Create a least-privilege IAM user++If you cannot use an instance role, create a dedicated IAM user with+**only** the policy below, and capture an access key for it:++```json+{+ "Version": "2012-10-17",+ "Statement": [+ {+ "Sid": "AiSOCSecurityHubRead",+ "Effect": "Allow",+ "Action": ["securityhub:GetFindings"],+ "Resource": "*"+ },+ {+ "Sid": "AiSOCInlineContainment",+ "Effect": "Allow",+ "Action": [+ "ec2:AuthorizeSecurityGroupIngress",+ "ec2:RevokeSecurityGroupIngress",+ "ec2:DescribeSecurityGroups"+ ],+ "Resource": "*"+ }+ ]+}+```++Drop the `AiSOCInlineContainment` statement if you only want read.++### 3. Add the connector in AiSOC++1. **Connectors → Add connector → AWS Security Hub**.+2. Set **AWS Region** (e.g. `us-east-1`).+3. Leave **Access Key ID** and **Secret Access Key** **blank** to use the+ runtime IAM role. Otherwise paste the static credentials from step 2.+4. **Test connection** — AiSOC runs `GetFindings(MaxResults=1)` and+ confirms the call returns 200.+5. **Save**.++## Polling details++- Default interval: **300 seconds**.+- Each poll calls `GetFindings` with `WorkflowStatus IN [NEW, NOTIFIED]`+ to skip findings already triaged in Security Hub.+- Pagination is currently **single-page (100 findings)** — the most recent+ 100 NEW/NOTIFIED findings per poll. Fine-grained windowing is on the+ v7.2 roadmap.++## Severity mapping++Security Hub uses the ASFF 4-tier ladder (`CRITICAL`, `HIGH`, `MEDIUM`,+`LOW`). AiSOC maps these directly:++| ASFF label | AiSOC severity |+|---|---|+| `CRITICAL` | `high` |+| `HIGH` | `high` |+| `MEDIUM` | `medium` |+| `LOW` | `low` |+| `INFORMATIONAL` (unmapped) | `info` |++The original ASFF severity is preserved on `raw_event.Severity.Label`.++## Containment via security groups++When an AiSOC playbook calls `BLOCK_IP` against an alert that came from+this connector, the actions service authorizes a **deny ingress rule** on+the configured security group:++- Default port range: `0–65535` (all ports), TCP only — override per-action+ via `aws_protocol`, `aws_from_port`, `aws_to_port`.+- Cross-account: pass `aws_assume_role_arn` and the actions service will+ STS:AssumeRole into the target account before authorizing.+- `ALLOW_IP` reverses the same rule via `RevokeSecurityGroupIngress`.++See [`services/actions/app/clients/aws_security_groups.py`](https://github.com/beenuar/AiSOC/tree/main/services/actions/app/clients/aws_security_groups.py)+for the full client.++## Troubleshooting++**`AccessDenied` on `GetFindings`** — the IAM user / role is missing+`securityhub:GetFindings`. Reattach the policy from step 2.++**`ResourceNotFoundException`** — Security Hub is not enabled in the+configured region. Enable it in the AWS console.++**`boto3 is required` at runtime** — boto3 is bundled with the+`services/connectors` Docker image. If you are running the service+outside Docker, install it: `pip install boto3`.++**`BLOCK_IP` returns success but the IP keeps connecting** — the playbook+step did not supply an `aws_security_group_id`, or the host is not+attached to that security group. Verify both.++## Related++- [AWS GuardDuty](/docs/connectors/aws-guardduty) — direct GuardDuty+ ingestion (skips Security Hub aggregation).+- [AWS CloudTrail](/docs/connectors/aws-cloudtrail) — high-signal API+ events for AWS-native detections.+- [Wiz](/docs/connectors/wiz) — multi-cloud CNAPP alternative.diff --git a/apps/docs/docs/connectors/aws-vpc-flow.md b/apps/docs/docs/connectors/aws-vpc-flow.mdnew file mode 100644index 000000000..1a7517f54--- /dev/null+++ b/apps/docs/docs/connectors/aws-vpc-flow.md@@ -0,0 +1,252 @@+---+sidebar_position: 23+title: AWS VPC Flow Logs+description: Native AWS VPC Flow Logs ingestion via CloudWatch Logs with a default REJECT-only filter pattern — surfaces blocked network flows without paying to ingest the steady-state ACCEPT firehose.+---++# AWS VPC Flow Logs++The AWS VPC Flow Logs connector pulls **network-flow records** from a+configured CloudWatch Logs log group via the+`logs:FilterLogEvents` API. It defaults to surfacing only **rejected+flows** (the default filter pattern is `?REJECT`) so the alert+pipeline gets the actionable port-scan / blocked-egress signal+without drowning in steady-state ACCEPT noise.++That default is deliberate. Even a tiny VPC publishes **hundreds of+thousands of flow records per minute**, the vast majority of which+are uninteresting ACCEPTed traffic on long-lived TCP sessions. The+bundled detection content in `detections/network/` and+`detections/cloud/` only fires on rejected or unusual flows, port+scans, or specific destinations — so the REJECT-only default+matches what the rules actually consume.++Use this connector together with+[AWS GuardDuty](/docs/connectors/aws-guardduty) (which uses VPC+flow logs as one of its inputs) and+[AWS CloudTrail](/docs/connectors/aws-cloudtrail) (management-plane+events) for full AWS coverage of the network and identity planes.++## What you get++| Source | CloudWatch API | Notes |+|---|---|---|+| VPC flow records | `FilterLogEvents` | One server-side-filtered call per poll, paginated |++Events are normalized with `source: aws_vpc_flow` and+`category: network`. The parsed flow fields (`src_ip`, `dst_ip`,+`src_port`, `dst_port`, `protocol`, `action`, `aws_account_id`,+`cloud_resource` = the ENI ID) are surfaced as top-level alert+fields so detections can match without unwrapping `raw_event`. The+original message body is preserved on `raw_event.message` for v5 /+JSON layouts where the parser cannot do better than passthrough.++## Why CloudWatch Logs and not S3?++AWS lets you publish flow logs to either CloudWatch Logs or S3.++- The **CloudWatch Logs** path is the only one with a real-time,+ queryable API surface — `filter_log_events` supports a CloudWatch+ Logs filter pattern, returns events as JSON envelopes, and tracks+ a cursor we can resume from.+- The **S3** path is cheaper at petabyte scale but requires a+ separate parse / dedupe layer per object and has 5–10 minute+ publish latency.++For an alert-pipeline connector AiSOC wants the lower-latency+CloudWatch path. If you need to bulk-analyse historical flow logs+that already live in S3, run an offline batch job rather than+trying to backfill through this connector.++## Capabilities++| Capability | Backed by | Notes |+|---|---|---|+| `PULL_ALERTS` | `logs:FilterLogEvents` | Records flow into the alert pipeline once normalised |+| `PULL_LOGS` | `logs:FilterLogEvents` | True to the source — these are passive logs |++VPC Flow Logs are read-only. To **block** an offending source IP+that surfaces in a rejected-flow record, route the alert through a+playbook that uses the+[AWS Security Hub](/docs/connectors/aws-security-hub) connector's+`BLOCK_IP` capability (which mutates the security group inline) or+your own NACL-management connector.++## Prerequisites++- A **VPC Flow Log** configured to publish to **CloudWatch Logs**.+ Create it under **VPC → Your VPCs → (vpc) → Flow logs → Create+ flow log → Send to CloudWatch Logs**. Note the log group name —+ you'll need it below.+- IAM permissions:+ - `logs:FilterLogEvents` on the target log group+ - `logs:DescribeLogGroups` on the target log group (used by `Test connection`)+- One of:+ - **Static access key** (`AccessKeyId` + `SecretAccessKey`) for a+ dedicated IAM user, **or**+ - **No credentials at all** — AiSOC falls back to the **runtime IAM+ role / instance profile** of the host running the `connectors`+ service.++The runtime-IAM-role path is strongly preferred for production+deployments.++## Setup walkthrough++### 1. Enable VPC Flow Logs (one-time per VPC)++In the AWS console:++1. **VPC → Your VPCs → (target VPC) → Flow logs → Create flow log**.+2. **Filter**: choose `All` if you want to be able to switch this+ connector to pull ACCEPTs later, or `Reject` to match the+ connector's default filter pattern at the source.+3. **Maximum aggregation interval**: 1 minute (recommended for+ detection latency).+4. **Destination**: `Send to CloudWatch Logs`.+5. **Destination log group**: pick or create one (e.g.+ `/aws/vpc/flowlogs`).+6. **Log format**: leave as the default `AWS default format` for the+ v2 14-field layout, or pick `Custom format` to define a v5+ layout.++### 2. (Optional) Create a least-privilege IAM user++If you cannot use an instance role, create a dedicated IAM user with+**only** the policy below, and capture an access key for it:++```json+{+ "Version": "2012-10-17",+ "Statement": [+ {+ "Sid": "AiSOCVPCFlowLogsRead",+ "Effect": "Allow",+ "Action": [+ "logs:FilterLogEvents",+ "logs:DescribeLogGroups"+ ],+ "Resource": "arn:aws:logs:*:*:log-group:/aws/vpc/flowlogs:*"+ }+ ]+}+```++Tighten the resource ARN to the specific log group ARN from step 1.++### 3. Add the connector in AiSOC++1. **Connectors → Add connector → AWS VPC Flow Logs**.+2. Set **AWS Region** (e.g. `us-east-1`).+3. Set **CloudWatch Logs log group** to the log group from step 1+ (e.g. `/aws/vpc/flowlogs`).+4. Leave **CloudWatch Logs filter pattern** as the default+ `?REJECT` (recommended). See+ [Tuning the filter pattern](#tuning-the-filter-pattern) below.+5. Leave **Flow log version** as `v2` unless you configured a custom+ v5 layout in step 1.+6. Leave **Access Key ID** and **Secret Access Key** **blank** to+ use the runtime IAM role. Otherwise paste the static credentials+ from step 2.+7. **Test connection** — AiSOC calls `DescribeLogGroups` to verify+ auth and that the log group exists.+8. **Save**.++## Polling details++- Default interval: **300 seconds**.+- Each poll calls `FilterLogEvents` with `startTime = now - 300s`+ and `endTime = now`, applying the configured filter pattern+ server-side.+- Pagination: 1,000 events per page (the API max), capped at+ **5,000 events per poll** to bound memory and prevent a single+ misconfigured filter from wedging the scheduler.+- If the log group does not exist or auth fails, the poll logs the+ error and returns an empty batch instead of raising — the+ scheduler stays healthy and the next poll retries.++## Severity mapping++VPC flow records do not carry intrinsic severity, so AiSOC labels+each record by action / log status:++| Condition | Examples | AiSOC severity |+|---|---|---|+| `action = REJECT` | A blocked flow — the loud signal we publish this connector for | `medium` |+| `action = ACCEPT` | An allowed flow — only ingested if the operator overrode the default filter | `low` |+| `log_status` ∈ `{NODATA, SKIPDATA}` | Collection gap reported by AWS — useful for the pipeline-health channel | `info` |+| Anything else | Unparsed / v5-passthrough records | `low` |++## Tuning the filter pattern++The `filter_pattern` field is a CloudWatch Logs filter expression+applied server-side, before AiSOC pays to fetch the record. Three+common modes:++- **`?REJECT`** (default) — surfaces only blocked flows. The right+ default for ~95% of operators.+- **Empty string** — disables the server-side filter and ingests+ every flow record. **High volume warning** — only use this in lab+ / staging accounts or when you have downstream rate-limiting in+ place. A single production VPC on `""` can generate tens of+ millions of records per day.+- **Custom expression** — anything CloudWatch Logs filter syntax+ accepts. Examples:+ - `?REJECT ?ERROR` — reject + downstream service errors+ - `[version, account, eni, src!="10.*", dst, ...]` — fixed-column+ pattern matching against parsed fields (v2 only)++See the+[CloudWatch Logs filter syntax docs](https://docs.aws.amazon.com/AmazonCloudWatch/latest/logs/FilterAndPatternSyntax.html)+for the full grammar.++## Flow log format support++| Format | Parsed natively | Notes |+|---|---|---|+| **v2 (default)** | Yes — 14 space-separated fields | All top-level fields populated. Parser falls through silently on the optional v2 header line. |+| **v5 (custom layout, JSON)** | Yes via JSON parse | Top-level fields populated when the JSON keys match the v2 names; otherwise everything passes through on `raw_event`. |+| **v5 (custom layout, fixed columns)** | No | The full message is preserved on `raw_event.message`. Detection rules can still pattern-match on the raw line. |++The connector inspects `raw_event.record_format` so playbooks /+detections can branch on whether the record was parsed cleanly.++## Troubleshooting++**`Test connection` returns "log group … not found"** — the IAM+identity can `DescribeLogGroups` but the requested group either+does not exist or lives in a different region. Check the AWS+console under **CloudWatch → Log groups** in the region configured+on the connector.++**`AccessDenied` on `FilterLogEvents`** — the IAM user / role is+missing `logs:FilterLogEvents` on the specific log-group ARN.+Reattach the policy from step 2 with the correct ARN.++**Volume too high even with `?REJECT`** — your VPC is genuinely+seeing a lot of denied traffic (often a sign of misconfigured+security groups or active scanning). Tighten the filter pattern,+add a destination-IP exclusion, or downgrade the polling interval+to spread the load. The connector caps at 5,000 records per poll+regardless.++**Records arrive several minutes late** — CloudWatch Logs is+**eventually consistent**, and VPC Flow Logs are aggregated for up+to 1–10 minutes (depending on the **Maximum aggregation interval**+setting on the flow log itself) before publishing. Set the+aggregation to 1 minute for the lowest detection latency.++**`boto3 is required` at runtime** — boto3 is bundled with the+`services/connectors` Docker image. If you are running the service+outside Docker, install it: `pip install boto3`.++## Related++- [AWS GuardDuty](/docs/connectors/aws-guardduty) — ML-based+ threat detection layered on top of these flow logs (plus+ CloudTrail and DNS).+- [AWS CloudTrail](/docs/connectors/aws-cloudtrail) — management-plane+ audit events to cross-reference against suspicious flow records.+- [AWS Security Hub](/docs/connectors/aws-security-hub) —+ multi-source finding aggregator with `BLOCK_IP` / `ALLOW_IP`+ containment.diff --git a/apps/docs/docs/connectors/kubernetes-audit.md b/apps/docs/docs/connectors/kubernetes-audit.mdnew file mode 100644index 000000000..e94446e84--- /dev/null+++ b/apps/docs/docs/connectors/kubernetes-audit.md@@ -0,0 +1,466 @@+---+sidebar_position: 24+title: Kubernetes Audit Logs+description: Dual-mode Kubernetes apiserver audit log connector — webhook (apiserver pushes to AiSOC's inbox) or file_tail (AiSOC reads a local audit log forward from a byte cursor). Powers cluster-level detections for kubectl exec, RBAC escalation, ServiceAccount token theft, and impersonation.+---++# Kubernetes Audit Logs++The Kubernetes Audit Logs connector ingests **apiserver audit events**+— the canonical record of every call hitting the Kubernetes control+plane. These are the events that power detection content under+`detections/cloud/kubernetes-*.yaml` (kubectl exec into a pod,+ServiceAccount token theft, RBAC privilege escalation,+`impersonate` abuse, and similar high-signal cluster-level+behaviours).++Unlike the cloud-platform connectors (AWS GuardDuty, GCP SCC,+Azure Defender) which only see what the cloud provider's own+security service surfaces, this connector reads the audit log+**directly** from the apiserver — so the detection content can+match on raw verbs, raw resources, raw users, and raw response+codes instead of a vendor-normalised abstraction.++## Two delivery modes++Kubernetes audit logging supports two output channels, and AiSOC+exposes both as a single connector with a `mode` switch:++| Mode | When to pick it | How AiSOC consumes it |+|---|---|---|+| **`webhook`** | Managed clusters (EKS / GKE / AKS) where you cannot mount the apiserver audit log into a sidecar | The apiserver POSTs each `EventList` batch to AiSOC's tenant-scoped endpoint `POST /v1/ingest/k8s-audit/<tenant_id>` and authenticates with the `X-AiSOC-K8s-Token` shared-secret header. The Go ingest service normalises every item in the batch directly. A legacy fallback via the AiSOC inbox at `/v1/inbox/<token>` is also supported for clusters that cannot set custom headers in audit-webhook kubeconfig. |+| **`file_tail`** | Self-hosted clusters where the audit log path is mountable | The connector pod tails the audit log file forward from a byte cursor on its configured poll interval. Cursor survives pod restarts; file rotation / truncation resets cleanly. |++You only configure one mode per connector instance. To cover+multiple clusters, add one instance per cluster.++## What you get++Every audit event is normalised to a stable shape regardless of+mode:++| Field | Source | Notes |+|---|---|---|+| `cluster_name` | Operator-supplied | Stamped on every event — filter detections by cluster |+| `k8s_user` / `k8s_user_groups` | `user.username`, `user.groups` | Who made the request |+| `k8s_impersonated_user` | `impersonatedUser.username` | Non-null = the request used `impersonate` |+| `k8s_verb` | `verb` | `get` / `list` / `watch` / `create` / `update` / `patch` / `delete` / `deletecollection` / `connect` / `impersonate` |+| `k8s_resource` | `objectRef.resource` | `pods`, `secrets`, `clusterrolebindings`, … |+| `k8s_subresource` | `objectRef.subresource` | `exec`, `attach`, `portforward`, `proxy`, `log`, `token` |+| `k8s_namespace` / `k8s_object_name` | `objectRef.namespace` / `objectRef.name` | Target of the request |+| `k8s_response_code` | `responseStatus.code` | 200 / 403 / 404 / 409 / 500 / … |+| `src_ip` / `source_ips` | `sourceIPs[0]`, `sourceIPs` | First IP surfaces as `src_ip` so detections can match a single column |+| `k8s_user_agent` | `userAgent` | `kubectl/v1.29.0`, controller-manager, kubelet, … |+| `audit_id` | `auditID` | Unique per request — use for deduplication |+| `raw_event` | The full `audit.k8s.io/v1` Event | Always preserved so detection content can match on any field |++## Capabilities++| Capability | Notes |+|---|---|+| `PULL_AUDIT` | Primary capability — audit events flow into the audit-event pipeline |+| `PULL_ALERTS` | High-severity events surface as alerts |++Kubernetes audit logs are passive — there is no `BLOCK` /+`ISOLATE` capability here. To **respond** to a suspicious audit+event (e.g. revoke a ServiceAccount, delete a pod) route the+alert through a playbook that uses a Kubernetes execution+connector or your own `kubectl` runner.++## Severity heuristic++The connector buckets events into AiSOC's four-tier severity+ladder using verb + resource + response code:++| Condition | AiSOC severity |+|---|---|+| `verb=impersonate` (any resource) | `high` |+| `verb=create/update/patch/delete` on `clusterrolebindings` or `rolebindings` | `high` |+| `verb=create/update/patch/delete` on `secrets`, `serviceaccounts`, `clusterroles`, `roles`, `certificatesigningrequests` | `high` |+| `subresource ∈ {exec, attach, portforward, proxy}` on `pods` | `high` |+| `verb=create/update/patch/delete` on `deployments`, `daemonsets`, `statefulsets`, `pods`, `jobs`, `cronjobs`, `replicasets` | `medium` |+| `responseStatus.code >= 400` (denied / failed requests) | `medium` |+| `verb=get/list/watch` on sensitive resources (`secrets`, RBAC, etc.) | `low` |+| Everything else (steady-state read traffic) | `info` |++The default poll-bucket cap is high enough that even a busy+cluster's `info` events do not crowd out the `high` band — but+in practice you do **not** want to surface every `get pods` in+the UI. Detection rules in `detections/cloud/kubernetes-*.yaml`+filter on `severity ∈ {high, medium}` only.++## Prerequisites++- A **Kubernetes cluster** with apiserver audit logging+ configured.+- For **webhook mode**:+ - Cluster admin access to update the apiserver's+ `--audit-webhook-config-file` flag (or push an `AuditSink`+ resource).+ - Network reachability from the apiserver to AiSOC's ingest+ endpoint.+ - The AiSOC ingest service must have `K8S_AUDIT_SHARED_SECRET`+ set in its environment. The webhook is **disabled by default**+ and the route returns `503 Service Unavailable` until an+ operator turns it on. Pick a long random value+ (`openssl rand -base64 32`) and store it in your secret manager.+ - The tenant ID you want to attribute events to. The route is+ `POST /v1/ingest/k8s-audit/<tenant_id>` so the tenant boundary+ is set at apiserver-config time.+ - **(Legacy / fallback)** For control planes that cannot set+ custom headers in audit-webhook kubeconfig, a bound inbox token+ created with the `k8s-audit` template is also supported.+- For **file_tail mode**:+ - The apiserver audit log path mounted **read-only** into the+ AiSOC connector pod.+ - A writeable directory next to that path for the byte cursor+ file (defaults to `<audit_log_path>.aisoc-cursor`).++## Setup — webhook mode (recommended for managed clusters)++The recommended webhook path is the dedicated tenant-scoped+endpoint:++```+POST https://<your-aisoc-host>/v1/ingest/k8s-audit/<tenant_id>+Content-Type: application/json+X-AiSOC-K8s-Token: <shared-secret>+```++The endpoint accepts a Kubernetes+[`audit.k8s.io/v1` `EventList`](https://kubernetes.io/docs/reference/config-api/apiserver-audit.v1/#audit-k8s-io-v1-EventList)+JSON document — the exact shape the apiserver pushes when you+configure an `--audit-webhook-config-file`. Every item in the+batch is normalised to OCSF `API Activity (6003)`, severity+classified using the heuristic above, and forwarded to the+detection pipeline.++The route is **disabled by default** so a stock AiSOC install+will return `503 Service Unavailable` until you turn it on.+Authentication is via a single installation-wide shared secret+(`K8S_AUDIT_SHARED_SECRET`), compared with constant-time+equality so a partial-prefix attacker cannot brute-force it+byte by byte.++### 1. Enable the webhook on the AiSOC ingest service++Set both env vars on the `services/ingest` deployment, then+restart:++```bash+# Pick a long random value once and store it in your secret manager.+export K8S_AUDIT_SHARED_SECRET="$(openssl rand -base64 32)"++# Optional — defaults to 16 MiB. Bump if your audit-batch-max-size+# is unusually large.+export K8S_AUDIT_MAX_BODY_BYTES=16777216+```++If `K8S_AUDIT_SHARED_SECRET` is unset or empty, the webhook+remains off. This is intentional — accidentally leaving an+unauthenticated audit-event sink open to the internet would be+a coverage hole, not an integration win.++### 2. Wire up the apiserver++Write an `audit-webhook-config-file` kubeconfig that targets+the AiSOC route and presents the shared secret as a header.+Apiserver kubeconfigs do not natively support custom request+headers, so use the cluster's `tls-server-name` /+`server` fields and either an apiserver authn-proxy or a+sidecar to inject the header. The most common pattern is a+small forwarder (e.g. nginx) that the apiserver hits over+loopback, which then adds the header before forwarding to+AiSOC. A reference apiserver kubeconfig that talks to such a+forwarder:++```yaml+apiVersion: v1+kind: Config+clusters:+ - name: aisoc-audit+ cluster:+ server: http://127.0.0.1:8080/forward+contexts:+ - name: aisoc-audit+ context:+ cluster: aisoc-audit+current-context: aisoc-audit+```++And the matching forwarder snippet (nginx):++```nginx+server {+ listen 127.0.0.1:8080;+ location /forward {+ proxy_set_header X-AiSOC-K8s-Token "<shared-secret>";+ proxy_set_header Content-Type application/json;+ proxy_pass https://<your-aisoc-host>/v1/ingest/k8s-audit/<tenant_id>;+ }+}+```++For **self-managed kubeadm**, add to your apiserver static-pod+manifest:++```yaml+spec:+ containers:+ - command:+ - kube-apiserver+ - --audit-policy-file=/etc/kubernetes/audit-policy.yaml+ - --audit-webhook-config-file=/etc/kubernetes/audit-webhook.yaml+ - --audit-webhook-batch-max-size=400+ - --audit-webhook-batch-max-wait=30s+```++For **EKS** specifically, control-plane logging publishes audit+to CloudWatch — pair this connector with the AiSOC AWS+CloudTrail / VPC Flow Logs connectors and run a thin Lambda+that subscribes to the audit log group and POSTs each batch+to the AiSOC endpoint with the header set.++Use the bundled+[recommended audit policy](https://kubernetes.io/docs/tasks/debug/debug-cluster/audit/#audit-policy)+as a starting point — at minimum log `Metadata` for RBAC,+secrets, and pod subresources.++### 3. Add the connector in AiSOC++1. **Connectors → Add connector → Kubernetes Audit Logs**.+2. **Delivery mode**: `Webhook`.+3. **Cluster name**: a human-readable cluster identifier+ (e.g. `prod-eks-us-east-1`). This is stamped on every event+ so detections can filter by cluster.+4. Leave **Inbox token** blank when using the dedicated route.+5. **Test connection** — AiSOC confirms the dedicated route is+ reachable and the shared secret is configured on the ingest+ service.+6. **Save**.++Audit events start flowing within a few seconds of the apiserver+picking up the webhook config (kube-apiserver does **not**+hot-reload audit config on managed clusters — a control-plane+restart may be required, which managed providers handle for+you).++### Setup — webhook mode (legacy inbox-token path)++If your control plane will not let you inject a custom header,+fall back to the AiSOC inbox path. Each token is bound to a+normalisation template at creation time, so the apiserver does+not need to know anything about AiSOC's internal schema — it+just POSTs raw audit events to the bound URL.++1. **Inbox → Tokens → Create token**.+2. **Template**: `k8s-audit`.+3. **Label**: a human-readable name (e.g. `prod-eks-legacy`).+4. Copy the token.++The endpoint to give the apiserver is:++```+POST https://<your-aisoc-host>/v1/inbox/<token>+Content-Type: application/json+```++Then in the connector configuration paste the token into the+**Inbox token (legacy path)** field. AiSOC routes events from+this path through the same `k8s-audit` normalisation template+as the dedicated route, so detections behave identically.++## Setup — file_tail mode (self-hosted clusters)++### 1. Configure the apiserver to write to a file++Add to your apiserver static-pod manifest:++```yaml+spec:+ containers:+ - command:+ - kube-apiserver+ - --audit-policy-file=/etc/kubernetes/audit-policy.yaml+ - --audit-log-path=/var/log/kubernetes/audit/audit.log+ - --audit-log-maxage=30+ - --audit-log-maxbackup=10+ - --audit-log-maxsize=100+ volumeMounts:+ - name: audit-log+ mountPath: /var/log/kubernetes/audit+ volumes:+ - name: audit-log+ hostPath:+ path: /var/log/kubernetes/audit+ type: DirectoryOrCreate+```++### 2. Mount the audit log into the AiSOC connector pod++The connector reads the audit log via standard POSIX file APIs —+mount it read-only into `services/connectors` at a stable path:++```yaml+spec:+ containers:+ - name: connectors+ volumeMounts:+ - name: k8s-audit-log+ mountPath: /var/log/kubernetes/audit+ readOnly: true+ - name: k8s-audit-cursor+ mountPath: /var/lib/aisoc/k8s-audit+ volumes:+ - name: k8s-audit-log+ hostPath:+ path: /var/log/kubernetes/audit+ type: Directory+ - name: k8s-audit-cursor+ emptyDir: {}+```++(In production, replace `emptyDir` with a PVC so the cursor+survives pod restarts.)++### 3. Add the connector in AiSOC++1. **Connectors → Add connector → Kubernetes Audit Logs**.+2. **Delivery mode**: `File tail`.+3. **Cluster name**: a human-readable cluster identifier.+4. **Audit log path**: `/var/log/kubernetes/audit/audit.log`+ (default).+5. **Cursor file path**: `/var/lib/aisoc/k8s-audit/audit.cursor`+ if you mounted a dedicated cursor volume. Defaults to+ `<audit_log_path>.aisoc-cursor` if blank.+6. **Test connection** — AiSOC confirms the audit log exists+ and is readable.+7. **Save**.++## Polling details++- Default poll interval: **300 seconds** (overrideable per+ instance).+- **Webhook mode**: `fetch_alerts` returns an empty list every+ poll — audit events arrive at the inbox in real time and are+ routed through the normaliser independently. The connector+ poll exists only to surface health / status in the UI.+- **File tail mode**: each poll reads the audit log forward+ from the saved byte cursor up to a hard cap of **8 MiB per+ poll** to bound memory. The cursor is written atomically after+ each successful read.+- **Rotation handling**: if the file size shrinks between polls+ (logrotate truncated it, or the apiserver opened a new+ segment) the cursor resets to 0 — AiSOC starts over from the+ top of the current segment.+- **Partial-line handling**: a final line without a trailing+ `\n` is treated as in-flight and left for the next poll, so+ the cursor never advances past an incomplete JSON record.++## Recommended audit policy++The connector itself is policy-agnostic — feed it whatever you+configure on the apiserver — but for the bundled detection+content you want **at least** the following stages and+resources logged at `Metadata` level or above:++```yaml+apiVersion: audit.k8s.io/v1+kind: Policy+rules:+ # Always log RBAC mutations + bindings+ - level: RequestResponse+ resources:+ - group: rbac.authorization.k8s.io+ resources: ["clusterroles", "clusterrolebindings", "roles", "rolebindings"]+ # Always log pod exec/attach/portforward/proxy+ - level: Request+ resources:+ - group: ""+ resources: ["pods/exec", "pods/attach", "pods/portforward", "pods/proxy"]+ # Always log secret + serviceaccount activity+ - level: Metadata+ resources:+ - group: ""+ resources: ["secrets", "serviceaccounts"]+ # Always log token creation+ - level: Metadata+ resources:+ - group: ""+ resources: ["serviceaccounts/token"]+ # Catch-all — request-level, not response-level+ - level: Metadata+```++A full reference policy lives in the+[Kubernetes upstream docs](https://kubernetes.io/docs/tasks/debug/debug-cluster/audit/#audit-policy).++## Troubleshooting++**Apiserver logs `failed to send audit events to webhook: 503`** —+the AiSOC ingest service is up, but `K8S_AUDIT_SHARED_SECRET`+is unset. The webhook stays disabled until an operator turns+it on. Set the env var on `services/ingest`, restart, retry.++**Apiserver logs `failed to send audit events to webhook: 401`** —+the shared secret on the apiserver side does not match the one+on AiSOC. Check the value the forwarder is injecting into the+`X-AiSOC-K8s-Token` header. Note that AiSOC compares with+constant-time equality, so a partial-prefix match also fails+(this is intentional).++**Apiserver logs `failed to send audit events to webhook: 413`** —+either the body exceeded `K8S_AUDIT_MAX_BODY_BYTES` (default 16+MiB) or the batch exceeded the ingest `MaxBatchSize` cap. Lower+the apiserver's `--audit-webhook-batch-max-size` or raise the+AiSOC limit.++**`Test connection` returns `inbox_token is required in webhook+mode`** — you picked **Webhook** with the **legacy** path but+did not paste a token. Either switch to the dedicated route+(leave the token field blank) or create a token bound to the+`k8s-audit` template under **Inbox → Tokens**.++**`Test connection` returns `audit log path … not found`** —+the connector pod cannot see the file. Check your volume+mount (`kubectl exec` into the pod and `ls -l` the path) and+that the apiserver is actually writing to the configured path.++**Webhook mode is configured but no events arrive** — the+apiserver may not have hot-reloaded the audit config. Restart+the apiserver (or, for managed clusters, wait for the control+plane to roll). You can also smoke-test the dedicated route end+to end with `curl`:++```bash+curl -X POST https://<your-aisoc-host>/v1/ingest/k8s-audit/<tenant_id> \+ -H "Content-Type: application/json" \+ -H "X-AiSOC-K8s-Token: <shared-secret>" \+ -d '{"kind":"EventList","apiVersion":"audit.k8s.io/v1","items":[]}'+```++A `200 OK` with `{"accepted":0,"rejected":0,...}` confirms the+endpoint is reachable and authenticated.++**File tail mode keeps reading from the top** — your cursor+file is not persistent. Mount a real volume (PVC or hostPath)+for the cursor directory instead of `emptyDir`.++**Severity is too noisy / too quiet** — adjust the audit policy+upstream, not the connector. AiSOC's severity heuristic operates+on what the apiserver actually sends. If you only log+`Metadata`-level requests for RBAC, that's still enough for the+detection content — the verbs and resources are present.++## Related++- [Universal capture / inbox](/docs/connectors/universal-capture) —+ the underlying webhook-receiver infrastructure that+ `webhook` mode reuses.+- [Wiz](/docs/connectors/wiz),+ [Lacework](/docs/connectors/lacework),+ [Prisma Cloud](/docs/connectors/prisma-cloud),+ [Orca](/docs/connectors/orca) — CNAPP connectors that can see+ Kubernetes posture and runtime findings from the cloud side.+ Pair them with this connector for both posture (CNAPP) and+ raw activity (apiserver audit).diff --git a/apps/docs/docs/connectors/lacework.md b/apps/docs/docs/connectors/lacework.mdnew file mode 100644index 000000000..4710e8d1f--- /dev/null+++ b/apps/docs/docs/connectors/lacework.md@@ -0,0 +1,129 @@+---+sidebar_position: 18+title: Lacework+description: Lacework cloud security platform alerts and compliance findings into AiSOC via the Lacework v2 API.+---++# Lacework++The Lacework connector pulls **alerts** (formerly "events") from a+Lacework tenant into AiSOC. One connector instance covers every Lacework+surface — workload, container, cloud configuration, and identity — because+the Lacework v2 `/Alerts` API is unified across all of them.++## What you get++| Source | Lacework v2 endpoint | Notes |+|---|---|---|+| Alerts | `GET /api/v2/Alerts` | All severities, last poll window |++Events are normalized with `source: lacework` and the original Lacework+alert envelope is preserved on `raw_event` so playbooks can target+specific alert categories (e.g. `Compliance`, `CloudActivity`).++## Prerequisites++- A **Lacework tenant** with an account subdomain (e.g. `yourcorp` for+ `https://yourcorp.lacework.net`).+- A Lacework **API access key**:+ - `keyId` — the access-key ID+ - `secret` — the access-key secret+- (Optional) A **subaccount** name if your tenant runs the multi-account+ model and you want to scope ingestion to a single subaccount.++API keys are created in the Lacework console under **Settings → API Keys+→ Create New**. Copy the key and secret immediately — Lacework only shows+the secret once.++## Setup walkthrough++### 1. Create the API key++1. In the Lacework console, **Settings → API Keys → Create New**.+2. Name the key `aisoc-prod` (or similar) and submit.+3. Save the **Key ID** and **Secret** to a password manager.++### 2. Add the connector in AiSOC++1. **Connectors → Add connector → Lacework**.+2. **Account subdomain** — first label of your console URL (e.g.+ `yourcorp` for `https://yourcorp.lacework.net`).+3. **Subaccount (optional)** — leave blank unless you want to scope the+ poll to a Lacework subaccount.+4. **Access Key ID** and **Secret Key** — paste from step 1.+5. **Test connection** — AiSOC exchanges the key/secret for a 1-hour+ bearer token via `POST /api/v2/access/tokens` and confirms a 200 on a+ 1-row `/Alerts` query.+6. **Save**.++## Polling details++- Default interval: **300 seconds**.+- Each poll re-authenticates against `POST /api/v2/access/tokens` if the+ cached bearer is expired (Lacework tokens are valid for ~1 hour).+- The poll requests **the last `interval × 2` seconds of alerts** (default+ 10 minutes) using `startTime` / `endTime` query parameters in the+ `/Alerts` endpoint.++## Severity mapping++Lacework alerts use a numeric severity (1 = critical, 5 = info). AiSOC+maps these into the canonical 4-tier ladder:++| Lacework severity | AiSOC severity |+|---|---|+| `1` — Critical | `high` |+| `2` — High | `high` |+| `3` — Medium | `medium` |+| `4` — Low | `low` |+| `5` — Info | `info` |++The original numeric severity is preserved under `raw_event.severity`.++## Subaccount scoping++If you operate multiple Lacework subaccounts (typical for MSSPs and+multi-business-unit deployments), create **one AiSOC connector instance+per subaccount** rather than rotating the same instance. This keeps+per-tenant audit logs clean and lets you set different polling cadences+per subaccount.++When the **Subaccount** field is set, the connector adds the+`Account-Name` header to every API call and the bearer token is scoped+to that subaccount.++## Live actions++The Lacework connector is **read-only** in v7.1.0. Containment for cloud+findings flows through the [AWS Security Hub](/docs/connectors/aws-security-hub),+[Cloudflare](/docs/connectors/cloudflare), or+[GCP Cloud Audit](/docs/connectors/gcp-cloud-audit) connectors.++## Troubleshooting++**`could not authenticate to lacework`** — the keyId / secret pair is+wrong, or the account subdomain has a typo. Test the credentials directly:++```bash+curl -X POST "https://YOUR_ACCOUNT.lacework.net/api/v2/access/tokens" \+ -H "X-LW-UAKS: YOUR_SECRET" \+ -H "Content-Type: application/json" \+ -d '{"keyId":"YOUR_KEY_ID","expiryTime":3600}'+```++A 200 response with `{ "token": "..." }` confirms the credentials are+good — the issue is then in the AiSOC field values.++**`HTTP 403` on `/Alerts`** — the API key was created on the parent+account but you set a **Subaccount** value the key cannot reach. Either+clear the Subaccount field or generate a key from the subaccount itself.++**`events_added: 0` between polls** — the tenant generated no alerts in+the last 10 minutes. Lower-severity alerts can take up to 5 minutes to+appear in `/Alerts`; that is expected steady state for a quiet tenant.++## Related++- [Wiz](/docs/connectors/wiz) — alternative CNAPP path.+- [AWS Security Hub](/docs/connectors/aws-security-hub) — alternative+ cloud finding source if you want native AWS aggregation.diff --git a/apps/docs/docs/connectors/orca.md b/apps/docs/docs/connectors/orca.mdnew file mode 100644index 000000000..97e446a74--- /dev/null+++ b/apps/docs/docs/connectors/orca.md@@ -0,0 +1,150 @@+---+sidebar_position: 20+title: Orca Security+description: Orca Security CNAPP alerts across workload, container, cloud configuration, identity, and data risk surfaces into AiSOC via the unified /api/alerts API.+---++# Orca Security++The Orca Security connector pulls **open security alerts** from an Orca+tenant into AiSOC. One connector instance covers every Orca surface —+**workload**, **container**, **cloud configuration (CSPM)**, **identity+(CIEM)**, and **data risk (DSPM)** — because the `/api/alerts` REST+endpoint aggregates findings across all of them. There is no per-product+configuration to babysit.++## What you get++| Source | Orca endpoint | Notes |+|---|---|---|+| Alerts | `GET /api/alerts` | Open alerts only, last poll window |++Events are normalized with `source: orca` and the original Orca alert+envelope is preserved on `raw_event` so playbooks can target specific+finding categories (e.g. `IAM`, `Vulnerability`, `Misconfiguration`).++## Prerequisites++- An **Orca Security tenant** with an admin or auditor-class user.+- An Orca **API token** scoped to read alerts. Tokens are minted in the+ Orca console under **Settings → Users & Permissions → API Tokens →+ Create Token**.++API tokens are long-lived; copy the secret immediately — Orca only+shows it once.++## Setup walkthrough++### 1. Create the API token++1. In the Orca console, **Settings → Users & Permissions → API Tokens →+ Create Token**.+2. Name the token `aisoc-prod` (or similar) and set an expiry — match it+ to your secrets-rotation policy.+3. Assign the role **Auditor** (read-only) or higher. Auditor is+ sufficient for alert ingestion.+4. Copy the token value to a password manager.++### 2. Add the connector in AiSOC++1. **Connectors → Add connector → Orca Security**.+2. **API Token** — paste the token from step 1.+3. **API URL** — leave blank unless you're on a region-specific+ endpoint. The default `https://api.orcasecurity.io` works for the+ standard commercial cloud.+4. **Test connection** — AiSOC calls `GET /api/user/session` to confirm+ the token is valid and live.+5. **Save**.++## Polling details++- Default interval: **300 seconds**.+- Each poll requests alerts opened in the last `interval` seconds via+ `start_at_gte` (ISO-8601).+- Only alerts with `status = "open"` are pulled. Resolved / dismissed+ alerts are filtered out at the source.+- Result set is capped at 200 alerts per poll. If your tenant routinely+ emits more than that in 5 minutes, lower the polling interval rather+ than raising the cap — it keeps each request well within Orca's API+ timeout.++## Severity mapping++Orca uses a 5-tier severity ladder. AiSOC's canonical ladder is 4-tier:++| Orca severity | AiSOC severity |+|---|---|+| `hazardous` | `high` |+| `imminent_compromise` | `high` |+| `critical` | `high` |+| `high` | `high` |+| `medium` | `medium` |+| `low` | `low` |+| `informational` | `info` |++`hazardous` is Orca-internal terminology for "actively exploited" and is+unambiguously high-impact, so it collapses into `high`. The original+tier is preserved under `raw_event.state.severity` so playbooks that+need to distinguish `hazardous` vs `critical` vs `high` still can.++## Coverage breakdown++The unified `/api/alerts` endpoint includes findings from every Orca+module you license:++| Module | What you'll see in AiSOC |+|---|---|+| **Workload** | Vulnerable packages, malware, runtime drift, exposed secrets in workloads |+| **Container / Kubernetes** | Image vulnerabilities, runtime risks, K8s misconfig |+| **CSPM** | Misconfigured S3 buckets, public DBs, IAM drift, network exposure |+| **CIEM** | Over-privileged identities, unused permissions, role-chain risks |+| **DSPM** | Sensitive data exposure, data-flow risks, compliance breaches |++If a module isn't licensed on the tenant, no alerts of that type appear+— there is nothing to disable in AiSOC.++## Live actions++The Orca connector is **read-only** in v7.1.0. Containment for cloud+findings flows through the+[AWS Security Hub](/docs/connectors/aws-security-hub),+[AWS GuardDuty](/docs/connectors/aws-guardduty),+[Cloudflare](/docs/connectors/cloudflare), or+[GCP Cloud Audit](/docs/connectors/gcp-cloud-audit) connectors.++## Troubleshooting++**`orca auth failed: HTTP 401`** — the API token is wrong, expired, or+revoked. Test directly:++```bash+curl https://api.orcasecurity.io/api/user/session \+ -H "Authorization: Token YOUR_TOKEN"+```++A 200 response with a JSON session body confirms the token is good — the+issue is then in the AiSOC field value.++**`orca auth failed: HTTP 403`** — the token's role does not have+permission to read alerts. Reassign the token to **Auditor** or higher+in **Settings → Users & Permissions → API Tokens → Edit**.++**`events_added: 0` between polls** — the tenant generated no new+**open** alerts in the last 5 minutes. Resolved alerts are filtered out+at the source by the `status = "open"` filter; that is expected steady+state for a quiet tenant.++**Tenant on a region-specific endpoint** — set the **API URL** field to+the regional value (e.g. `https://api.eu.orcasecurity.io`). The console+URL is **not** the API URL.++## Related++- [Wiz](/docs/connectors/wiz) — alternative CNAPP path with broader+ cloud-graph context.+- [Prisma Cloud](/docs/connectors/prisma-cloud) — alternative CNAPP from+ Palo Alto Networks.+- [Lacework](/docs/connectors/lacework) — alternative CNAPP focused on+ workload + compliance.+- [AWS Security Hub](/docs/connectors/aws-security-hub) — native AWS+ finding aggregation for AWS-only deployments.diff --git a/apps/docs/docs/connectors/prisma-cloud.md b/apps/docs/docs/connectors/prisma-cloud.mdnew file mode 100644index 000000000..f3c7eca8b--- /dev/null+++ b/apps/docs/docs/connectors/prisma-cloud.md@@ -0,0 +1,161 @@+---+sidebar_position: 19+title: Prisma Cloud+description: Prisma Cloud (Palo Alto Networks) cloud security alerts across CSPM, CWPP, CIEM, and DSPM into AiSOC via the unified /alert/v1/alert API.+---++# Prisma Cloud++The Prisma Cloud connector pulls **open security alerts** from a Prisma+Cloud tenant into AiSOC. One connector instance covers every Prisma Cloud+surface — **CSPM**, **CWPP**, **CIEM**, and **DSPM** — because the+`/alert/v1/alert` REST endpoint aggregates findings across all of them.+There is no per-product configuration to babysit.++## What you get++| Source | Prisma Cloud endpoint | Notes |+|---|---|---|+| Alerts | `POST /alert/v1/alert` | All open alerts, last poll window, sorted newest first |++Events are normalized with `source: prisma_cloud` and the original+Prisma Cloud envelope is preserved on `raw_event` so playbooks can target+specific alert categories (e.g. policy type, finding subtype).++## Prerequisites++- A **Prisma Cloud tenant** with admin or System Admin access.+- A Prisma Cloud **access key pair**:+ - `accessKeyId` — the access-key ID (UUID-formatted).+ - `secretKey` — the matching secret.+- Your **region-specific API endpoint** (e.g. `https://api.prismacloud.io`,+ `https://api2.eu.prismacloud.io`, `https://api.gov.prismacloud.io`).+ Find it in **System → API Endpoints** in the Prisma Cloud console.++Access keys are created in the Prisma Cloud console under **Settings →+Access Control → Access Keys → Add New**. Copy the secret immediately —+Prisma Cloud only shows it once.++## Setup walkthrough++### 1. Create the access key++1. In the Prisma Cloud console, **Settings → Access Control → Access+ Keys → Add New**.+2. Name the key `aisoc-prod` (or similar) and pick an expiry — match it+ to your secrets-rotation policy.+3. Copy the **Access Key ID** and **Secret Key** to a password manager.+4. Confirm the **role** attached to the key has at least read access to+ the `Alerts` resource. The built-in `System Admin` and `Account Group+ Admin` roles work; for least-privilege, create a custom role with the+ `Alerts: View` permission only.++### 2. Add the connector in AiSOC++1. **Connectors → Add connector → Prisma Cloud**.+2. **API URL** — paste the region-specific value from+ **System → API Endpoints** (e.g. `https://api.prismacloud.io`).+3. **Access Key ID** and **Secret Key** — paste from step 1.+4. **Compute API URL** — leave blank. v7.1.0 only consumes the unified+ `/alert` endpoint, which already includes runtime findings collapsed+ in from Compute (Twistlock).+5. **Test connection** — AiSOC exchanges the access keys for a+ short-lived JWT via `POST /login` and confirms a successful auth.+6. **Save**.++## Polling details++- Default interval: **300 seconds**.+- Each poll calls `POST /login` to mint a fresh JWT. Prisma Cloud tokens+ have a sliding TTL and re-auth is cheap; doing it every poll avoids+ cache-invalidation bugs around expiry windows.+- The poll requests **alerts in the last `interval` seconds** with+ `timeRange.type = "absolute"` and a `startTime`/`endTime` pair in+ epoch milliseconds.+- Only alerts with `status = "open"` are pulled. Resolved /+ snoozed / dismissed alerts are filtered out at the source.+- Result set is capped at 200 alerts per poll. If your tenant routinely+ emits more than that in 5 minutes, lower the polling interval rather+ than raising the cap — it keeps each request well within Prisma+ Cloud's API timeout.++## Severity mapping++Prisma Cloud uses a 4-tier severity ladder. AiSOC maps directly into the+canonical 4-tier set:++| Prisma Cloud severity | AiSOC severity |+|---|---|+| `critical` | `high` |+| `high` | `high` |+| `medium` | `medium` |+| `low` | `low` |+| `informational` | `info` |++`critical` collapses into `high` because AiSOC does not expose a+separate critical band. The original tier is preserved under+`raw_event.policy.severity` so playbooks that need to distinguish+`critical` vs `high` still can.++## Coverage breakdown++The unified `/alert` endpoint includes findings from every Prisma Cloud+module you license:++| Module | What you'll see in AiSOC |+|---|---|+| **CSPM** (Cloud Security Posture) | Misconfigured S3 buckets, public DBs, IAM drift, network exposure |+| **CWPP** (Workload Protection) | Vulnerable images, runtime drift, host posture findings |+| **CIEM** (Identity & Entitlements) | Over-privileged identities, unused permissions, role-chain risks |+| **DSPM** (Data Security Posture) | Sensitive data exposure, classification findings, data-flow risks |++If a module isn't licensed on the tenant, no alerts of that type appear+— there is nothing to disable in AiSOC.++## Live actions++The Prisma Cloud connector is **read-only** in v7.1.0. Containment for+cloud findings flows through the+[AWS Security Hub](/docs/connectors/aws-security-hub),+[AWS GuardDuty](/docs/connectors/aws-guardduty),+[Cloudflare](/docs/connectors/cloudflare), or+[GCP Cloud Audit](/docs/connectors/gcp-cloud-audit) connectors.++## Troubleshooting++**`could not exchange access keys for prisma cloud JWT`** — the+`accessKeyId` / `secretKey` pair is wrong, the access key has expired,+or the API URL points to a different region than the tenant. Test+directly:++```bash+curl -X POST "https://api.prismacloud.io/login" \+ -H "Content-Type: application/json" \+ -d '{"username":"YOUR_ACCESS_KEY_ID","password":"YOUR_SECRET"}'+```++A 200 response with `{ "token": "..." }` confirms the credentials are+good — the issue is then in the AiSOC field values (most often, wrong+region URL).++**`HTTP 403` on `/alert/v1/alert`** — the role attached to the access+key lacks `Alerts: View`. Check **Settings → Access Control → Access+Keys → \<your key\> → Role** and confirm the role has the permission.++**`events_added: 0` between polls** — the tenant generated no new+**open** alerts in the last 5 minutes. Resolved / snoozed alerts are+filtered out at the source by the `alert.status = "open"` filter; that+is expected steady state for a quiet tenant.++**Tenant in EU / Gov region not returning data** — confirm the API URL+matches the region. EU tenants use `api2.eu.prismacloud.io`, Gov uses+`api.gov.prismacloud.io`. The console URL is **not** the API URL.++## Related++- [Wiz](/docs/connectors/wiz) — alternative CNAPP path with broader+ cloud-graph context.+- [Lacework](/docs/connectors/lacework) — alternative CNAPP focused on+ workload + compliance.+- [AWS Security Hub](/docs/connectors/aws-security-hub) — native AWS+ finding aggregation for AWS-only deployments.diff --git a/apps/docs/docs/connectors/wiz.md b/apps/docs/docs/connectors/wiz.mdnew file mode 100644index 000000000..44a9a4d10--- /dev/null+++ b/apps/docs/docs/connectors/wiz.md@@ -0,0 +1,110 @@+---+sidebar_position: 16+title: Wiz+description: Wiz cloud security findings (CSPM, CWPP, CIEM, container, code) into AiSOC via the Wiz GraphQL API.+---++# Wiz++The Wiz connector pulls **cloud security issues from the Wiz GraphQL API**+into AiSOC. One connector instance covers every Wiz product surface — CSPM,+CWPP, CIEM, container, and code findings — because Wiz exposes them all as+`Issue` objects on the same GraphQL graph.++## What you get++| Source | Wiz GraphQL field | Notes |+|---|---|---|+| Cloud security issues | `issues(first: 200, filterBy: { status: OPEN })` | All OPEN issues across CSPM/CWPP/CIEM/container/code |++Events are normalized with `source: wiz` and the original Wiz issue payload+is preserved on `raw_event` for downstream playbooks and the Investigation+Ledger.++## Prerequisites++- A **Wiz tenant** with a GraphQL API endpoint (e.g. `https://api.us20.app.wiz.io/graphql`).+- A **Wiz service account** with at least `read:issues` scope.+- The service-account **client ID** and **client secret**.++The Wiz auth endpoint defaults to `https://auth.app.wiz.io/oauth/token` and+only needs to be overridden for **gov-cloud tenants** (e.g.+`https://auth.gov.wiz.io/oauth/token`).++## Setup walkthrough++### 1. Create a Wiz service account++1. In the Wiz console, open **Settings → Service Accounts → Create Service+ Account**.+2. Grant **`read:issues`** as the minimum scope (add `read:vulnerabilities`+ and `read:cloud_resources` if you want richer enrichment downstream).+3. Save the **Client ID** and **Client Secret** — Wiz only shows the secret+ once.+4. Note the **API Endpoint URL** from **Settings → Tenant → API Endpoint**+ (region-specific, e.g. `https://api.us20.app.wiz.io/graphql`).++### 2. Add the connector in AiSOC++1. **Connectors → Add connector → Wiz**.+2. Enter **Client ID**, **Client Secret**, and **API Endpoint URL**.+3. Leave **Auth URL** blank unless you are on a gov-cloud tenant.+4. **Test connection** → AiSOC exchanges the credentials for an OAuth bearer+ token and runs a 1-row `issues` query against the GraphQL endpoint.+5. **Save**.++## Polling details++- Default interval: **300 seconds**.+- Each poll authenticates fresh against the OAuth `/token` endpoint.+- The GraphQL query requests up to **200 OPEN issues per poll** and+ unwraps `issues.nodes`.++## Severity mapping++Wiz ships a 5-tier severity ladder. AiSOC collapses it into the canonical+4-tier ladder used across the platform:++| Wiz severity | AiSOC severity |+|---|---|+| `CRITICAL` | `high` |+| `HIGH` | `high` |+| `MEDIUM` | `medium` |+| `LOW` | `low` |+| `INFORMATIONAL` | `info` |++The original Wiz severity is preserved verbatim under+`raw_event.severity` for playbooks that need the full 5-tier signal.++## Live actions++The Wiz connector is **read-only** in v7.1.0 — it pulls findings but+does not push back into Wiz. Containment for cloud findings flows through+the [AWS Security Hub](/docs/connectors/aws-security-hub) and+[Cloudflare](/docs/connectors/cloudflare) connectors which expose+`BLOCK_IP` / `ALLOW_IP` capabilities. A future `RESOLVE_ISSUE` capability+that calls back into the Wiz GraphQL `updateIssue` mutation is on the+v7.2 roadmap.++## Troubleshooting++**`could not authenticate to wiz`** — the service account credentials are+wrong, or the Auth URL is overridden but pointing at the wrong cloud+(commercial vs gov-cloud). Reset the Auth URL to blank to fall back to the+default commercial endpoint.++**`HTTP 401` on `issues` query** — the OAuth bearer was issued but lacks+`read:issues` scope. Re-grant the scope on the service account in the Wiz+console; tokens cache scopes at issue time, so wait one poll cycle for the+new token to take effect.++**`events_added: 0` indefinitely** — your Wiz tenant has no OPEN issues.+That is the expected steady state for a clean tenant. Trigger a benign+finding (e.g. open a public S3 bucket in a sandbox account) to confirm the+connector path is healthy.++## Related++- [AWS Security Hub](/docs/connectors/aws-security-hub) — alternative cloud+ finding source if you have not adopted Wiz.+- [Lacework](/docs/connectors/lacework) — alternative CNAPP path.diff --git a/apps/docs/docs/detections/coverage.md b/apps/docs/docs/detections/coverage.mdindex 01e408954..f5912e24a 100644--- a/apps/docs/docs/detections/coverage.md+++ b/apps/docs/docs/detections/coverage.md@@ -11,7 +11,7 @@ sidebar_position: 2# Detection Coverage-Generated: `2026-05-10T18:54:09Z`+Generated: `2026-05-11T03:45:32Z`## Headline numbersdiff --git a/apps/docs/sidebars.ts b/apps/docs/sidebars.tsindex d4bcd90cd..f4d7daabd 100644--- a/apps/docs/sidebars.ts+++ b/apps/docs/sidebars.ts@@ -51,6 +51,15 @@ const sidebars: SidebarsConfig = {"connectors/osctrl","connectors/fleetdm","connectors/osquery-extensions",+ "connectors/wiz",+ "connectors/aws-security-hub",+ "connectors/lacework",+ "connectors/prisma-cloud",+ "connectors/orca",+ "connectors/aws-guardduty",+ "connectors/aws-cloudtrail",+ "connectors/aws-vpc-flow",+ "connectors/kubernetes-audit",],},{diff --git a/apps/web/next.config.js b/apps/web/next.config.jsindex e9c3de1f2..2d2f887d8 100644--- a/apps/web/next.config.js+++ b/apps/web/next.config.js@@ -1,5 +1,7 @@/** @type {import('next').NextConfig} */+const path = require('path');+// ─── Server-side rewrite targets ────────────────────────────────────────────//// These are the *origin* URLs the Next.js server uses when proxying@@ -28,8 +30,12 @@ const OSQUERY_TLS_HOST = process.env.OSQUERY_TLS_URL || 'http://localhost:8090';const nextConfig = {reactStrictMode: true,transpilePackages: ['@aisoc/ui', '@aisoc/types'],+ // pnpm monorepo: anchor Turbopack at the repository root so it can resolve+ // the hoisted `next` package via apps/web/node_modules/next (symlink into+ // the root .pnpm store). Setting this to __dirname caused Turbopack to+ // fail in CI with "We couldn't find the Next.js package (next/package.json)".turbopack: {- root: __dirname,+ root: path.resolve(__dirname, '..', '..'),},// Mock data in views uses shapes that diverge from the strict typed API// contracts. We rely on per-package type-checks (pnpm --filter <pkg> tsc)diff --git a/apps/web/package.json b/apps/web/package.jsonindex f03c9a5bd..69258de97 100644--- a/apps/web/package.json+++ b/apps/web/package.json@@ -1,6 +1,6 @@{"name": "@aisoc/web",- "version": "7.0.3",+ "version": "7.1.0","private": true,"description": "AiSOC SOC Console - Next.js 14 Frontend","license": "MIT",diff --git a/apps/web/public/marketplace/curated.json b/apps/web/public/marketplace/curated.jsonindex 746e88ee3..7ac577bd4 100644--- a/apps/web/public/marketplace/curated.json+++ b/apps/web/public/marketplace/curated.json@@ -1,7 +1,7 @@{"$schema": "https://aisoc.example.com/schemas/curated/v1.json","version": "1.0.0",- "generated": "2026-05-10T18:54:09Z",+ "generated": "2026-05-11T03:45:32Z","stats": {"considered": 1047,"eligible": 1043,diff --git a/apps/web/public/marketplace/index.json b/apps/web/public/marketplace/index.jsonindex 28752861d..330225aac 100644--- a/apps/web/public/marketplace/index.json+++ b/apps/web/public/marketplace/index.json@@ -1,7 +1,7 @@{"$schema": "https://example.com/schemas/marketplace/v1.json","version": "1.0.0",- "generated": "2026-05-10T18:54:21Z",+ "generated": "2026-05-11T03:45:31Z","categories": [{"id": "playbooks",@@ -20,16 +20,16 @@}],"stats": {- "total": 7098,+ "total": 7104,"playbooks": 62,"detections": 6993,- "plugins": 43,- "verified": 982,+ "plugins": 49,+ "verified": 985,"community": 0,"by_tier": {- "beta": 3,+ "beta": 6,"imported": 6113,- "stable": 982+ "stable": 985},"detections_by_tier": {"imported": 6113,@@ -223889,6 +223889,69 @@"tier": "stable","path": "plugins/auth0/plugin.yaml"},+ {+ "id": "aws-cloudtrail",+ "type": "plugin",+ "name": "AWS CloudTrail",+ "description": "Polls a curated allow-list of high-signal AWS CloudTrail management events (IAM grants, trail tampering, public-S3 changes, KMS key destruction, cross-account sharing) so detections fire reliably without drowning in read-only describe/list noise. Allow-list is derived directly from the detection content shipped with AiSOC and is overridable via the ``event_names`` config field.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [],+ "plugin_type": null,+ "license": "MIT",+ "homepage": "https://aws.amazon.com/cloudtrail/",+ "min_aisoc_version": null,+ "sdks": [],+ "mitre_techniques": [],+ "verified": false,+ "source": "core",+ "tier": "beta",+ "path": "plugins/aws-cloudtrail/plugin.yaml"+ },+ {+ "id": "aws-guardduty",+ "type": "plugin",+ "name": "AWS GuardDuty Connector",+ "description": "AWS GuardDuty threat detection. Pulls findings directly from the native GuardDuty API (not Security Hub) for richer per-finding context including network connection action, runtime details, EKS audit shape, and S3 access patterns. One connector per region.",+ "version": "1.0.0",+ "author": "AiSOC Core Team",+ "tags": [+ "cloud",+ "aws",+ "guardduty",+ "threat-detection",+ "native"+ ],+ "plugin_type": "connector",+ "license": "MIT",+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/aws_guardduty.py",+ "min_aisoc_version": "7.1.0",+ "sdks": [],+ "mitre_techniques": [],+ "verified": true,+ "source": "core",+ "tier": "stable",+ "path": "plugins/aws-guardduty/plugin.yaml"+ },+ {+ "id": "aws-vpc-flow",+ "type": "plugin",+ "name": "AWS VPC Flow Logs",+ "description": "Streams AWS VPC Flow Log records from CloudWatch Logs with a default REJECT-only filter pattern so detections see denied connections (port scans, brute-force attempts, exfiltration probes) without paying to ingest the steady-state ACCEPT firehose. Parses the default v2 fixed-column layout natively and passes v5 / JSON custom layouts through on raw_event for downstream rules.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [],+ "plugin_type": null,+ "license": "MIT",+ "homepage": "https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs.html",+ "min_aisoc_version": null,+ "sdks": [],+ "mitre_techniques": [],+ "verified": false,+ "source": "core",+ "tier": "beta",+ "path": "plugins/aws-vpc-flow/plugin.yaml"+ },{"id": "azure-activity","type": "plugin",@@ -224407,6 +224470,25 @@"tier": "stable","path": "plugins/jamf-mdm/plugin.yaml"},+ {+ "id": "kubernetes-audit",+ "type": "plugin",+ "name": "Kubernetes Audit Logs",+ "description": "Kubernetes apiserver audit logs in dual delivery mode: webhook (apiserver pushes audit events to AiSOC's tenant-scoped ingest endpoint with a shared-secret header) or file_tail (AiSOC reads a local audit log forward from a byte cursor). Powers cluster-level detections including kubectl exec abuse, ServiceAccount token theft, RBAC privilege escalation, and impersonation. Severity is bucketed by verb + resource + response code so the inbox surfaces high-signal events instead of routine apiserver chatter.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [],+ "plugin_type": null,+ "license": "MIT",+ "homepage": "https://kubernetes.io/docs/tasks/debug/debug-cluster/audit/",+ "min_aisoc_version": null,+ "sdks": [],+ "mitre_techniques": [],+ "verified": false,+ "source": "core",+ "tier": "beta",+ "path": "plugins/kubernetes-audit/plugin.yaml"+ },{"id": "lacework","type": "plugin",@@ -224594,6 +224676,33 @@"tier": "stable","path": "plugins/onepassword-events/plugin.yaml"},+ {+ "id": "orca",+ "type": "plugin",+ "name": "Orca Security Connector",+ "description": "Orca Security cloud-native application protection platform. Pulls open alerts across workload, container, cloud configuration, identity, and data-risk surfaces from the unified /api/alerts REST endpoint. One connector instance covers every Orca surface.",+ "version": "1.0.0",+ "author": "AiSOC Core Team",+ "tags": [+ "cloud",+ "cnapp",+ "cspm",+ "cwpp",+ "ciem",+ "dspm",+ "orca"+ ],+ "plugin_type": "connector",+ "license": "MIT",+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/orca.py",+ "min_aisoc_version": "7.1.0",+ "sdks": [],+ "mitre_techniques": [],+ "verified": true,+ "source": "core",+ "tier": "stable",+ "path": "plugins/orca/plugin.yaml"+ },{"id": "osctrl","type": "plugin",@@ -224647,6 +224756,34 @@"tier": "stable","path": "plugins/pagerduty-paging/plugin.yaml"},+ {+ "id": "prisma-cloud",+ "type": "plugin",+ "name": "Prisma Cloud Connector",+ "description": "Prisma Cloud cloud security platform. Pulls open alerts across CSPM, CWPP, CIEM, and DSPM surfaces via the v1 REST API (/alert).",+ "version": "1.0.0",+ "author": "AiSOC Core Team",+ "tags": [+ "cloud",+ "prisma-cloud",+ "cnapp",+ "cspm",+ "cwpp",+ "ciem",+ "dspm",+ "palo-alto"+ ],+ "plugin_type": "connector",+ "license": "MIT",+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/prisma_cloud.py",+ "min_aisoc_version": "7.1.0",+ "sdks": [],+ "mitre_techniques": [],+ "verified": true,+ "source": "core",+ "tier": "stable",+ "path": "plugins/prisma-cloud/plugin.yaml"+ },{"id": "rapid7-insightidr","type": "plugin",diff --git a/marketplace/curated.json b/marketplace/curated.jsonindex 746e88ee3..7ac577bd4 100644--- a/marketplace/curated.json+++ b/marketplace/curated.json@@ -1,7 +1,7 @@{"$schema": "https://aisoc.example.com/schemas/curated/v1.json","version": "1.0.0",- "generated": "2026-05-10T18:54:09Z",+ "generated": "2026-05-11T03:45:32Z","stats": {"considered": 1047,"eligible": 1043,diff --git a/marketplace/index.json b/marketplace/index.jsonindex 28752861d..330225aac 100644--- a/marketplace/index.json+++ b/marketplace/index.json@@ -1,7 +1,7 @@{"$schema": "https://example.com/schemas/marketplace/v1.json","version": "1.0.0",- "generated": "2026-05-10T18:54:21Z",+ "generated": "2026-05-11T03:45:31Z","categories": [{"id": "playbooks",@@ -20,16 +20,16 @@}],"stats": {- "total": 7098,+ "total": 7104,"playbooks": 62,"detections": 6993,- "plugins": 43,- "verified": 982,+ "plugins": 49,+ "verified": 985,"community": 0,"by_tier": {- "beta": 3,+ "beta": 6,"imported": 6113,- "stable": 982+ "stable": 985},"detections_by_tier": {"imported": 6113,@@ -223889,6 +223889,69 @@"tier": "stable","path": "plugins/auth0/plugin.yaml"},+ {+ "id": "aws-cloudtrail",+ "type": "plugin",+ "name": "AWS CloudTrail",+ "description": "Polls a curated allow-list of high-signal AWS CloudTrail management events (IAM grants, trail tampering, public-S3 changes, KMS key destruction, cross-account sharing) so detections fire reliably without drowning in read-only describe/list noise. Allow-list is derived directly from the detection content shipped with AiSOC and is overridable via the ``event_names`` config field.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [],+ "plugin_type": null,+ "license": "MIT",+ "homepage": "https://aws.amazon.com/cloudtrail/",+ "min_aisoc_version": null,+ "sdks": [],+ "mitre_techniques": [],+ "verified": false,+ "source": "core",+ "tier": "beta",+ "path": "plugins/aws-cloudtrail/plugin.yaml"+ },+ {+ "id": "aws-guardduty",+ "type": "plugin",+ "name": "AWS GuardDuty Connector",+ "description": "AWS GuardDuty threat detection. Pulls findings directly from the native GuardDuty API (not Security Hub) for richer per-finding context including network connection action, runtime details, EKS audit shape, and S3 access patterns. One connector per region.",+ "version": "1.0.0",+ "author": "AiSOC Core Team",+ "tags": [+ "cloud",+ "aws",+ "guardduty",+ "threat-detection",+ "native"+ ],+ "plugin_type": "connector",+ "license": "MIT",+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/aws_guardduty.py",+ "min_aisoc_version": "7.1.0",+ "sdks": [],+ "mitre_techniques": [],+ "verified": true,+ "source": "core",+ "tier": "stable",+ "path": "plugins/aws-guardduty/plugin.yaml"+ },+ {+ "id": "aws-vpc-flow",+ "type": "plugin",+ "name": "AWS VPC Flow Logs",+ "description": "Streams AWS VPC Flow Log records from CloudWatch Logs with a default REJECT-only filter pattern so detections see denied connections (port scans, brute-force attempts, exfiltration probes) without paying to ingest the steady-state ACCEPT firehose. Parses the default v2 fixed-column layout natively and passes v5 / JSON custom layouts through on raw_event for downstream rules.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [],+ "plugin_type": null,+ "license": "MIT",+ "homepage": "https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs.html",+ "min_aisoc_version": null,+ "sdks": [],+ "mitre_techniques": [],+ "verified": false,+ "source": "core",+ "tier": "beta",+ "path": "plugins/aws-vpc-flow/plugin.yaml"+ },{"id": "azure-activity","type": "plugin",@@ -224407,6 +224470,25 @@"tier": "stable","path": "plugins/jamf-mdm/plugin.yaml"},+ {+ "id": "kubernetes-audit",+ "type": "plugin",+ "name": "Kubernetes Audit Logs",+ "description": "Kubernetes apiserver audit logs in dual delivery mode: webhook (apiserver pushes audit events to AiSOC's tenant-scoped ingest endpoint with a shared-secret header) or file_tail (AiSOC reads a local audit log forward from a byte cursor). Powers cluster-level detections including kubectl exec abuse, ServiceAccount token theft, RBAC privilege escalation, and impersonation. Severity is bucketed by verb + resource + response code so the inbox surfaces high-signal events instead of routine apiserver chatter.",+ "version": "1.0.0",+ "author": "AiSOC",+ "tags": [],+ "plugin_type": null,+ "license": "MIT",+ "homepage": "https://kubernetes.io/docs/tasks/debug/debug-cluster/audit/",+ "min_aisoc_version": null,+ "sdks": [],+ "mitre_techniques": [],+ "verified": false,+ "source": "core",+ "tier": "beta",+ "path": "plugins/kubernetes-audit/plugin.yaml"+ },{"id": "lacework","type": "plugin",@@ -224594,6 +224676,33 @@"tier": "stable","path": "plugins/onepassword-events/plugin.yaml"},+ {+ "id": "orca",+ "type": "plugin",+ "name": "Orca Security Connector",+ "description": "Orca Security cloud-native application protection platform. Pulls open alerts across workload, container, cloud configuration, identity, and data-risk surfaces from the unified /api/alerts REST endpoint. One connector instance covers every Orca surface.",+ "version": "1.0.0",+ "author": "AiSOC Core Team",+ "tags": [+ "cloud",+ "cnapp",+ "cspm",+ "cwpp",+ "ciem",+ "dspm",+ "orca"+ ],+ "plugin_type": "connector",+ "license": "MIT",+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/orca.py",+ "min_aisoc_version": "7.1.0",+ "sdks": [],+ "mitre_techniques": [],+ "verified": true,+ "source": "core",+ "tier": "stable",+ "path": "plugins/orca/plugin.yaml"+ },{"id": "osctrl","type": "plugin",@@ -224647,6 +224756,34 @@"tier": "stable","path": "plugins/pagerduty-paging/plugin.yaml"},+ {+ "id": "prisma-cloud",+ "type": "plugin",+ "name": "Prisma Cloud Connector",+ "description": "Prisma Cloud cloud security platform. Pulls open alerts across CSPM, CWPP, CIEM, and DSPM surfaces via the v1 REST API (/alert).",+ "version": "1.0.0",+ "author": "AiSOC Core Team",+ "tags": [+ "cloud",+ "prisma-cloud",+ "cnapp",+ "cspm",+ "cwpp",+ "ciem",+ "dspm",+ "palo-alto"+ ],+ "plugin_type": "connector",+ "license": "MIT",+ "homepage": "https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/prisma_cloud.py",+ "min_aisoc_version": "7.1.0",+ "sdks": [],+ "mitre_techniques": [],+ "verified": true,+ "source": "core",+ "tier": "stable",+ "path": "plugins/prisma-cloud/plugin.yaml"+ },{"id": "rapid7-insightidr","type": "plugin",diff --git a/plugins/aws-cloudtrail/plugin.yaml b/plugins/aws-cloudtrail/plugin.yamlnew file mode 100644index 000000000..d1d14b047--- /dev/null+++ b/plugins/aws-cloudtrail/plugin.yaml@@ -0,0 +1,45 @@+id: aws-cloudtrail+name: AWS CloudTrail+version: 1.0.0+category: cloud+vendor: Amazon Web Services+publisher: AiSOC Community+description: >+ Polls a curated allow-list of high-signal AWS CloudTrail management+ events (IAM grants, trail tampering, public-S3 changes, KMS key+ destruction, cross-account sharing) so detections fire reliably+ without drowning in read-only describe/list noise. Allow-list is+ derived directly from the detection content shipped with AiSOC and+ is overridable via the ``event_names`` config field.+homepage: https://aws.amazon.com/cloudtrail/+docs_url: /docs/connectors/aws-cloudtrail+license: MIT+capabilities:+ - pull_alerts+config_schema:+ - name: region+ label: AWS Region+ type: string+ required: true+ default: us-east-1+ help_text: AWS region to poll CloudTrail events from.+ - name: access_key+ label: Access Key ID+ type: string+ required: false+ help_text: >+ Leave blank to use the runtime IAM role / instance profile+ (recommended for production deployments).+ - name: secret_key+ label: Secret Access Key+ type: secret+ required: false+ help_text: Required only when supplying a static access key above.+ - name: event_names+ label: Event allow-list (comma-separated)+ type: string+ required: false+ help_text: >+ Override the curated event list. Leave blank to use the default+ (recommended), or set to '*' to pull every CloudTrail event in+ the polling window (high volume — not recommended).diff --git a/plugins/aws-guardduty/plugin.yaml b/plugins/aws-guardduty/plugin.yamlnew file mode 100644index 000000000..e4bd97853--- /dev/null+++ b/plugins/aws-guardduty/plugin.yaml@@ -0,0 +1,34 @@+id: aws-guardduty+name: AWS GuardDuty Connector+version: "1.0.0"+plugin_type: connector+tier: stable+description: >+ AWS GuardDuty threat detection. Pulls findings directly from the native+ GuardDuty API (not Security Hub) for richer per-finding context including+ network connection action, runtime details, EKS audit shape, and S3 access+ patterns. One connector per region.+author: AiSOC Core Team+tags: [cloud, aws, guardduty, threat-detection, native]+homepage: https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/aws_guardduty.py+license: MIT+min_aisoc_version: "7.1.0"+config_schema:+ type: object+ required: [region]+ properties:+ region:+ type: string+ description: AWS region the GuardDuty detector lives in.+ default: "us-east-1"+ access_key:+ type: string+ description: >+ IAM access key ID. Leave blank to use the runtime IAM role /+ instance profile, which is the recommended production posture.+ secret_key:+ type: string+ description: >+ IAM secret access key. Required only when supplying a static+ access key above.+ secret: truediff --git a/plugins/aws-vpc-flow/plugin.yaml b/plugins/aws-vpc-flow/plugin.yamlnew file mode 100644index 000000000..fc352c326--- /dev/null+++ b/plugins/aws-vpc-flow/plugin.yaml@@ -0,0 +1,64 @@+id: aws-vpc-flow+name: AWS VPC Flow Logs+version: 1.0.0+category: cloud+vendor: Amazon Web Services+publisher: AiSOC Community+description: >+ Streams AWS VPC Flow Log records from CloudWatch Logs with a default+ REJECT-only filter pattern so detections see denied connections (port+ scans, brute-force attempts, exfiltration probes) without paying to+ ingest the steady-state ACCEPT firehose. Parses the default v2+ fixed-column layout natively and passes v5 / JSON custom layouts+ through on raw_event for downstream rules.+homepage: https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs.html+docs_url: /docs/connectors/aws-vpc-flow+license: MIT+capabilities:+ - pull_alerts+ - pull_logs+config_schema:+ - name: region+ label: AWS Region+ type: string+ required: true+ default: us-east-1+ help_text: AWS region the CloudWatch Logs group lives in.+ - name: log_group_name+ label: CloudWatch Logs log group+ type: string+ required: true+ help_text: >+ The CloudWatch Logs log group your VPC Flow Logs publish to+ (e.g. ``/aws/vpc/flowlogs``). Configure the flow log to publish+ to CloudWatch Logs in the VPC console first if you haven't.+ - name: filter_pattern+ label: CloudWatch Logs filter pattern+ type: string+ required: false+ default: "?REJECT"+ help_text: >+ CloudWatch Logs filter pattern applied server-side. Default+ ``?REJECT`` surfaces blocked flows only. Set to empty string to+ ingest every flow record (high volume warning).+ - name: flow_log_version+ label: Flow log version (v2 or v5)+ type: string+ required: false+ default: v2+ help_text: >+ AiSOC parses v2 (the AWS default 14-field layout) natively. For+ v5 custom layouts the raw record passes through on raw_event so+ detection content can match on the JSON.+ - name: access_key+ label: Access Key ID+ type: string+ required: false+ help_text: >+ Leave blank to use the runtime IAM role / instance profile+ (recommended for production deployments).+ - name: secret_key+ label: Secret Access Key+ type: secret+ required: false+ help_text: Required only when supplying a static access key above.diff --git a/plugins/kubernetes-audit/plugin.yaml b/plugins/kubernetes-audit/plugin.yamlnew file mode 100644index 000000000..1e11aa3d8--- /dev/null+++ b/plugins/kubernetes-audit/plugin.yaml@@ -0,0 +1,77 @@+id: kubernetes-audit+name: Kubernetes Audit Logs+version: 1.0.0+category: cloud+vendor: Kubernetes+publisher: AiSOC Community+description: >+ Kubernetes apiserver audit logs in dual delivery mode: webhook+ (apiserver pushes audit events to AiSOC's tenant-scoped ingest+ endpoint with a shared-secret header) or file_tail (AiSOC reads+ a local audit log forward from a byte cursor). Powers cluster-level+ detections including kubectl exec abuse, ServiceAccount token theft,+ RBAC privilege escalation, and impersonation. Severity is bucketed+ by verb + resource + response code so the inbox surfaces high-signal+ events instead of routine apiserver chatter.+homepage: https://kubernetes.io/docs/tasks/debug/debug-cluster/audit/+docs_url: /docs/connectors/kubernetes-audit+license: MIT+capabilities:+ - pull_audit+ - pull_alerts+config_schema:+ - name: mode+ label: Delivery mode+ type: select+ required: true+ default: webhook+ options:+ - value: webhook+ label: Webhook (apiserver pushes)+ - value: file_tail+ label: File tail (read local audit log)+ help_text: >+ Webhook is the right choice for managed clusters (EKS / GKE+ / AKS). File tail is the right choice for self-hosted clusters+ where you can mount the audit log path into the AiSOC+ connector pod.+ - name: cluster_name+ label: Cluster name+ type: string+ required: true+ help_text: >+ Human-readable cluster name. Stamped onto every normalised+ event so detection content and investigations can filter+ to a single cluster.+ - name: inbox_token+ label: Inbox token (webhook mode, legacy path)+ type: secret+ required: false+ help_text: >+ Optional. Use only if you cannot configure the apiserver to+ send the ``X-AiSOC-K8s-Token`` header (some managed control+ planes restrict custom headers in audit-webhook kubeconfig).+ Bound inbox token created with the ``k8s-audit`` template+ attached. Configure your apiserver AuditSink or+ ``--audit-webhook-config-file`` to POST audit events to+ ``/v1/inbox/<this-token>``. Prefer the dedicated+ ``/v1/ingest/k8s-audit/<tenant_id>`` endpoint described in+ the connector docs whenever possible.+ - name: audit_log_path+ label: Audit log path (file_tail mode only)+ type: string+ required: false+ default: /var/log/kubernetes/audit/audit.log+ help_text: >+ Absolute path to the apiserver audit log file inside the+ connector pod. Mount it read-only from the host or from a+ persistent volume the apiserver writes to.+ - name: cursor_path+ label: Cursor file path (file_tail mode only)+ type: string+ required: false+ help_text: >+ Optional override for where AiSOC stores its byte-position+ cursor. Defaults to ``<audit_log_path>.aisoc-cursor``. Use+ a writeable path — the connector pod needs to update this+ on every successful poll.diff --git a/plugins/orca/plugin.yaml b/plugins/orca/plugin.yamlnew file mode 100644index 000000000..f597fe0d1--- /dev/null+++ b/plugins/orca/plugin.yaml@@ -0,0 +1,29 @@+id: orca+name: Orca Security Connector+version: "1.0.0"+plugin_type: connector+tier: stable+description: >+ Orca Security cloud-native application protection platform. Pulls open+ alerts across workload, container, cloud configuration, identity, and+ data-risk surfaces from the unified /api/alerts REST endpoint. One+ connector instance covers every Orca surface.+author: AiSOC Core Team+tags: [cloud, cnapp, cspm, cwpp, ciem, dspm, orca]+homepage: https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/orca.py+license: MIT+min_aisoc_version: "7.1.0"+config_schema:+ type: object+ required: [api_token]+ properties:+ api_token:+ type: string+ description: Orca Security API token+ secret: true+ api_url:+ type: string+ description: >+ Orca API base URL. Defaults to https://api.orcasecurity.io.+ Override only if your tenant lives on a region-specific endpoint.+ default: "https://api.orcasecurity.io"diff --git a/plugins/prisma-cloud/plugin.yaml b/plugins/prisma-cloud/plugin.yamlnew file mode 100644index 000000000..a1f7e6721--- /dev/null+++ b/plugins/prisma-cloud/plugin.yaml@@ -0,0 +1,30 @@+id: prisma-cloud+name: Prisma Cloud Connector+version: "1.0.0"+plugin_type: connector+tier: stable+description: >+ Prisma Cloud cloud security platform. Pulls open alerts across CSPM,+ CWPP, CIEM, and DSPM surfaces via the v1 REST API (/alert).+author: AiSOC Core Team+tags: [cloud, prisma-cloud, cnapp, cspm, cwpp, ciem, dspm, palo-alto]+homepage: https://github.com/beenuar/AiSOC/tree/main/services/connectors/app/connectors/prisma_cloud.py+license: MIT+min_aisoc_version: "7.1.0"+config_schema:+ type: object+ required: [api_url, access_key_id, secret_key]+ properties:+ api_url:+ type: string+ description: "Region-specific Prisma Cloud REST API URL (e.g. https://api.prismacloud.io)."+ access_key_id:+ type: string+ description: Access Key ID minted under Settings → Access Control → Access Keys.+ secret_key:+ type: string+ description: Secret Key for the access key (shown once at creation).+ secret: true+ compute_url:+ type: string+ description: Tenant-specific Compute (Twistlock) API base URL (optional, unused in v7.1.0).diff --git a/services/connectors/app/connectors/__init__.py b/services/connectors/app/connectors/__init__.pyindex 73aa888a2..5c82d9f07 100644--- a/services/connectors/app/connectors/__init__.py+++ b/services/connectors/app/connectors/__init__.py@@ -17,7 +17,10 @@ from __future__ import annotationsfrom typing import TYPE_CHECKINGfrom app.connectors.auth0 import Auth0Connector+from app.connectors.aws_cloudtrail import AWSCloudTrailConnector+from app.connectors.aws_guardduty import AWSGuardDutyConnectorfrom app.connectors.aws_security_hub import AWSSecurityHubConnector+from app.connectors.aws_vpc_flow import AWSVPCFlowLogsConnectorfrom app.connectors.azure_activity import AzureActivityConnectorfrom app.connectors.azure_defender import AzureDefenderConnectorfrom app.connectors.azure_entra import AzureEntraConnector@@ -39,13 +42,16 @@ from app.connectors.gcp_scc import GCPSCCConnectorfrom app.connectors.github import GitHubConnectorfrom app.connectors.google_workspace import GoogleWorkspaceConnectorfrom app.connectors.jira_connector import JiraConnector+from app.connectors.kubernetes_audit import KubernetesAuditConnectorfrom app.connectors.lacework import LaceworkConnectorfrom app.connectors.m365_audit import M365AuditConnectorfrom app.connectors.microsoft_sentinel import MicrosoftSentinelConnectorfrom app.connectors.mimecast import MimecastConnectorfrom app.connectors.okta import OktaConnectorfrom app.connectors.onepassword import OnePasswordConnector+from app.connectors.orca import OrcaConnectorfrom app.connectors.osctrl import OsctrlConnector+from app.connectors.prisma_cloud import PrismaCloudConnectorfrom app.connectors.proofpoint import ProofpointConnectorfrom app.connectors.rapid7_insightidr import Rapid7InsightIDRConnectorfrom app.connectors.salesforce import SalesforceConnector@@ -69,7 +75,10 @@ if TYPE_CHECKING:# Source of truth for "which connectors does this build know about".# Keep alphabetised by connector_id for predictable diffs._CONNECTOR_CLASSES: tuple[type[BaseConnector], ...] = (+ AWSCloudTrailConnector,+ AWSGuardDutyConnector,AWSSecurityHubConnector,+ AWSVPCFlowLogsConnector,Auth0Connector,AzureActivityConnector,AzureDefenderConnector,@@ -91,13 +100,16 @@ _CONNECTOR_CLASSES: tuple[type[BaseConnector], ...] = (GitHubConnector,GoogleWorkspaceConnector,JiraConnector,+ KubernetesAuditConnector,LaceworkConnector,M365AuditConnector,MicrosoftSentinelConnector,MimecastConnector,OktaConnector,OnePasswordConnector,+ OrcaConnector,OsctrlConnector,+ PrismaCloudConnector,ProofpointConnector,Rapid7InsightIDRConnector,SalesforceConnector,@@ -157,7 +169,10 @@ def list_connector_schemas() -> list[dict]:__all__ = [+ "AWSCloudTrailConnector",+ "AWSGuardDutyConnector","AWSSecurityHubConnector",+ "AWSVPCFlowLogsConnector","Auth0Connector","AzureActivityConnector","AzureDefenderConnector",@@ -183,6 +198,7 @@ __all__ = ["GitHubConnector","GoogleWorkspaceConnector","JiraConnector",+ "KubernetesAuditConnector","LaceworkConnector","M365AuditConnector","MicrosoftSentinelConnector",@@ -190,7 +206,9 @@ __all__ = ["OAuthHints","OktaConnector","OnePasswordConnector",+ "OrcaConnector","OsctrlConnector",+ "PrismaCloudConnector","ProofpointConnector","Rapid7InsightIDRConnector","SalesforceConnector",diff --git a/services/connectors/app/connectors/aws_cloudtrail.py b/services/connectors/app/connectors/aws_cloudtrail.pynew file mode 100644index 000000000..87c46a425--- /dev/null+++ b/services/connectors/app/connectors/aws_cloudtrail.py@@ -0,0 +1,459 @@+"""+AWS CloudTrail connector.++Polls a curated allow-list of high-signal CloudTrail events via+``cloudtrail.lookup_events`` and emits normalized AiSOC alerts.++Why an allow-list, not a firehose?++ CloudTrail in a busy production account emits tens of thousands of+ events per minute — mostly noisy describes/lists from AWS services+ themselves. Detections in ``detections/cloud/aws-*.yaml`` only fire+ on a small, well-defined set of mutating or sensitive events (IAM+ grants, trail tampering, public-S3 changes, KMS key destruction,+ cross-account snapshot/AMI sharing, etc). We default-poll exactly+ that set so the ingest pipeline sees the events detections care+ about and nothing else.++ Operators who want a different scope can override via the+ ``event_names`` config field (comma-separated). Setting it to ``*``+ disables the filter and pulls all events in the time window.++API mechanics:++ ``lookup_events`` takes one ``LookupAttributes`` filter at a time,+ so we issue one paginated call per ``EventName`` in the allow-list+ per poll. Each call is capped at 100 results. With ~80 events in+ the default allow-list and the AWS CloudTrail rate limit of 2 TPS+ per region per account, a full poll completes in ~40 seconds in+ the worst case. Most events return zero results in a 5-minute+ window, so steady-state is much faster.++ Each event has a ``CloudTrailEvent`` field that contains the full+ record (``userIdentity``, ``requestParameters``, ``responseElements``,+ ``sourceIPAddress``, ``errorCode``, etc.) as a JSON string. We parse+ that to extract the fields detections actually filter on.++Auth model:++ Same dual-mode pattern as AWS Security Hub and GuardDuty. Either:+ - Leave ``access_key`` / ``secret_key`` blank to use the runtime+ IAM role / instance profile (recommended for production).+ - Or supply a static IAM access-key pair scoped to+ ``cloudtrail:LookupEvents`` read-only permissions.++Severity bucketing:++ CloudTrail doesn't ship intrinsic severity. We label by event+ sensitivity (trail tamper / detection tamper / KMS destruction →+ high, mutating IAM / network / public-S3 → medium, read-only recon+ → low). Events with an ``errorCode`` get bumped up one tier because+ a denied destructive action is often the loudest signal in the+ account.+"""++from __future__ import annotations++import ipaddress+import json+from datetime import UTC, datetime, timedelta+from typing import Any++import structlog++from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field++logger = structlog.get_logger()+++# High-severity events: trail/detection tamper, KMS destruction, root+# account use, org-level tampering. These are almost always incidents.+_HIGH_SEVERITY_EVENTS = frozenset(+ {+ "ChangeRootMail",+ "DeleteDetector",+ "DeleteFlowLogs",+ "DeleteTrail",+ "DisableKey",+ "DisableSecurityHub",+ "LeaveOrganization",+ "PutEventSelectors",+ "RemoveAccountFromOrganization",+ "ScheduleKeyDeletion",+ "StopConfigurationRecorder",+ "StopLogging",+ "TransferDomainToAnotherAwsAccount",+ "UpdateTrail",+ }+)+++# Read-only / recon events. Useful for sequencing but individually low+# severity.+_LOW_SEVERITY_EVENTS = frozenset(+ {+ "GetAccountAuthorizationDetails",+ "GetAccountSummary",+ "GetObject",+ "GetSecretValue",+ "ListAccessKeys",+ }+)+++# Default curated allow-list. Every entry here is referenced by at+# least one detection rule in ``detections/cloud/aws-*.yaml`` or+# ``detections/cloud/cloud-*.yaml`` — keep it tight to keep CloudTrail+# volume manageable. Sorted alphabetically for diff-friendliness.+DEFAULT_EVENT_NAMES: tuple[str, ...] = (+ "AddPermission",+ "AddUserToGroup",+ "AssumeRole",+ "AttachGroupPolicy",+ "AttachRolePolicy",+ "AttachUserPolicy",+ "AuthorizeSecurityGroupIngress",+ "ChangeRootMail",+ "ConsoleLogin",+ "CreateAccessKey",+ "CreateCluster",+ "CreateDBInstance",+ "CreateFargateProfile",+ "CreateFunction",+ "CreateFunctionUrlConfig",+ "CreateLoadBalancer",+ "CreateLoginProfile",+ "CreatePolicy",+ "CreatePolicyVersion",+ "CreateRole",+ "CreateRoute",+ "CreateSAMLProvider",+ "CreateService",+ "CreateUser",+ "CreateVpcPeeringConnection",+ "DeactivateMFADevice",+ "DeleteBucket",+ "DeleteDetector",+ "DeleteFlowLogs",+ "DeletePublicAccessBlock",+ "DeleteTrail",+ "DeleteUserPermissionsBoundary",+ "DisableKey",+ "DisableSecurityHub",+ "DisassociateWebACL",+ "GetAccountAuthorizationDetails",+ "GetAccountSummary",+ "GetSecretValue",+ "ImportKeyPair",+ "LeaveOrganization",+ "ListAccessKeys",+ "ModifyDBInstance",+ "ModifyDBSnapshotAttribute",+ "ModifyImageAttribute",+ "ModifyInstanceAttribute",+ "ModifyLoadBalancerAttributes",+ "ModifySnapshotAttribute",+ "PutBucketAcl",+ "PutBucketLogging",+ "PutBucketPolicy",+ "PutBucketPublicAccessBlock",+ "PutBucketReplication",+ "PutEventSelectors",+ "PutImageScanningConfiguration",+ "PutKeyPolicy",+ "PutObjectLockConfiguration",+ "PutObjectRetention",+ "PutParameter",+ "PutRolePolicy",+ "PutUserPolicy",+ "RegisterTaskDefinition",+ "RemoveAccountFromOrganization",+ "RunInstances",+ "ScheduleKeyDeletion",+ "SetDefaultPolicyVersion",+ "SetQueueAttributes",+ "SetRepositoryPolicy",+ "SetTopicAttributes",+ "StopConfigurationRecorder",+ "StopLogging",+ "TransferDomainToAnotherAwsAccount",+ "UpdateAssumeRolePolicy",+ "UpdateClusterConfig",+ "UpdateDistribution",+ "UpdateFunctionConfiguration",+ "UpdateSAMLProvider",+ "UpdateService",+ "UpdateTrail",+)+++def _event_severity(event_name: str, error_code: str | None) -> str:+ """Bucket a CloudTrail event into AiSOC's 4-tier severity ladder.++ Heuristic:+ - HIGH if it's in ``_HIGH_SEVERITY_EVENTS`` (trail tamper,+ KMS destruction, org-level changes, etc).+ - LOW if it's a known read-only recon call.+ - MEDIUM for everything else (the default for mutating events).++ Events that failed (``errorCode`` set) get bumped up one tier on+ the theory that a denied destructive action is often the loudest+ signal we have in the account.+ """+ if event_name in _HIGH_SEVERITY_EVENTS:+ base = "high"+ elif event_name in _LOW_SEVERITY_EVENTS:+ base = "low"+ else:+ base = "medium"++ if not error_code:+ return base++ bump = {"info": "low", "low": "medium", "medium": "high", "high": "high"}+ return bump.get(base, base)+++class AWSCloudTrailConnector(BaseConnector):+ connector_id = "aws_cloudtrail"+ connector_name = "AWS CloudTrail"+ connector_category = "cloud"++ @classmethod+ def schema(cls) -> ConnectorSchema:+ return ConnectorSchema(+ connector_id=cls.connector_id,+ connector_name=cls.connector_name,+ category=cls.connector_category,+ description=(+ "AWS CloudTrail audit events. Polls a curated "+ "allow-list of high-signal management events "+ "(IAM grants, trail tampering, public-S3 changes, "+ "KMS key destruction, cross-account sharing) so "+ "detections fire without drowning in read-only noise."+ ),+ docs_url="/docs/connectors/aws-cloudtrail",+ fields=[+ Field("region", "string", "AWS Region", default="us-east-1"),+ Field(+ "access_key",+ "string",+ "Access Key ID",+ required=False,+ help_text="Leave blank to use the runtime IAM role / instance profile.",+ ),+ Field(+ "secret_key",+ "secret",+ "Secret Access Key",+ required=False,+ help_text="Required only when supplying a static access key above.",+ ),+ Field(+ "event_names",+ "string",+ "Event allow-list (comma-separated)",+ required=False,+ default="",+ help_text=(+ "Override the default curated event list. "+ "Leave blank to use AiSOC's curated list, or "+ "set to '*' to pull every CloudTrail event in "+ "the window (high volume — not recommended)."+ ),+ ),+ ],+ )++ @classmethod+ def capabilities(cls) -> tuple[Capability, ...]:+ return (Capability.PULL_ALERTS,)++ def __init__(+ self,+ region: str = "us-east-1",+ access_key: str = "",+ secret_key: str = "",+ event_names: str = "",+ ):+ self._region = region+ self._access_key = access_key+ self._secret_key = secret_key+ self._event_names = self._parse_event_names(event_names)++ @staticmethod+ def _parse_event_names(raw: str) -> tuple[str, ...] | None:+ """Resolve the ``event_names`` config field.++ Returns:+ - ``None`` to mean "no filter, pull every event"+ (only when the operator explicitly sets ``*``).+ - A tuple of event names otherwise. Empty / blank input+ falls back to the curated default list.+ """+ if not raw:+ return DEFAULT_EVENT_NAMES+ stripped = raw.strip()+ if stripped == "*":+ return None+ parsed = tuple(sorted({e.strip() for e in stripped.split(",") if e.strip()}))+ return parsed or DEFAULT_EVENT_NAMES++ def _get_client(self):+ try:+ import boto3++ kwargs: dict[str, Any] = {"region_name": self._region}+ if self._access_key and self._secret_key:+ kwargs["aws_access_key_id"] = self._access_key+ kwargs["aws_secret_access_key"] = self._secret_key+ return boto3.client("cloudtrail", **kwargs)+ except ImportError as exc:+ raise RuntimeError("boto3 is required for AWS CloudTrail connector. Install it with: pip install boto3") from exc++ async def test_connection(self) -> dict[str, Any]:+ try:+ client = self._get_client()+ # ``describe_trails`` is the cheapest auth-only call. We don't+ # require the account to have at least one trail because+ # ``lookup_events`` works against the management-events+ # history even when no trail is configured — but if the auth+ # is wrong, this call will surface it.+ client.describe_trails()+ return {+ "success": True,+ "connector": self.connector_id,+ "region": self._region,+ }+ except Exception as exc:+ return {+ "success": False,+ "connector": self.connector_id,+ "error": str(exc),+ }++ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:+ try:+ client = self._get_client()+ except RuntimeError as exc:+ logger.warning("cloudtrail.client_init_failed", error=str(exc))+ return []++ start_time = datetime.now(UTC) - timedelta(seconds=since_seconds)+ end_time = datetime.now(UTC)++ all_events: list[dict[str, Any]] = []++ if self._event_names is None:+ # Firehose mode — pull every event in the window. Operators+ # who set ``event_names=*`` explicitly opted in.+ all_events.extend(self._lookup_for_attribute(client, attribute=None, start=start_time, end=end_time))+ else:+ for event_name in self._event_names:+ try:+ all_events.extend(+ self._lookup_for_attribute(+ client,+ attribute=("EventName", event_name),+ start=start_time,+ end=end_time,+ )+ )+ except Exception as exc:+ # Don't let one bad event-name shape kill the poll.+ logger.warning(+ "cloudtrail.lookup_failed",+ event_name=event_name,+ error=str(exc),+ )+ continue++ return [self.normalize(e) for e in all_events]++ @staticmethod+ def _lookup_for_attribute(+ client,+ attribute: tuple[str, str] | None,+ start: datetime,+ end: datetime,+ ) -> list[dict[str, Any]]:+ kwargs: dict[str, Any] = {+ "StartTime": start,+ "EndTime": end,+ "MaxResults": 50,+ }+ if attribute is not None:+ attr_key, attr_value = attribute+ kwargs["LookupAttributes"] = [{"AttributeKey": attr_key, "AttributeValue": attr_value}]++ events: list[dict[str, Any]] = []+ paginator = client.get_paginator("lookup_events")+ # Cap each event-name at 100 hits per poll. If a single event+ # is firing more than 100 times in 5 minutes the operator+ # already has a different problem.+ pages = paginator.paginate(**kwargs, PaginationConfig={"MaxItems": 100, "PageSize": 50})+ for page in pages:+ events.extend(page.get("Events", []))+ return events++ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:+ # ``CloudTrailEvent`` is the full record encoded as a JSON+ # string. The lookup envelope only carries the top-level+ # summary fields, so unpack the embedded payload for the rich+ # detection-friendly fields (sourceIPAddress, errorCode,+ # requestParameters, etc.).+ detail: dict[str, Any] = {}+ ct_event = raw.get("CloudTrailEvent")+ if isinstance(ct_event, str):+ try:+ detail = json.loads(ct_event)+ except (TypeError, ValueError):+ detail = {}+ elif isinstance(ct_event, dict):+ detail = ct_event++ user_identity = detail.get("userIdentity") or {}+ event_name = raw.get("EventName") or detail.get("eventName") or ""+ error_code = detail.get("errorCode")+ severity = _event_severity(event_name, error_code)++ event_time = raw.get("EventTime") or detail.get("eventTime")+ # ``EventTime`` from boto3 is a tz-aware datetime; coerce to+ # ISO-8601 so the rest of the pipeline (which is mostly Go and+ # postgres) can read it without type-juggling.+ if isinstance(event_time, datetime):+ event_time = event_time.astimezone(UTC).isoformat()++ src_ip = detail.get("sourceIPAddress") or raw.get("SourceIPAddress")+ # AWS populates ``sourceIPAddress`` with either a real IP (v4/v6) or an+ # AWS service principal hostname like ``cloudtrail.amazonaws.com`` for+ # internal callers. Validate as a real IP and drop anything else —+ # safer than substring-matching ``amazonaws.com``, which would also+ # accept hostile lookalikes such as ``amazonaws.com.attacker.tld``.+ if isinstance(src_ip, str):+ try:+ ipaddress.ip_address(src_ip.strip())+ except ValueError:+ src_ip = None++ return {+ "source": self.connector_id,+ "category": "cloud",+ "external_id": raw.get("EventId") or detail.get("eventID"),+ "title": event_name or "CloudTrail event",+ "description": (f"{event_name} on {detail.get('eventSource', 'aws')}" if event_name else "CloudTrail audit event"),+ "severity": severity,+ "event_name": event_name,+ "event_source": detail.get("eventSource") or raw.get("EventSource"),+ "aws_account_id": detail.get("recipientAccountId") or detail.get("userIdentity", {}).get("accountId"),+ "aws_region": detail.get("awsRegion") or self._region,+ "cloud_platform": "aws",+ "user_name": (raw.get("Username") or user_identity.get("userName") or user_identity.get("principalId")),+ "user_arn": user_identity.get("arn"),+ "user_type": user_identity.get("type"),+ "src_ip": src_ip,+ "error_code": error_code,+ "user_agent": detail.get("userAgent"),+ "raw_event": detail or raw,+ "created_at": event_time,+ }diff --git a/services/connectors/app/connectors/aws_guardduty.py b/services/connectors/app/connectors/aws_guardduty.pynew file mode 100644index 000000000..1265468a3--- /dev/null+++ b/services/connectors/app/connectors/aws_guardduty.py@@ -0,0 +1,253 @@+"""+AWS GuardDuty connector.++Pulls findings from one or more AWS GuardDuty detectors in a single region+via boto3. GuardDuty's data model is:++ detector --> finding (per detector)++so each poll lists all detectors in the configured region, then fetches+findings under each detector. Cross-region coverage is handled by adding+one connector instance per region.++Auth model:+ Same dual-mode pattern as AWS Security Hub. Either:+ - Leave ``access_key`` / ``secret_key`` blank to use the runtime+ IAM role / instance profile (recommended for production).+ - Or supply a static IAM access-key pair scoped to read-only+ GuardDuty permissions.++Severity collapse:+ GuardDuty returns severity as a float in [1.0, 8.9]. AiSOC's+ canonical ladder is ``info | low | medium | high``. We bucket using+ AWS's published thresholds:++ 1.0–3.9 --> low+ 4.0–6.9 --> medium+ 7.0–8.9 --> high++ Anything < 1.0 (rare but possible for sample/test findings) collapses+ to ``info``.+"""++from __future__ import annotations++from datetime import UTC, datetime, timedelta+from typing import Any++import structlog++from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field++logger = structlog.get_logger()+++def _severity_label(score: float | int | None) -> str:+ """Collapse GuardDuty's float severity into AiSOC's 4-tier ladder.++ GuardDuty publishes severity as a float roughly in [0.1, 10.0]. AWS's+ own console buckets that into Low (1.0-3.9), Medium (4.0-6.9),+ High (7.0-8.9), and Critical (9.0-10.0). AiSOC's canonical ladder+ has no ``critical`` tier, so anything 7.0+ collapses into ``high``+ and the original float is preserved on ``raw_event.Severity`` for+ callers that need exact comparisons.+ """+ if score is None:+ return "medium"+ try:+ s = float(score)+ except (TypeError, ValueError):+ return "medium"+ if s < 1.0:+ return "info"+ if s < 4.0:+ return "low"+ if s < 7.0:+ return "medium"+ return "high"+++class AWSGuardDutyConnector(BaseConnector):+ connector_id = "aws_guardduty"+ connector_name = "AWS GuardDuty"+ connector_category = "cloud"++ @classmethod+ def schema(cls) -> ConnectorSchema:+ return ConnectorSchema(+ connector_id=cls.connector_id,+ connector_name=cls.connector_name,+ category=cls.connector_category,+ description=(+ "AWS GuardDuty findings. Pulls native GuardDuty alerts "+ "(threat detection across VPC flow logs, DNS logs, "+ "CloudTrail, EKS, S3, RDS, Lambda) directly without "+ "requiring Security Hub aggregation."+ ),+ docs_url="/docs/connectors/aws-guardduty",+ fields=[+ Field("region", "string", "AWS Region", default="us-east-1"),+ Field(+ "access_key",+ "string",+ "Access Key ID",+ required=False,+ help_text="Leave blank to use the runtime IAM role / instance profile.",+ ),+ Field(+ "secret_key",+ "secret",+ "Secret Access Key",+ required=False,+ help_text="Required only when supplying a static access key above.",+ ),+ ],+ )++ @classmethod+ def capabilities(cls) -> tuple[Capability, ...]:+ return (Capability.PULL_ALERTS,)++ def __init__(+ self,+ region: str = "us-east-1",+ access_key: str = "",+ secret_key: str = "",+ ):+ self._region = region+ self._access_key = access_key+ self._secret_key = secret_key++ def _get_client(self):+ try:+ import boto3++ kwargs: dict[str, Any] = {"region_name": self._region}+ if self._access_key and self._secret_key:+ kwargs["aws_access_key_id"] = self._access_key+ kwargs["aws_secret_access_key"] = self._secret_key+ return boto3.client("guardduty", **kwargs)+ except ImportError as exc:+ raise RuntimeError("boto3 is required for AWS GuardDuty connector. Install it with: pip install boto3") from exc++ async def test_connection(self) -> dict[str, Any]:+ try:+ client = self._get_client()+ # ``list_detectors`` is the cheapest auth-only call. We treat+ # a successful 200 with zero detectors as a soft failure+ # because the polling loop would be a no-op forever — the+ # operator almost certainly pointed at the wrong region.+ resp = client.list_detectors()+ detector_ids = resp.get("DetectorIds", [])+ if not detector_ids:+ return {+ "success": False,+ "connector": self.connector_id,+ "error": (+ f"GuardDuty has no detector in region {self._region}. "+ "Enable GuardDuty in this region or point the "+ "connector at the correct region."+ ),+ }+ return {+ "success": True,+ "connector": self.connector_id,+ "region": self._region,+ "detector_count": len(detector_ids),+ }+ except Exception as exc:+ return {+ "success": False,+ "connector": self.connector_id,+ "error": str(exc),+ }++ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:+ try:+ client = self._get_client()+ except RuntimeError as exc:+ logger.warning("guardduty.client_init_failed", error=str(exc))+ return []++ # GuardDuty stores ``updatedAt`` as epoch milliseconds. Filter on+ # the cursor window so we only re-fetch changed findings.+ cursor_ms = int((datetime.now(UTC) - timedelta(seconds=since_seconds)).timestamp() * 1000)++ all_findings: list[dict[str, Any]] = []++ try:+ detector_ids = client.list_detectors().get("DetectorIds", [])+ except Exception as exc:+ logger.warning("guardduty.list_detectors_failed", error=str(exc))+ return []++ for detector_id in detector_ids:+ try:+ # Page list_findings to keep memory bounded. We cap each+ # detector at 500 findings per poll — same order of+ # magnitude as the Security Hub connector.+ finding_ids: list[str] = []+ paginator = client.get_paginator("list_findings")+ pages = paginator.paginate(+ DetectorId=detector_id,+ FindingCriteria={+ "Criterion": {+ "updatedAt": {"GreaterThanOrEqual": cursor_ms},+ "service.archived": {"Equals": ["false"]},+ }+ },+ PaginationConfig={"MaxItems": 500, "PageSize": 50},+ )+ for page in pages:+ finding_ids.extend(page.get("FindingIds", []))++ if not finding_ids:+ continue++ # ``get_findings`` accepts max 50 IDs per call.+ for i in range(0, len(finding_ids), 50):+ batch = finding_ids[i : i + 50]+ resp = client.get_findings(DetectorId=detector_id, FindingIds=batch)+ all_findings.extend(resp.get("Findings", []))+ except Exception as exc:+ logger.warning(+ "guardduty.detector_fetch_failed",+ detector_id=detector_id,+ error=str(exc),+ )+ continue++ return [self.normalize(f) for f in all_findings]++ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:+ service = raw.get("Service") or {}+ resource = raw.get("Resource") or {}+ severity = _severity_label(raw.get("Severity"))++ # Best-effort attacker-IP extraction. GuardDuty surfaces remote IPs+ # on a few different paths depending on the finding type+ # (PortProbe, Recon:EC2/Portscan, UnauthorizedAccess:*, etc).+ action = service.get("Action") or {}+ remote_ip = (+ action.get("NetworkConnectionAction", {}).get("RemoteIpDetails", {}).get("IpAddressV4")+ or action.get("AwsApiCallAction", {}).get("RemoteIpDetails", {}).get("IpAddressV4")+ or action.get("PortProbeAction", {}).get("PortProbeDetails", [{}])[0].get("RemoteIpDetails", {}).get("IpAddressV4")+ )++ return {+ "source": self.connector_id,+ "category": "cloud",+ "external_id": raw.get("Id"),+ "title": raw.get("Title") or raw.get("Type") or "GuardDuty finding",+ "description": raw.get("Description") or "",+ "severity": severity,+ "src_ip": remote_ip,+ "aws_account_id": raw.get("AccountId"),+ "aws_region": raw.get("Region"),+ "cloud_platform": "aws",+ "cloud_resource": (resource.get("InstanceDetails") or {}).get("InstanceId")+ or (resource.get("AccessKeyDetails") or {}).get("AccessKeyId"),+ "rule_name": raw.get("Type"),+ "raw_event": raw,+ "created_at": raw.get("CreatedAt"),+ }diff --git a/services/connectors/app/connectors/aws_vpc_flow.py b/services/connectors/app/connectors/aws_vpc_flow.pynew file mode 100644index 000000000..5f0548c60--- /dev/null+++ b/services/connectors/app/connectors/aws_vpc_flow.py@@ -0,0 +1,442 @@+"""+AWS VPC Flow Logs connector.++Pulls VPC Flow Log records from a CloudWatch Logs log group via+``logs.filter_log_events`` and emits normalised AiSOC alerts.++Why CloudWatch Logs and not S3?++ AWS lets you publish flow logs to either CloudWatch Logs or S3. The+ CloudWatch Logs path is the only one with a real-time, queryable+ API surface — ``filter_log_events`` supports a CloudWatch Logs+ filter pattern, returns events as JSON envelopes, and tracks a+ cursor we can resume from. The S3 path is cheaper at petabyte+ scale but requires a separate parse/dedupe layer per object and+ has 5–10 minute publish latency. For an alert-pipeline connector+ we want the lower-latency CloudWatch path.++Why default to ``?REJECT``?++ Even a tiny VPC publishes hundreds of thousands of flow records+ per minute. The vast majority are uninteresting ACCEPTed traffic+ on long-lived TCP sessions. Detection content in+ ``detections/network/`` and ``detections/cloud/`` only fires on+ rejected / unusual flows, port scans, or specific destinations.+ Defaulting the CloudWatch filter pattern to ``?REJECT`` keeps the+ poll volume sane while still surfacing every blocked flow. Operators+ can override via the ``filter_pattern`` field.++Flow log format support:++ AWS supports two field layouts:++ v2 (default) — 14 space-separated fields, version through+ log-status. Documented at:+ https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs.html#flow-logs-fields++ v5 (custom) — operator-defined field set. The first record+ in the log group can include a ``${header}``+ line, but more commonly operators publish+ custom fields in JSON or in a fixed order+ agreed in their AWS configuration. We support+ v2 natively and pass v5 through as-is on+ ``raw_event`` so downstream detection content+ can match on the JSON.++Auth model:+ Same dual-mode pattern as the other AWS connectors. Either:+ - Leave ``access_key`` / ``secret_key`` blank to use the runtime+ IAM role / instance profile (recommended for production).+ - Or supply a static IAM access-key pair scoped to read-only+ ``logs:FilterLogEvents`` and ``logs:DescribeLogGroups`` on+ the target log group.+"""++from __future__ import annotations++import json+from datetime import UTC, datetime+from typing import Any++import structlog++from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field++logger = structlog.get_logger()+++# v2 (default) field order. From AWS docs:+# https://docs.aws.amazon.com/vpc/latest/userguide/flow-logs.html#flow-logs-fields+_V2_FIELDS: tuple[str, ...] = (+ "version",+ "account_id",+ "interface_id",+ "src_ip",+ "dst_ip",+ "src_port",+ "dst_port",+ "protocol",+ "packets",+ "bytes",+ "start",+ "end",+ "action",+ "log_status",+)+++# IANA protocol numbers we surface as a friendly name. Anything not in+# this table flows through as the raw integer so detections can still+# match on it.+_PROTOCOL_NAMES: dict[str, str] = {+ "1": "icmp",+ "6": "tcp",+ "17": "udp",+ "47": "gre",+ "50": "esp",+ "51": "ah",+ "58": "icmpv6",+}+++def _parse_v2_record(message: str) -> dict[str, Any]:+ """Parse a single space-separated v2 VPC flow log line.++ Returns an empty dict for the header line (``version account-id ...``)+ or for malformed lines. We deliberately *don't* raise — flow log+ poll volume is high enough that a single garbled record should not+ abort the whole batch.+ """+ if not message or not message.strip():+ return {}++ parts = message.strip().split()+ if len(parts) != len(_V2_FIELDS):+ # Wrong column count — either a v5 custom layout or a header+ # line. Hand back empty so the caller can fall through to the+ # generic JSON pass-through path.+ return {}++ rec: dict[str, Any] = dict(zip(_V2_FIELDS, parts, strict=False))++ # AWS uses literal ``-`` for "no value" fields. Normalise to None.+ for k, v in list(rec.items()):+ if v == "-":+ rec[k] = None++ # Friendly protocol name where we know it.+ proto_raw = rec.get("protocol")+ if proto_raw:+ rec["protocol_name"] = _PROTOCOL_NAMES.get(str(proto_raw), str(proto_raw))++ return rec+++def _record_severity(parsed: dict[str, Any]) -> str:+ """Pick a severity tier for a flow log record.++ Heuristic:+ - ``REJECT`` action -> medium (blocked flows are the loud+ signal we publish this connector for in the first place).+ - ``ACCEPT`` action -> low (operator opted in to ACCEPTs by+ changing the filter, so they want them, but they're not+ inherently alert-worthy).+ - log-status of ``NODATA`` / ``SKIPDATA`` -> info (collection+ gaps, useful for the pipeline-health channel).+ - Anything else -> low.+ """+ action = (parsed.get("action") or "").upper()+ log_status = (parsed.get("log_status") or "").upper()++ if log_status in {"NODATA", "SKIPDATA"}:+ return "info"+ if action == "REJECT":+ return "medium"+ if action == "ACCEPT":+ return "low"+ return "low"+++class AWSVPCFlowLogsConnector(BaseConnector):+ connector_id = "aws_vpc_flow"+ connector_name = "AWS VPC Flow Logs"+ connector_category = "cloud"++ @classmethod+ def schema(cls) -> ConnectorSchema:+ return ConnectorSchema(+ connector_id=cls.connector_id,+ connector_name=cls.connector_name,+ category=cls.connector_category,+ description=(+ "AWS VPC Flow Logs streamed from CloudWatch Logs. "+ "Defaults to surfacing rejected flows only so the "+ "ingest pipeline gets the actionable network-deny "+ "signal without drowning in steady-state ACCEPT noise."+ ),+ docs_url="/docs/connectors/aws-vpc-flow",+ fields=[+ Field("region", "string", "AWS Region", default="us-east-1"),+ Field(+ "log_group_name",+ "string",+ "CloudWatch Logs log group",+ required=True,+ help_text=(+ "The CloudWatch Logs log group your VPC Flow "+ "Logs publish to (e.g. ``/aws/vpc/flowlogs``). "+ "Configure flow logs to publish to CloudWatch "+ "Logs in the VPC console first if you haven't."+ ),+ ),+ Field(+ "filter_pattern",+ "string",+ "CloudWatch Logs filter pattern",+ required=False,+ default="?REJECT",+ help_text=(+ "CloudWatch Logs filter pattern applied "+ "server-side. Default ``?REJECT`` surfaces "+ "blocked flows only. Set to empty string to "+ "ingest every flow record (high volume warning)."+ ),+ ),+ Field(+ "flow_log_version",+ "string",+ "Flow log version (v2 or v5)",+ required=False,+ default="v2",+ help_text=(+ "AiSOC parses v2 (the AWS default 14-field "+ "layout) natively. For v5 custom layouts the "+ "raw record passes through on raw_event so "+ "detection content can match on the JSON."+ ),+ ),+ Field(+ "access_key",+ "string",+ "Access Key ID",+ required=False,+ help_text="Leave blank to use the runtime IAM role / instance profile.",+ ),+ Field(+ "secret_key",+ "secret",+ "Secret Access Key",+ required=False,+ help_text="Required only when supplying a static access key above.",+ ),+ ],+ )++ @classmethod+ def capabilities(cls) -> tuple[Capability, ...]:+ # Flow log records are passive logs, not curated alerts. We tag+ # both PULL_LOGS (true to the source) and PULL_ALERTS (since+ # downstream detections produce alerts from these records and+ # the agent layer treats them in the alert pipeline).+ return (Capability.PULL_LOGS, Capability.PULL_ALERTS)++ def __init__(+ self,+ region: str = "us-east-1",+ log_group_name: str = "",+ filter_pattern: str = "?REJECT",+ flow_log_version: str = "v2",+ access_key: str = "",+ secret_key: str = "",+ ):+ self._region = region+ self._log_group_name = log_group_name+ # Empty / whitespace = no server-side filter. Don't accidentally+ # send the literal string ``""`` to CloudWatch as a filter.+ self._filter_pattern = (filter_pattern or "").strip()+ self._flow_log_version = (flow_log_version or "v2").strip().lower()+ self._access_key = access_key+ self._secret_key = secret_key++ def _get_client(self):+ try:+ import boto3++ kwargs: dict[str, Any] = {"region_name": self._region}+ if self._access_key and self._secret_key:+ kwargs["aws_access_key_id"] = self._access_key+ kwargs["aws_secret_access_key"] = self._secret_key+ return boto3.client("logs", **kwargs)+ except ImportError as exc:+ raise RuntimeError("boto3 is required for AWS VPC Flow Logs connector. Install it with: pip install boto3") from exc++ async def test_connection(self) -> dict[str, Any]:+ if not self._log_group_name:+ return {+ "success": False,+ "connector": self.connector_id,+ "error": "log_group_name is required",+ }+ try:+ client = self._get_client()+ # ``describe_log_groups`` with a prefix is the cheapest way+ # to verify both auth and that the log group actually+ # exists. We then check the result set rather than relying+ # on an exception, because the API returns 200 + empty list+ # for "no match".+ resp = client.describe_log_groups(logGroupNamePrefix=self._log_group_name, limit=5)+ groups = resp.get("logGroups", []) or []+ match = any(g.get("logGroupName") == self._log_group_name for g in groups)+ if not match:+ return {+ "success": False,+ "connector": self.connector_id,+ "error": (+ f"log group {self._log_group_name} not found in "+ f"region {self._region}. Verify the name and that "+ "the credentials can describe log groups."+ ),+ }+ return {+ "success": True,+ "connector": self.connector_id,+ "region": self._region,+ "log_group": self._log_group_name,+ }+ except Exception as exc:+ return {+ "success": False,+ "connector": self.connector_id,+ "error": str(exc),+ }++ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:+ if not self._log_group_name:+ logger.warning(+ "vpc_flow.log_group_missing",+ connector=self.connector_id,+ )+ return []++ try:+ client = self._get_client()+ except RuntimeError as exc:+ logger.warning("vpc_flow.client_init_failed", error=str(exc))+ return []++ # CloudWatch Logs takes start/end as epoch milliseconds.+ end_ms = int(datetime.now(UTC).timestamp() * 1000)+ start_ms = end_ms - (since_seconds * 1000)++ kwargs: dict[str, Any] = {+ "logGroupName": self._log_group_name,+ "startTime": start_ms,+ "endTime": end_ms,+ # 1k events / page is the API max. Cap total volume at 5k+ # per poll so a single misconfigured filter can't wedge+ # the scheduler.+ "limit": 1000,+ }+ if self._filter_pattern:+ kwargs["filterPattern"] = self._filter_pattern++ events: list[dict[str, Any]] = []+ try:+ paginator = client.get_paginator("filter_log_events")+ pages = paginator.paginate(**kwargs, PaginationConfig={"MaxItems": 5000, "PageSize": 1000})+ for page in pages:+ events.extend(page.get("events", []))+ except Exception as exc:+ logger.warning(+ "vpc_flow.filter_log_events_failed",+ log_group=self._log_group_name,+ error=str(exc),+ )+ return []++ return [self.normalize(e) for e in events]++ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:+ """Map a CloudWatch Logs envelope to AiSOC's normalised shape.++ ``raw`` is the envelope from ``filter_log_events``:+ {+ "logStreamName": "...",+ "timestamp": 1731000000000,+ "message": "<the actual flow log line>",+ "ingestionTime": 1731000000123,+ "eventId": "..."+ }++ We try the v2 fixed-column parser first, fall back to JSON, and+ finally fall back to a passthrough so detection content always+ sees the original message body.+ """+ message = raw.get("message", "") or ""+ parsed: dict[str, Any] = {}+ record_format = "unknown"++ # Path 1: v2 fixed-column. Almost all default flow log+ # configurations land here.+ if self._flow_log_version == "v2":+ parsed = _parse_v2_record(message)+ if parsed:+ record_format = "v2"++ # Path 2: JSON line. v5 layouts can be configured to publish+ # JSON, and some operators wrap their flow logs in their own+ # structured envelope.+ if not parsed and message.strip().startswith("{"):+ try:+ parsed = json.loads(message)+ record_format = "json"+ except (TypeError, ValueError):+ parsed = {}++ severity = _record_severity(parsed) if parsed else "info"+ action = parsed.get("action") if parsed else None++ # Build a human-readable title even when parse failed, because+ # operators looking at the inbox shouldn't see a blank row.+ if parsed and parsed.get("src_ip") and parsed.get("dst_ip"):+ title = (+ f"VPC flow {action or 'event'}: "+ f"{parsed.get('src_ip')}:{parsed.get('src_port', '?')} -> "+ f"{parsed.get('dst_ip')}:{parsed.get('dst_port', '?')}"+ )+ elif action:+ title = f"VPC flow {action}"+ else:+ title = "VPC flow log event"++ # CloudWatch envelope timestamp is epoch milliseconds. Coerce+ # to ISO-8601 so the rest of the pipeline (Go + postgres) can+ # read it directly.+ ts_ms = raw.get("timestamp")+ created_at: str | None = None+ if isinstance(ts_ms, int | float):+ created_at = datetime.fromtimestamp(ts_ms / 1000.0, tz=UTC).isoformat()++ return {+ "source": self.connector_id,+ "category": "network",+ "external_id": raw.get("eventId"),+ "title": title,+ "description": message,+ "severity": severity,+ "src_ip": parsed.get("src_ip") if parsed else None,+ "dst_ip": parsed.get("dst_ip") if parsed else None,+ "src_port": parsed.get("src_port") if parsed else None,+ "dst_port": parsed.get("dst_port") if parsed else None,+ "protocol": parsed.get("protocol_name") or (parsed.get("protocol") if parsed else None),+ "action": action,+ "aws_account_id": parsed.get("account_id") if parsed else None,+ "aws_region": self._region,+ "cloud_platform": "aws",+ "cloud_resource": parsed.get("interface_id") if parsed else None,+ "log_stream": raw.get("logStreamName"),+ "log_status": parsed.get("log_status") if parsed else None,+ "record_format": record_format,+ "raw_event": parsed or {"message": message},+ "created_at": created_at,+ }diff --git a/services/connectors/app/connectors/kubernetes_audit.py b/services/connectors/app/connectors/kubernetes_audit.pynew file mode 100644index 000000000..c75b8cf88--- /dev/null+++ b/services/connectors/app/connectors/kubernetes_audit.py@@ -0,0 +1,592 @@+"""+Kubernetes audit log connector.++The Kubernetes API server emits an audit log for every authenticated+request hitting the apiserver. Audit logs are the highest-fidelity+detection surface inside a cluster: every ``kubectl exec``, every+service-account token mint, every ``secrets`` GET shows up here.+Almost every detection rule under+``detections/cloud/kubernetes-*.yaml`` and+``detections/identity/kubernetes-*.yaml`` expects events in this+shape.++Why dual-mode (webhook vs file_tail)?++ Kubernetes supports two audit backends:++ * **Webhook backend** — the apiserver POSTs each batch of audit+ events to an HTTP endpoint configured via ``AuditSink`` (v1beta1)+ or via the ``--audit-webhook-config-file`` apiserver flag. This+ is the right pick for managed clusters (EKS / GKE / AKS) where+ operators can't shell onto the control plane to read log files.+ We don't expose a new HTTP route per connector — instead this+ mode tells the operator to drop their audit events at the+ existing ``/v1/inbox/{token}`` endpoint backed by the+ ``k8s-audit`` ingest template. That keeps the auth model+ consistent (token-bound) and reuses the same normalizer the+ rest of the inbox flow uses.++ * **file_tail backend** — many self-hosted clusters publish+ audit events to a local JSON-line file (``--audit-log-path``).+ The polling scheduler reads the file forward from a cursor+ and ships each event up to ingest. This mode is the+ operationally-cheap option for on-prem / Rancher / kubeadm+ clusters, but does require AiSOC's connector pod to be able+ to read the file.++ Both modes emit the same normalized shape — the apiserver writes+ the same ``Event`` JSON schema regardless of backend+ (``audit.k8s.io/v1``), so all the divergence is in *how* we+ receive bytes, not in what's inside them.++What we don't do here:++ The connector deliberately does not run a long-lived listener+ process. ``fetch_alerts`` is called by the polling scheduler on+ a cadence; in file_tail mode we read from the cursor; in webhook+ mode we return an empty list and the events arrive over the+ inbox path instead. That keeps the runtime model identical to+ every other connector and avoids needing connector-instance-aware+ HTTP routes.++Severity heuristic:++ Audit events don't carry an inherent severity — they're a raw+ log of API activity. We bucket using the following heuristic+ so the inbox doesn't fill with low-signal ``get pods`` rows:++ * ``critical`` — ``exec`` / ``attach`` / ``portforward`` into+ a pod, ``impersonate`` verb, or any write against+ ``clusterrolebindings`` / ``rolebindings``.+ * ``high`` — write verbs (``create`` / ``delete`` /+ ``patch``) on ``secrets``, ``serviceaccounts``,+ ``clusterroles``, or ``roles``.+ * ``medium`` — write verbs on workloads (``deployments``,+ ``daemonsets``, ``statefulsets``) or any failed (non-2xx)+ request.+ * ``low`` — read verbs on sensitive resources.+ * ``info`` — anything else (the apiserver chatter floor).+"""++from __future__ import annotations++import json+import os+from datetime import UTC, datetime+from pathlib import Path+from typing import Any++import structlog++from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field++logger = structlog.get_logger()+++# Verbs that mutate cluster state. Used by the severity heuristic.+_WRITE_VERBS: frozenset[str] = frozenset({"create", "update", "patch", "delete", "deletecollection"})++# Resources we always treat as sensitive (writes are high+).+_SENSITIVE_RESOURCES: frozenset[str] = frozenset(+ {+ "secrets",+ "serviceaccounts",+ "clusterroles",+ "roles",+ "clusterrolebindings",+ "rolebindings",+ "certificatesigningrequests",+ }+)++# Pod subresources that imply interactive access. ``exec`` is the big+# one — it's the kubernetes-native "shell on prod" verb.+_INTERACTIVE_SUBRESOURCES: frozenset[str] = frozenset({"exec", "attach", "portforward", "proxy"})++# Workload resources whose writes deserve medium severity even+# without a sensitive-resource match.+_WORKLOAD_RESOURCES: frozenset[str] = frozenset(+ {+ "deployments",+ "daemonsets",+ "statefulsets",+ "jobs",+ "cronjobs",+ "pods",+ "replicasets",+ }+)++# Hard ceiling on bytes read per poll in file_tail mode. The+# apiserver can produce hundreds of MB per minute on a busy cluster+# — we'd rather drop trailing events from a single poll and catch+# up on the next tick than wedge the scheduler.+_MAX_TAIL_BYTES_PER_POLL = 8 * 1024 * 1024 # 8 MiB+++def _classify_severity(event: dict[str, Any]) -> str:+ """Bucket a single audit event into AiSOC's 4-tier severity ladder.++ Reads the standard ``audit.k8s.io/v1`` Event shape:+ objectRef.resource, objectRef.subresource, verb,+ responseStatus.code.+ """+ verb = (event.get("verb") or "").lower()+ obj_ref = event.get("objectRef") or {}+ resource = (obj_ref.get("resource") or "").lower()+ subresource = (obj_ref.get("subresource") or "").lower()+ code = (event.get("responseStatus") or {}).get("code")++ # Interactive shell into a pod is the loudest signal we have.+ if resource == "pods" and subresource in _INTERACTIVE_SUBRESOURCES:+ return "high"++ # Privilege-escalation primitives.+ if verb == "impersonate":+ return "high"++ # Writes against the RBAC graph itself.+ if verb in _WRITE_VERBS and resource in {"clusterrolebindings", "rolebindings"}:+ return "high"++ # Writes against any other sensitive resource.+ if verb in _WRITE_VERBS and resource in _SENSITIVE_RESOURCES:+ return "high"++ # Workload writes are medium — operators do these all the time+ # in normal CI/CD flow, so they're not high, but they're not+ # noise floor either.+ if verb in _WRITE_VERBS and resource in _WORKLOAD_RESOURCES:+ return "medium"++ # Failed (non-2xx) requests are worth bumping above floor so+ # bruteforce / probing patterns surface.+ if isinstance(code, int) and code >= 400:+ return "medium"++ # Reads of sensitive resources — useful trail for credential+ # access investigations but not inherently alarming.+ if verb in {"get", "list", "watch"} and resource in _SENSITIVE_RESOURCES:+ return "low"++ return "info"+++class KubernetesAuditConnector(BaseConnector):+ """Dual-mode Kubernetes audit log connector.++ Configure exactly one of:+ * ``mode = "webhook"`` — listener configured externally; you+ POST audit events to ``/v1/inbox/{inbox_token}`` with the+ ``k8s-audit`` template attached. ``fetch_alerts`` returns+ an empty list because the events arrive via the inbox path.+ * ``mode = "file_tail"`` — the connector pod reads the local+ audit log file forward from a saved byte cursor.+ """++ connector_id = "kubernetes_audit"+ connector_name = "Kubernetes Audit Logs"+ connector_category = "cloud"++ # File cursor state lives next to the audit log itself so the+ # cursor survives connector restarts. Operators who'd rather+ # store cursors in a different location can override via the+ # ``cursor_path`` field — see schema().+ _DEFAULT_CURSOR_SUFFIX = ".aisoc-cursor"++ @classmethod+ def schema(cls) -> ConnectorSchema:+ return ConnectorSchema(+ connector_id=cls.connector_id,+ connector_name=cls.connector_name,+ category=cls.connector_category,+ description=(+ "Kubernetes apiserver audit logs. Supports two delivery "+ "modes: webhook (apiserver pushes events to AiSOC's "+ "inbox) and file_tail (AiSOC tails a local audit log "+ "file forward from a byte cursor). Powers cluster-level "+ "detections under detections/cloud/kubernetes-*.yaml."+ ),+ docs_url="/docs/connectors/kubernetes-audit",+ fields=[+ Field(+ "mode",+ "select",+ "Delivery mode",+ required=True,+ default="webhook",+ options=[+ {"value": "webhook", "label": "Webhook (apiserver pushes)"},+ {"value": "file_tail", "label": "File tail (read local audit log)"},+ ],+ help_text=(+ "Webhook is the right choice for managed "+ "clusters (EKS/GKE/AKS). File tail is the "+ "right choice for self-hosted clusters where "+ "you can mount the audit log path into the "+ "AiSOC connector pod."+ ),+ ),+ Field(+ "cluster_name",+ "string",+ "Cluster name",+ required=True,+ help_text=(+ "Human-readable cluster name. Surfaced on "+ "every normalised event so detections and "+ "investigations can filter to a single cluster."+ ),+ ),+ Field(+ "inbox_token",+ "secret",+ "Inbox token (webhook mode only)",+ required=False,+ help_text=(+ "Bound inbox token created with the "+ "``k8s-audit`` template attached. Configure "+ "your apiserver AuditSink / "+ "--audit-webhook-config-file to POST to "+ "``/v1/inbox/<this-token>``."+ ),+ ),+ Field(+ "audit_log_path",+ "string",+ "Audit log path (file_tail mode only)",+ required=False,+ default="/var/log/kubernetes/audit/audit.log",+ help_text=(+ "Absolute path to the apiserver audit log "+ "file inside the connector pod. Mount it "+ "read-only from the host or from a persistent "+ "volume the apiserver writes to."+ ),+ ),+ Field(+ "cursor_path",+ "string",+ "Cursor file path (file_tail mode only)",+ required=False,+ help_text=(+ "Optional override for where AiSOC stores "+ "its byte-position cursor. Defaults to "+ "``<audit_log_path>.aisoc-cursor``. Use a "+ "writeable path — the connector pod needs "+ "to update this on every successful poll."+ ),+ ),+ ],+ )++ @classmethod+ def capabilities(cls) -> tuple[Capability, ...]:+ # Audit logs are the canonical PULL_AUDIT surface inside a+ # cluster. They also drive PULL_ALERTS because downstream+ # detections turn them into alerts.+ return (Capability.PULL_AUDIT, Capability.PULL_ALERTS)++ def __init__(+ self,+ mode: str = "webhook",+ cluster_name: str = "",+ inbox_token: str = "",+ audit_log_path: str = "/var/log/kubernetes/audit/audit.log",+ cursor_path: str = "",+ ):+ self._mode = (mode or "webhook").strip().lower()+ self._cluster_name = cluster_name+ self._inbox_token = inbox_token+ self._audit_log_path = audit_log_path+ self._cursor_path = cursor_path or f"{audit_log_path}{self._DEFAULT_CURSOR_SUFFIX}"++ # ------------------------------ helpers ----------------------------------++ def _read_cursor(self) -> int:+ """Read the byte offset for the next file_tail poll.++ Missing cursor file -> 0 (start of file). Corrupt cursor file+ -> 0 with a warning; better to re-ingest than to silently+ wedge on an unreadable cursor.+ """+ try:+ with open(self._cursor_path) as fh:+ raw = fh.read().strip()+ return int(raw) if raw else 0+ except FileNotFoundError:+ return 0+ except (OSError, ValueError) as exc:+ logger.warning(+ "kubernetes_audit.cursor_read_failed",+ cursor_path=self._cursor_path,+ error=str(exc),+ )+ return 0++ def _write_cursor(self, offset: int) -> None:+ try:+ # Atomic write: rename is the only POSIX-portable way to+ # avoid a partially-written cursor on crash.+ tmp = f"{self._cursor_path}.tmp"+ with open(tmp, "w") as fh:+ fh.write(str(offset))+ os.replace(tmp, self._cursor_path)+ except OSError as exc:+ logger.warning(+ "kubernetes_audit.cursor_write_failed",+ cursor_path=self._cursor_path,+ offset=offset,+ error=str(exc),+ )++ def _tail_audit_file(self) -> list[dict[str, Any]]:+ """Read forward from the saved cursor.++ Handles three rotation scenarios:+ * Truncation (file size < cursor) -> reset cursor to 0.+ * Replacement (logrotate copied + truncated, but inode+ unchanged) -> covered by the truncation case.+ * Rename + create (logrotate moved the old file aside) ->+ we re-open the new file and start from 0.+ """+ path = Path(self._audit_log_path)+ if not path.exists():+ logger.warning(+ "kubernetes_audit.audit_log_missing",+ audit_log_path=str(path),+ )+ return []++ try:+ size = path.stat().st_size+ except OSError as exc:+ logger.warning(+ "kubernetes_audit.stat_failed",+ audit_log_path=str(path),+ error=str(exc),+ )+ return []++ cursor = self._read_cursor()+ # File shrank -> rotation/truncation. Start over.+ if cursor > size:+ logger.info(+ "kubernetes_audit.cursor_reset_after_rotation",+ old_cursor=cursor,+ new_size=size,+ )+ cursor = 0++ if cursor >= size:+ # No new bytes since last poll — common, cheap exit.+ return []++ # Cap how much we read in a single poll. Better to fall+ # behind by one poll cycle than to chew the scheduler trying+ # to drain an enormous backlog on the same tick.+ read_end = min(size, cursor + _MAX_TAIL_BYTES_PER_POLL)+ events: list[dict[str, Any]] = []++ try:+ with open(path, "rb") as fh:+ fh.seek(cursor)+ chunk = fh.read(read_end - cursor)+ except OSError as exc:+ logger.warning(+ "kubernetes_audit.read_failed",+ audit_log_path=str(path),+ cursor=cursor,+ error=str(exc),+ )+ return []++ # The apiserver writes one JSON event per line. Split on+ # newline, keeping the trailing partial (if any) for the+ # next poll by adjusting the cursor to the last complete+ # newline.+ last_complete_offset = cursor+ for line in chunk.splitlines(keepends=True):+ last_complete_offset += len(line)+ stripped = line.strip()+ if not stripped:+ continue+ # If this line doesn't end with a newline, we read a+ # partial trailing event — back the cursor up and wait+ # for the rest on the next poll.+ if not line.endswith(b"\n"):+ last_complete_offset -= len(line)+ break+ try:+ events.append(json.loads(stripped))+ except (TypeError, ValueError):+ # A malformed line shouldn't abort the batch — log+ # and skip. This is a high-volume source and we'd+ # rather drop one event than miss everything after it.+ logger.warning(+ "kubernetes_audit.parse_failed",+ cursor_offset=last_complete_offset,+ )+ continue++ self._write_cursor(last_complete_offset)+ return events++ # ------------------------------ contract ---------------------------------++ async def test_connection(self) -> dict[str, Any]:+ if not self._cluster_name:+ return {+ "success": False,+ "connector": self.connector_id,+ "error": "cluster_name is required",+ }++ if self._mode == "webhook":+ if not self._inbox_token:+ return {+ "success": False,+ "connector": self.connector_id,+ "error": (+ "inbox_token is required in webhook mode. Create an inbox token bound to the k8s-audit template and paste it here."+ ),+ }+ return {+ "success": True,+ "connector": self.connector_id,+ "mode": "webhook",+ "cluster": self._cluster_name,+ "hint": (f"Configure your apiserver AuditSink to POST to /v1/inbox/{self._inbox_token[:6]}…"),+ }++ if self._mode == "file_tail":+ path = Path(self._audit_log_path)+ if not path.exists():+ return {+ "success": False,+ "connector": self.connector_id,+ "error": (+ f"audit log path {self._audit_log_path} not "+ "found inside the connector pod. Make sure "+ "the apiserver audit log is mounted and "+ "readable."+ ),+ }+ if not os.access(self._audit_log_path, os.R_OK):+ return {+ "success": False,+ "connector": self.connector_id,+ "error": (f"audit log path {self._audit_log_path} is not readable by the connector pod."),+ }+ return {+ "success": True,+ "connector": self.connector_id,+ "mode": "file_tail",+ "cluster": self._cluster_name,+ "audit_log_path": self._audit_log_path,+ "cursor_path": self._cursor_path,+ }++ return {+ "success": False,+ "connector": self.connector_id,+ "error": (f"unknown mode '{self._mode}'. Expected one of: webhook, file_tail."),+ }++ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:+ # ``since_seconds`` is intentionally ignored in both modes:+ # * webhook mode pulls nothing on the scheduler tick+ # because events arrive via the inbox path.+ # * file_tail mode uses the byte cursor, not a time+ # window, because the apiserver doesn't timestamp the+ # trailing partial line we might have stopped on.+ if self._mode == "webhook":+ return []+ if self._mode == "file_tail":+ events = self._tail_audit_file()+ return [self.normalize(e) for e in events]+ return []++ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:+ """Map an audit.k8s.io/v1 Event to AiSOC's normalised shape.++ See https://kubernetes.io/docs/tasks/debug/debug-cluster/audit/+ for the upstream schema. We project the subset detection+ content actually pivots on; the full event lives on+ ``raw_event`` for everything else.+ """+ verb = raw.get("verb")+ user = (raw.get("user") or {}) if isinstance(raw.get("user"), dict) else {}+ username = user.get("username")+ impersonated = raw.get("impersonatedUser") or {}+ impersonated_username = impersonated.get("username") if isinstance(impersonated, dict) else None++ obj_ref = (raw.get("objectRef") or {}) if isinstance(raw.get("objectRef"), dict) else {}+ resource = obj_ref.get("resource")+ subresource = obj_ref.get("subresource")+ namespace = obj_ref.get("namespace")+ name = obj_ref.get("name")++ response_status = (raw.get("responseStatus") or {}) if isinstance(raw.get("responseStatus"), dict) else {}+ response_code = response_status.get("code")++ source_ips_raw = raw.get("sourceIPs") or []+ source_ips: list[str] = [str(ip) for ip in source_ips_raw] if isinstance(source_ips_raw, list) else []+ # The apiserver writes the immediate caller first; the+ # remaining entries are the X-Forwarded-For chain. Pick the+ # first one as the "principal" src_ip so detection content+ # has a single field to match against.+ principal_src_ip = source_ips[0] if source_ips else None++ severity = _classify_severity(raw)++ # The apiserver emits ``stageTimestamp`` (RFC3339) for every+ # event; fall back to ``requestReceivedTimestamp`` if that's+ # the only one present (older API versions).+ stamp = raw.get("stageTimestamp") or raw.get("requestReceivedTimestamp")+ created_at: str | None = None+ if isinstance(stamp, str):+ created_at = stamp+ elif isinstance(stamp, datetime):+ created_at = stamp.astimezone(UTC).isoformat()++ # Human-readable title — operators in the alert inbox should+ # be able to read "what happened" without expanding the row.+ target = name or "(cluster-scope)"+ if namespace:+ target = f"{namespace}/{target}"+ sub = f"/{subresource}" if subresource else ""+ title = f"k8s audit: {username or 'unknown'} {verb or 'request'} {resource or 'resource'}{sub} {target}"++ return {+ "source": self.connector_id,+ "category": "cloud",+ "external_id": raw.get("auditID"),+ "title": title,+ "description": (+ f"verb={verb} resource={resource} subresource={subresource} "+ f"namespace={namespace} name={name} user={username} "+ f"impersonated={impersonated_username} code={response_code}"+ ),+ "severity": severity,+ "cluster_name": self._cluster_name,+ "k8s_user": username,+ "k8s_user_groups": user.get("groups") if isinstance(user, dict) else None,+ "k8s_impersonated_user": impersonated_username,+ "k8s_verb": verb,+ "k8s_resource": resource,+ "k8s_subresource": subresource,+ "k8s_namespace": namespace,+ "k8s_object_name": name,+ "k8s_api_group": obj_ref.get("apiGroup"),+ "k8s_api_version": obj_ref.get("apiVersion"),+ "k8s_response_code": response_code,+ "k8s_user_agent": raw.get("userAgent"),+ "src_ip": principal_src_ip,+ "source_ips": source_ips or None,+ "cloud_platform": "kubernetes",+ "stage": raw.get("stage"),+ "audit_id": raw.get("auditID"),+ "raw_event": raw,+ "created_at": created_at,+ }diff --git a/services/connectors/app/connectors/orca.py b/services/connectors/app/connectors/orca.pynew file mode 100644index 000000000..e8034a335--- /dev/null+++ b/services/connectors/app/connectors/orca.py@@ -0,0 +1,199 @@+"""+Orca Security connector.++Pulls open security alerts from an Orca Security tenant via the public+REST API. Like the other CNAPP integrations in this release, one Orca+connector instance covers every Orca surface — workload, container,+cloud configuration, identity, and data risks — because the+``/api/alerts`` endpoint is unified across products.++Auth model:+ Long-lived API token, sent as ``Authorization: Token <token>``.+ Tokens are minted in the Orca console under+ Settings → Users & Permissions → API Tokens.++Severity collapse:+ Orca uses a 5-tier ladder (``hazardous, critical, high, medium,+ informational``). AiSOC exposes 4 tiers (``high, medium, low, info``).+ ``hazardous`` and ``critical`` collapse into ``high``. The original+ Orca tier is preserved on ``raw_event.state.severity``.+"""++from __future__ import annotations++from datetime import UTC, datetime, timedelta+from typing import Any++import httpx+import structlog++from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field++logger = structlog.get_logger()++_DEFAULT_API_URL = "https://api.orcasecurity.io"++# Orca's 5-tier ladder collapsed into AiSOC's 4-tier canonical set.+# ``hazardous`` is Orca-internal terminology for "actively exploited /+# active threat" and is unambiguously high-impact. ``critical`` likewise+# collapses into ``high`` because AiSOC does not expose a separate+# critical band.+_SEVERITY_MAP: dict[str, str] = {+ "hazardous": "high",+ "imminent_compromise": "high",+ "critical": "high",+ "high": "high",+ "medium": "medium",+ "low": "low",+ "informational": "info",+ "info": "info",+}+++class OrcaConnector(BaseConnector):+ """Orca Security cloud-native application protection platform."""++ connector_id = "orca"+ connector_name = "Orca Security"+ connector_category = "cloud"++ @classmethod+ def schema(cls) -> ConnectorSchema:+ return ConnectorSchema(+ connector_id=cls.connector_id,+ connector_name=cls.connector_name,+ category=cls.connector_category,+ description=(+ "Orca Security CNAPP. Pulls open alerts across workload, "+ "container, cloud configuration, identity, and data risk "+ "surfaces from the unified /api/alerts REST endpoint."+ ),+ docs_url="/docs/connectors/orca",+ fields=[+ Field("api_token", "secret", "API Token"),+ Field(+ "api_url",+ "string",+ "API URL",+ required=False,+ default=_DEFAULT_API_URL,+ placeholder=_DEFAULT_API_URL,+ help_text=(+ "Override only if your tenant lives on a region-specific "+ "Orca endpoint. The default works for the standard "+ "commercial cloud."+ ),+ ),+ ],+ )++ @classmethod+ def capabilities(cls) -> tuple[Capability, ...]:+ return (Capability.PULL_ALERTS,)++ def __init__(self, api_token: str, api_url: str | None = None):+ self._api_token = api_token+ self._api_url = (api_url or _DEFAULT_API_URL).rstrip("/")++ def _headers(self) -> dict[str, str]:+ return {+ "Authorization": f"Token {self._api_token}",+ "Accept": "application/json",+ "Content-Type": "application/json",+ }++ async def test_connection(self) -> dict[str, Any]:+ try:+ async with httpx.AsyncClient(timeout=15.0) as client:+ # Orca's ``/api/user/session`` returns the auth-context+ # for the calling token. It's the cheapest auth-only call+ # and surfaces both bad-token and revoked-token cases+ # cleanly.+ resp = await client.get(+ f"{self._api_url}/api/user/session",+ headers=self._headers(),+ )+ if resp.status_code == 200:+ return {+ "success": True,+ "connector": self.connector_id,+ "api_url": self._api_url,+ }+ return {+ "success": False,+ "connector": self.connector_id,+ "error": f"orca auth failed: HTTP {resp.status_code}",+ }+ except Exception as exc:+ return {+ "success": False,+ "connector": self.connector_id,+ "error": str(exc),+ }++ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:+ end = datetime.now(UTC)+ start = end - timedelta(seconds=since_seconds)+ # Orca's /api/alerts accepts an ISO-8601 ``start_at_gte`` to+ # limit results to alerts opened since the cursor. ``status``+ # filter keeps the volume sane by only returning open alerts.+ params = {+ "start_at_gte": start.strftime("%Y-%m-%dT%H:%M:%SZ"),+ "status": "open",+ "limit": 200,+ }+ try:+ async with httpx.AsyncClient(timeout=30.0) as client:+ resp = await client.get(+ f"{self._api_url}/api/alerts",+ headers=self._headers(),+ params=params,+ )+ if resp.status_code != 200:+ logger.warning(+ "orca.fetch_failed",+ status=resp.status_code,+ body=resp.text[:300],+ )+ return []+ payload = resp.json() or {}+ except Exception as exc:+ logger.warning("orca.fetch_exception", error=str(exc))+ return []++ # Orca has shipped both ``{"data": [...]}`` and+ # ``{"results": [...]}`` envelopes across product versions.+ # Accept both plus the bare-list fallback.+ items: list[dict[str, Any]]+ if isinstance(payload, list):+ items = payload+ elif isinstance(payload, dict):+ items = payload.get("data") or payload.get("results") or payload.get("alerts") or []+ else:+ items = []++ return [self.normalize(i) for i in items]++ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:+ state = raw.get("state") or {}+ asset = raw.get("asset") or raw.get("source_asset") or {}+ cloud_account = raw.get("cloud_account") or {}++ sev_raw = (state.get("severity") or raw.get("severity") or raw.get("priority") or "medium").lower()+ severity = _SEVERITY_MAP.get(sev_raw, "medium")++ return {+ "source": self.connector_id,+ "category": "cloud",+ "external_id": raw.get("alert_id") or raw.get("id"),+ "title": raw.get("description") or raw.get("rule_name") or "Orca alert",+ "description": raw.get("recommendation") or raw.get("description") or "",+ "severity": severity,+ "hostname": asset.get("name") or asset.get("asset_name"),+ "cloud_resource": asset.get("vendor_id") or asset.get("asset_unique_id"),+ "cloud_platform": asset.get("vendor") or cloud_account.get("vendor") or raw.get("cloud_provider"),+ "cloud_region": asset.get("region") or asset.get("cloud_region"),+ "rule_name": raw.get("rule_name") or raw.get("type"),+ "raw_event": raw,+ "created_at": raw.get("created_at") or raw.get("source_event_time"),+ }diff --git a/services/connectors/app/connectors/prisma_cloud.py b/services/connectors/app/connectors/prisma_cloud.pynew file mode 100644index 000000000..3f9bafa80--- /dev/null+++ b/services/connectors/app/connectors/prisma_cloud.py@@ -0,0 +1,253 @@+"""+Prisma Cloud (Palo Alto Networks) connector.++Pulls open security alerts from a Prisma Cloud tenant via the v1 REST API.+A single connector instance covers every Prisma Cloud surface — CSPM, CWPP,+CIEM, DSPM — because the ``/alert/v1/alert`` endpoint aggregates findings+across all of them.++Auth model:+ POST /login with ``username`` (= access key ID) and ``password`` (=+ secret) returns a short-lived JWT in ``token``. We exchange on every+ poll because Prisma Cloud tokens have a sliding TTL and re-auth is+ cheap; this avoids cache-invalidation bugs around expiry windows.++The optional ``compute_url`` field stays in the schema for forward+compatibility with the Compute (Twistlock) API, but the v7.1.0 release+only consumes the unified ``/alert`` surface — which already includes+runtime findings collapsed in from Compute.+"""++from __future__ import annotations++from datetime import UTC, datetime, timedelta+from typing import Any++import httpx+import structlog++from app.connectors.base import BaseConnector, Capability, ConnectorSchema, Field++logger = structlog.get_logger()++# Prisma Cloud uses a 4-tier severity ladder; map directly into AiSOC's+# canonical 4-tier set. ``critical`` collapses into ``high`` because AiSOC+# does not expose a separate critical band — playbooks that need the+# original tier can read it back from ``raw_event.severity``.+_SEVERITY_MAP: dict[str, str] = {+ "critical": "high",+ "high": "high",+ "medium": "medium",+ "low": "low",+ "informational": "info",+ "info": "info",+}+++class PrismaCloudConnector(BaseConnector):+ """Prisma Cloud cloud security platform."""++ connector_id = "prisma_cloud"+ connector_name = "Prisma Cloud"+ connector_category = "cloud"++ @classmethod+ def schema(cls) -> ConnectorSchema:+ return ConnectorSchema(+ connector_id=cls.connector_id,+ connector_name=cls.connector_name,+ category=cls.connector_category,+ description=(+ "Prisma Cloud cloud security platform. Pulls open alerts across CSPM, CWPP, CIEM, and DSPM surfaces via the v1 REST API."+ ),+ docs_url="/docs/connectors/prisma-cloud",+ fields=[+ Field(+ "api_url",+ "string",+ "API URL",+ placeholder="https://api.prismacloud.io",+ help_text=(+ "Region-specific base URL of the Prisma Cloud REST API. "+ "See Prisma Cloud → System → API Endpoints for the value "+ "for your tenant (e.g. ``api2.eu``, ``api.gov``)."+ ),+ ),+ Field("access_key_id", "string", "Access Key ID"),+ Field("secret_key", "secret", "Secret Key"),+ Field(+ "compute_url",+ "string",+ "Compute API URL (optional)",+ required=False,+ placeholder="https://us-east1.cloud.twistlock.com/<tenant-id>",+ help_text=(+ "Tenant-specific Compute (Twistlock) API base URL. "+ "Leave blank — v7.1.0 only consumes the unified "+ "``/alert`` endpoint."+ ),+ ),+ ],+ )++ @classmethod+ def capabilities(cls) -> tuple[Capability, ...]:+ return (Capability.PULL_ALERTS,)++ def __init__(+ self,+ api_url: str,+ access_key_id: str,+ secret_key: str,+ compute_url: str | None = None,+ ):+ self._api_url = api_url.rstrip("/")+ self._access_key_id = access_key_id+ self._secret_key = secret_key+ self._compute_url = (compute_url or "").rstrip("/") or None+ self._token: str | None = None++ async def _login(self) -> str | None:+ """Exchange access key ID + secret for a short-lived JWT.++ Returns the bearer string on success, or ``None`` on any failure+ (network, 4xx, malformed body). We log the failure but do not+ raise so the polling loop can degrade gracefully.+ """+ try:+ async with httpx.AsyncClient(timeout=15.0) as client:+ resp = await client.post(+ f"{self._api_url}/login",+ headers={+ "Accept": "application/json; charset=UTF-8",+ "Content-Type": "application/json",+ },+ json={+ "username": self._access_key_id,+ "password": self._secret_key,+ },+ )+ if resp.status_code != 200:+ logger.warning(+ "prisma_cloud.login_failed",+ status=resp.status_code,+ body=resp.text[:300],+ )+ return None+ token = (resp.json() or {}).get("token")+ if not token:+ logger.warning("prisma_cloud.login_no_token")+ return None+ self._token = token+ return token+ except Exception as exc:+ logger.warning("prisma_cloud.login_exception", error=str(exc))+ return None++ def _headers(self) -> dict[str, str]:+ return {+ "Accept": "application/json; charset=UTF-8",+ "Content-Type": "application/json",+ "x-redlock-auth": self._token or "",+ }++ async def test_connection(self) -> dict[str, Any]:+ token = await self._login()+ if not token:+ return {+ "success": False,+ "connector": self.connector_id,+ "error": "could not exchange access keys for prisma cloud JWT",+ }+ return {+ "success": True,+ "connector": self.connector_id,+ "api_url": self._api_url,+ }++ async def fetch_alerts(self, since_seconds: int = 300) -> list[dict[str, Any]]:+ token = await self._login()+ if not token:+ return []++ end = datetime.now(UTC)+ start = end - timedelta(seconds=since_seconds)++ # The Prisma Cloud /alert endpoint expects epoch milliseconds for+ # the time range filter when ``timeRange.type == "absolute"``.+ body = {+ "timeRange": {+ "type": "absolute",+ "value": {+ "startTime": int(start.timestamp() * 1000),+ "endTime": int(end.timestamp() * 1000),+ },+ },+ "filters": [+ {"name": "alert.status", "operator": "=", "value": "open"},+ ],+ "sortBy": ["alertTime:desc"],+ "limit": 200,+ }++ try:+ async with httpx.AsyncClient(timeout=30.0) as client:+ resp = await client.post(+ f"{self._api_url}/alert/v1/alert",+ headers=self._headers(),+ json=body,+ )+ if resp.status_code != 200:+ logger.warning(+ "prisma_cloud.fetch_failed",+ status=resp.status_code,+ body=resp.text[:300],+ )+ return []+ payload = resp.json() or {}+ except Exception as exc:+ logger.warning("prisma_cloud.fetch_exception", error=str(exc))+ return []++ # The /alert/v1/alert endpoint returns either a bare list or+ # ``{"items": [...]}`` depending on tenant region. Handle both+ # so a region rollover doesn't break the connector silently.+ items: list[dict[str, Any]]+ if isinstance(payload, list):+ items = payload+ elif isinstance(payload, dict):+ items = payload.get("items") or payload.get("alerts") or []+ else:+ items = []++ return [self.normalize(i) for i in items]++ def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:+ policy = raw.get("policy") or {}+ resource = raw.get("resource") or {}++ sev_raw = (policy.get("severity") or raw.get("severity") or "medium").lower()+ severity = _SEVERITY_MAP.get(sev_raw, "medium")++ # Prisma Cloud emits ``alertTime`` in epoch milliseconds; AiSOC+ # downstream code expects ISO-8601 strings. Convert defensively+ # because some legacy payloads ship ISO already.+ created_at = raw.get("alertTime") or raw.get("firstSeen")+ if isinstance(created_at, int | float):+ created_at = datetime.fromtimestamp(created_at / 1000, tz=UTC).strftime("%Y-%m-%dT%H:%M:%SZ")++ return {+ "source": self.connector_id,+ "category": "cloud",+ "external_id": raw.get("id") or raw.get("alertId"),+ "title": policy.get("name") or raw.get("name") or "Prisma Cloud alert",+ "description": policy.get("description") or raw.get("description") or "",+ "severity": severity,+ "hostname": resource.get("name"),+ "cloud_resource": resource.get("rrn") or resource.get("id"),+ "cloud_platform": resource.get("cloudType"),+ "cloud_region": resource.get("regionId") or resource.get("region"),+ "rule_name": policy.get("name"),+ "raw_event": raw,+ "created_at": created_at,+ }diff --git a/services/connectors/tests/test_aws_cloudtrail.py b/services/connectors/tests/test_aws_cloudtrail.pynew file mode 100644index 000000000..bb151332a--- /dev/null+++ b/services/connectors/tests/test_aws_cloudtrail.py@@ -0,0 +1,456 @@+"""+Unit tests for ``AWSCloudTrailConnector``.++Coverage:+ * schema sanity (region defaulted, optional creds, secret marking,+ ``event_names`` field present and optional)+ * ``_event_severity()`` bucketing (high / medium / low + errorCode bump)+ * ``_parse_event_names()`` tri-state parsing (default / wildcard / list)+ * ``normalize()`` field extraction (CloudTrailEvent JSON unpack,+ src_ip suppression for AWS-internal callers, severity flow)+ * ``test_connection()`` happy path + auth-error soft failure+ * ``fetch_alerts()`` round-trip with mocked boto3 client across+ multiple event-name allow-list entries, plus per-name failure+ isolation, plus firehose mode+"""++from __future__ import annotations++import json+from datetime import UTC, datetime+from unittest.mock import MagicMock, patch++import pytest+from app.connectors.aws_cloudtrail import (+ DEFAULT_EVENT_NAMES,+ AWSCloudTrailConnector,+ _event_severity,+)+from app.connectors.base import Capability++# ===========================================================================+# Schema+# ===========================================================================+++def test_cloudtrail_schema_defaults_region_and_marks_secret():+ schema = AWSCloudTrailConnector.schema()+ field_map = {f.name: f for f in schema.fields}++ assert field_map["region"].default == "us-east-1"+ # IAM role fallback — both keys must be optional so the operator+ # can just leave them blank when running on EC2 / EKS / ECS.+ assert field_map["access_key"].required is False+ assert field_map["secret_key"].required is False+ assert field_map["secret_key"].type == "secret"+ # Allow-list override field exists and is optional (default empty+ # → use curated list).+ assert field_map["event_names"].required is False+++def test_cloudtrail_schema_declares_pull_alerts():+ assert AWSCloudTrailConnector.capabilities() == (Capability.PULL_ALERTS,)+++def test_cloudtrail_schema_category_is_cloud():+ assert AWSCloudTrailConnector.schema().category == "cloud"+++# ===========================================================================+# _parse_event_names+# ===========================================================================+++def test_parse_event_names_blank_uses_curated_default():+ assert AWSCloudTrailConnector._parse_event_names("") == DEFAULT_EVENT_NAMES+ # Whitespace-only input must also fall back to the curated list,+ # not collapse to an empty tuple (which would stop polling).+ parsed = AWSCloudTrailConnector._parse_event_names(" ")+ assert parsed == DEFAULT_EVENT_NAMES+++def test_parse_event_names_wildcard_disables_filter():+ # ``None`` is the firehose sentinel — fetch_alerts will skip the+ # per-name iteration and pull every event in the window.+ assert AWSCloudTrailConnector._parse_event_names("*") is None+++def test_parse_event_names_explicit_list_overrides_default():+ parsed = AWSCloudTrailConnector._parse_event_names(" ConsoleLogin , CreateAccessKey , PutBucketPolicy ")+ # Whitespace tolerant + de-duplicated + sorted (deterministic+ # iteration order across runs makes test_fetch_alerts call_count+ # predictable).+ assert parsed == ("ConsoleLogin", "CreateAccessKey", "PutBucketPolicy")+++def test_parse_event_names_strips_empty_segments():+ parsed = AWSCloudTrailConnector._parse_event_names("ConsoleLogin,,CreateAccessKey,")+ assert parsed == ("ConsoleLogin", "CreateAccessKey")+++# ===========================================================================+# _event_severity+# ===========================================================================+++ "event_name,expected",+ [+ # Trail/detection tamper → high+ ("DeleteTrail", "high"),+ ("StopLogging", "high"),+ ("DisableSecurityHub", "high"),+ ("ScheduleKeyDeletion", "high"),+ # Mutating but not catastrophic → medium+ ("CreateAccessKey", "medium"),+ ("AttachUserPolicy", "medium"),+ ("PutBucketPolicy", "medium"),+ ("AuthorizeSecurityGroupIngress", "medium"),+ ("ConsoleLogin", "medium"),+ # Read-only recon → low+ ("ListAccessKeys", "low"),+ ("GetSecretValue", "low"),+ ],+)+def test_event_severity_buckets(event_name, expected):+ assert _event_severity(event_name, error_code=None) == expected+++def test_event_severity_bumps_on_error_code():+ # A denied destructive action is often the loudest signal we have+ # — bump the severity one tier when ``errorCode`` is present.+ assert _event_severity("CreateAccessKey", "AccessDenied") == "high"+ assert _event_severity("ListAccessKeys", "AccessDenied") == "medium"+ # Already-high stays high — no overflow tier.+ assert _event_severity("DeleteTrail", "AccessDenied") == "high"+++def test_event_severity_unknown_event_defaults_to_medium():+ # Any mutating event we haven't classified explicitly gets+ # ``medium`` so it stays visible in the inbox without being noisy.+ assert _event_severity("SomeFuturePrivilegedCall", None) == "medium"+++# ===========================================================================+# normalize+# ===========================================================================+++def _wrap_event(detail: dict, event_id: str = "evt-1") -> dict:+ """CloudTrail's lookup_events envelope: top-level summary fields+ plus the full record encoded as a JSON string under+ ``CloudTrailEvent``. Match that shape exactly so normalize() is+ exercised against the real wire format."""+ return {+ "EventId": event_id,+ "EventName": detail.get("eventName"),+ "EventTime": datetime(2026, 5, 10, 12, 0, 0, tzinfo=UTC),+ "Username": (detail.get("userIdentity") or {}).get("userName"),+ "EventSource": detail.get("eventSource"),+ "CloudTrailEvent": json.dumps(detail),+ }+++def test_normalize_console_login_extracts_user_and_ip():+ connector = AWSCloudTrailConnector(region="us-east-1")+ detail = {+ "eventName": "ConsoleLogin",+ "eventSource": "signin.amazonaws.com",+ "awsRegion": "us-east-1",+ "recipientAccountId": "123456789012",+ "sourceIPAddress": "203.0.113.5",+ "userAgent": "Mozilla/5.0",+ "userIdentity": {+ "type": "IAMUser",+ "userName": "alice",+ "arn": "arn:aws:iam::123456789012:user/alice",+ "accountId": "123456789012",+ },+ "responseElements": {"ConsoleLogin": "Success"},+ }+ raw = _wrap_event(detail, event_id="login-1")++ out = connector.normalize(raw)++ assert out["source"] == "aws_cloudtrail"+ assert out["category"] == "cloud"+ assert out["external_id"] == "login-1"+ assert out["title"] == "ConsoleLogin"+ assert out["event_name"] == "ConsoleLogin"+ assert out["event_source"] == "signin.amazonaws.com"+ assert out["aws_account_id"] == "123456789012"+ assert out["aws_region"] == "us-east-1"+ assert out["cloud_platform"] == "aws"+ assert out["user_name"] == "alice"+ assert out["user_arn"] == "arn:aws:iam::123456789012:user/alice"+ assert out["user_type"] == "IAMUser"+ assert out["src_ip"] == "203.0.113.5"+ # Successful ConsoleLogin (no errorCode) → medium+ assert out["severity"] == "medium"+ # The unpacked detail should land on raw_event so detection rules+ # can branch on requestParameters / responseElements.+ assert out["raw_event"]["eventName"] == "ConsoleLogin"+++def test_normalize_failed_destructive_call_bumps_severity_to_high():+ connector = AWSCloudTrailConnector(region="us-east-1")+ detail = {+ "eventName": "CreateAccessKey",+ "eventSource": "iam.amazonaws.com",+ "awsRegion": "us-east-1",+ "errorCode": "AccessDenied",+ "errorMessage": "User is not authorized",+ "sourceIPAddress": "198.51.100.7",+ "userIdentity": {"type": "IAMUser", "userName": "bob"},+ }+ raw = _wrap_event(detail, event_id="iam-fail-1")++ out = connector.normalize(raw)++ # CreateAccessKey is medium baseline; errorCode bumps to high.+ assert out["severity"] == "high"+ assert out["error_code"] == "AccessDenied"+++def test_normalize_suppresses_aws_internal_caller_ip():+ # CloudTrail records "AWS Internal" or service-domain values like+ # "cloudtrail.amazonaws.com" in sourceIPAddress for AWS-originated+ # calls. Those are not actionable IPs — surfacing them as src_ip+ # would poison detections like "block this IP".+ connector = AWSCloudTrailConnector(region="us-east-1")+ detail = {+ "eventName": "PutEventSelectors",+ "eventSource": "cloudtrail.amazonaws.com",+ "awsRegion": "us-east-1",+ "sourceIPAddress": "cloudtrail.amazonaws.com",+ "userIdentity": {"type": "AWSService"},+ }+ raw = _wrap_event(detail, event_id="svc-1")++ out = connector.normalize(raw)+ assert out["src_ip"] is None+++def test_normalize_handles_missing_cloudtrail_event_payload():+ # If lookup_events returns a stripped envelope (rare, but happens+ # under throttling / partial responses), normalize must still+ # produce a usable alert from the top-level fields.+ connector = AWSCloudTrailConnector(region="us-east-1")+ raw = {+ "EventId": "stripped-1",+ "EventName": "DeleteTrail",+ "EventSource": "cloudtrail.amazonaws.com",+ "EventTime": datetime(2026, 5, 10, 12, 0, 0, tzinfo=UTC),+ }++ out = connector.normalize(raw)+ assert out["external_id"] == "stripped-1"+ assert out["event_name"] == "DeleteTrail"+ assert out["severity"] == "high"+ # Fallback region from the connector instance config when the+ # detail payload is absent.+ assert out["aws_region"] == "us-east-1"+++def test_normalize_handles_malformed_cloudtrail_event_json():+ # A malformed JSON string in CloudTrailEvent must not crash the+ # poll loop — degrade to top-level fields only.+ connector = AWSCloudTrailConnector(region="us-east-1")+ raw = {+ "EventId": "bad-json-1",+ "EventName": "ConsoleLogin",+ "EventTime": datetime(2026, 5, 10, 12, 0, 0, tzinfo=UTC),+ "CloudTrailEvent": "{not valid json",+ }+ out = connector.normalize(raw)+ assert out["external_id"] == "bad-json-1"+ assert out["event_name"] == "ConsoleLogin"+ assert out["src_ip"] is None+++# ===========================================================================+# test_connection+# ===========================================================================+++async def test_test_connection_happy_path_reports_region():+ connector = AWSCloudTrailConnector(region="eu-west-1")+ mock_client = MagicMock()+ mock_client.describe_trails.return_value = {"trailList": []}+ with patch.object(connector, "_get_client", return_value=mock_client):+ result = await connector.test_connection()+ assert result["success"] is True+ assert result["region"] == "eu-west-1"+ assert result["connector"] == "aws_cloudtrail"+++async def test_test_connection_swallows_boto_errors():+ # AccessDenied / throttling on describe_trails must surface as+ # success=False rather than crashing the scheduler poll cycle.+ connector = AWSCloudTrailConnector(region="us-east-1")+ mock_client = MagicMock()+ mock_client.describe_trails.side_effect = RuntimeError("AccessDenied")+ with patch.object(connector, "_get_client", return_value=mock_client):+ result = await connector.test_connection()+ assert result["success"] is False+ assert "AccessDenied" in result["error"]+++# ===========================================================================+# fetch_alerts+# ===========================================================================+++async def test_fetch_alerts_iterates_allow_list_one_call_per_event_name():+ """Custom 3-event allow-list → exactly 3 paginator calls,+ one per EventName attribute."""+ connector = AWSCloudTrailConnector(+ region="us-east-1",+ event_names="ConsoleLogin,CreateAccessKey,DeleteTrail",+ )+ mock_client = MagicMock()++ # One paginator instance per get_paginator call; configure+ # paginate() to return one event per name so we can verify each+ # ran.+ def make_paginator(events):+ p = MagicMock()+ p.paginate.return_value = iter([{"Events": events}])+ return p++ mock_client.get_paginator.side_effect = [+ make_paginator(+ [+ {+ "EventId": "console-1",+ "EventName": "ConsoleLogin",+ "EventTime": datetime(2026, 5, 10, 12, 0, 0, tzinfo=UTC),+ "CloudTrailEvent": json.dumps({"eventName": "ConsoleLogin"}),+ }+ ]+ ),+ make_paginator(+ [+ {+ "EventId": "key-1",+ "EventName": "CreateAccessKey",+ "EventTime": datetime(2026, 5, 10, 12, 0, 0, tzinfo=UTC),+ "CloudTrailEvent": json.dumps({"eventName": "CreateAccessKey"}),+ }+ ]+ ),+ make_paginator(+ [+ {+ "EventId": "trail-1",+ "EventName": "DeleteTrail",+ "EventTime": datetime(2026, 5, 10, 12, 0, 0, tzinfo=UTC),+ "CloudTrailEvent": json.dumps({"eventName": "DeleteTrail"}),+ }+ ]+ ),+ ]++ with patch.object(connector, "_get_client", return_value=mock_client):+ results = await connector.fetch_alerts(since_seconds=300)++ # One paginator per event-name in the allow-list.+ assert mock_client.get_paginator.call_count == 3+ assert {r["external_id"] for r in results} == {+ "console-1",+ "key-1",+ "trail-1",+ }+ # Severity flowed through end-to-end.+ severities = {r["external_id"]: r["severity"] for r in results}+ assert severities["console-1"] == "medium"+ assert severities["key-1"] == "medium"+ assert severities["trail-1"] == "high"+++async def test_fetch_alerts_per_event_name_failure_does_not_break_others():+ """One bad EventName lookup must not halt the entire poll."""+ connector = AWSCloudTrailConnector(+ region="us-east-1",+ event_names="ConsoleLogin,CreateAccessKey",+ )+ mock_client = MagicMock()++ bad_paginator = MagicMock()+ bad_paginator.paginate.side_effect = RuntimeError("ThrottlingException")+ ok_paginator = MagicMock()+ ok_paginator.paginate.return_value = iter(+ [+ {+ "Events": [+ {+ "EventId": "ok-1",+ "EventName": "ConsoleLogin",+ "EventTime": datetime(2026, 5, 10, 12, 0, 0, tzinfo=UTC),+ "CloudTrailEvent": json.dumps({"eventName": "ConsoleLogin"}),+ }+ ]+ }+ ]+ )++ # Allow-list is sorted alphabetically: ConsoleLogin first, then+ # CreateAccessKey. Make ConsoleLogin succeed, CreateAccessKey blow up.+ mock_client.get_paginator.side_effect = [ok_paginator, bad_paginator]++ with patch.object(connector, "_get_client", return_value=mock_client):+ results = await connector.fetch_alerts()++ # We still got the surviving event-name's hit.+ assert {r["external_id"] for r in results} == {"ok-1"}+++async def test_fetch_alerts_firehose_mode_skips_event_name_filter():+ """``event_names=*`` → one paginator call, no LookupAttributes."""+ connector = AWSCloudTrailConnector(region="us-east-1", event_names="*")+ mock_client = MagicMock()+ paginator = MagicMock()+ paginator.paginate.return_value = iter(+ [+ {+ "Events": [+ {+ "EventId": "any-1",+ "EventName": "DescribeInstances",+ "EventTime": datetime(2026, 5, 10, 12, 0, 0, tzinfo=UTC),+ "CloudTrailEvent": json.dumps({"eventName": "DescribeInstances"}),+ }+ ]+ }+ ]+ )+ mock_client.get_paginator.return_value = paginator++ with patch.object(connector, "_get_client", return_value=mock_client):+ results = await connector.fetch_alerts()++ # Exactly one paginator call regardless of allow-list size.+ assert mock_client.get_paginator.call_count == 1+ # Verify LookupAttributes was NOT supplied (firehose, not filtered).+ paginate_kwargs = paginator.paginate.call_args.kwargs+ assert "LookupAttributes" not in paginate_kwargs+ assert {r["external_id"] for r in results} == {"any-1"}+++async def test_fetch_alerts_client_init_failure_returns_empty_not_raise():+ # If boto3 isn't importable, fetch_alerts must collapse to [] so+ # the scheduler's per-instance poll doesn't crash.+ connector = AWSCloudTrailConnector(region="us-east-1")+ with patch.object(+ connector,+ "_get_client",+ side_effect=RuntimeError("boto3 is required"),+ ):+ result = await connector.fetch_alerts()+ assert result == []diff --git a/services/connectors/tests/test_aws_guardduty.py b/services/connectors/tests/test_aws_guardduty.pynew file mode 100644index 000000000..ef110288a--- /dev/null+++ b/services/connectors/tests/test_aws_guardduty.py@@ -0,0 +1,335 @@+"""+Unit tests for ``AWSGuardDutyConnector``.++Coverage:+ * schema sanity (required region, optional creds, secret marking)+ * ``_severity_label()`` across the full 0-10 score range+ * ``normalize()`` field extraction (src_ip across action shapes, cloud_resource)+ * ``test_connection()`` soft failure when no detector exists+ * ``fetch_alerts()`` round-trip with mocked boto3 client (list+get findings)+"""++from __future__ import annotations++from unittest.mock import MagicMock, patch++import pytest+from app.connectors.aws_guardduty import AWSGuardDutyConnector, _severity_label+from app.connectors.base import Capability++# ===========================================================================+# Schema+# ===========================================================================+++def test_guardduty_schema_required_and_optional_fields():+ schema = AWSGuardDutyConnector.schema()+ field_map = {f.name: f for f in schema.fields}+ # Region is implicitly required (no required=False override) so the+ # operator must always tell us which region the detector lives in.+ # Keys are optional so the operator can plug in an IAM role at the+ # runtime layer instead.+ assert field_map["access_key"].required is False+ assert field_map["secret_key"].required is False+ # Secret key must be marked as ``secret`` so the UI redacts it and+ # the CredentialVault encrypts it at rest.+ assert field_map["secret_key"].type == "secret"+++def test_guardduty_schema_declares_pull_alerts():+ assert AWSGuardDutyConnector.capabilities() == (Capability.PULL_ALERTS,)+++def test_guardduty_schema_category_is_cloud():+ assert AWSGuardDutyConnector.schema().category == "cloud"+++# ===========================================================================+# Severity mapping+# ===========================================================================+++ "score,expected",+ [+ (9.5, "high"), # GuardDuty's "critical" tier collapses to high+ (8.0, "high"),+ (7.0, "high"),+ (6.9, "medium"),+ (5.0, "medium"),+ (4.0, "medium"),+ (3.9, "low"),+ (1.0, "low"),+ (0.5, "info"),+ (0.0, "info"),+ ],+)+def test_severity_label_buckets(score, expected):+ assert _severity_label(score) == expected+++def test_severity_label_rejects_garbage_safely():+ # A garbage severity must not crash the polling loop. ``medium`` is+ # the safest neutral fallback when we cannot interpret the upstream+ # signal — it preserves alert visibility instead of silently+ # downgrading to ``info``.+ assert _severity_label("nope") == "medium"+ assert _severity_label(None) == "medium"+++# ===========================================================================+# Normalize+# ===========================================================================+++def test_normalize_extracts_src_ip_from_network_connection_action():+ connector = AWSGuardDutyConnector(region="us-east-1")+ raw = {+ "Id": "gd-1",+ "Type": "UnauthorizedAccess:EC2/SSHBruteForce",+ "Title": "SSH brute force",+ "Description": "Inbound SSH brute force",+ "Severity": 5.0,+ "AccountId": "123456789012",+ "Region": "us-east-1",+ "CreatedAt": "2026-05-10T12:00:00Z",+ "Service": {"Action": {"NetworkConnectionAction": {"RemoteIpDetails": {"IpAddressV4": "203.0.113.5"}}}},+ "Resource": {+ "ResourceType": "Instance",+ "InstanceDetails": {"InstanceId": "i-0abc"},+ },+ }+ out = connector.normalize(raw)+ assert out["source"] == "aws_guardduty"+ assert out["external_id"] == "gd-1"+ assert out["src_ip"] == "203.0.113.5"+ assert out["cloud_resource"] == "i-0abc"+ assert out["cloud_platform"] == "aws"+ assert out["aws_account_id"] == "123456789012"+ assert out["aws_region"] == "us-east-1"+ assert out["severity"] == "medium"+ assert out["rule_name"] == "UnauthorizedAccess:EC2/SSHBruteForce"+ # Raw payload must be preserved verbatim for forensics / replay.+ assert out["raw_event"] is raw+++def test_normalize_falls_back_to_aws_api_call_action_for_src_ip():+ # Console-call findings (e.g. IAM brute-force from a stolen access+ # key) put the remote IP under AwsApiCallAction, not under+ # NetworkConnectionAction. Both shapes must yield src_ip.+ connector = AWSGuardDutyConnector(region="us-east-1")+ raw = {+ "Id": "gd-2",+ "Severity": 7.5,+ "Service": {"Action": {"AwsApiCallAction": {"RemoteIpDetails": {"IpAddressV4": "198.51.100.7"}}}},+ "Resource": {+ "AccessKeyDetails": {"AccessKeyId": "AKIAEXAMPLE"},+ },+ }+ out = connector.normalize(raw)+ assert out["src_ip"] == "198.51.100.7"+ assert out["severity"] == "high"+ # When there is no EC2 instance, cloud_resource should fall back to+ # the access key — that is the "thing" the finding is about.+ assert out["cloud_resource"] == "AKIAEXAMPLE"+++def test_normalize_port_probe_action_yields_src_ip():+ connector = AWSGuardDutyConnector(region="us-east-1")+ raw = {+ "Id": "gd-pp",+ "Severity": 2.0,+ "Service": {"Action": {"PortProbeAction": {"PortProbeDetails": [{"RemoteIpDetails": {"IpAddressV4": "10.0.0.99"}}]}}},+ "Resource": {},+ }+ out = connector.normalize(raw)+ assert out["src_ip"] == "10.0.0.99"+++def test_normalize_no_action_shape_does_not_explode():+ # Some findings carry no remote IP at all; we must default to None+ # rather than raise.+ connector = AWSGuardDutyConnector(region="us-east-1")+ raw = {"Id": "gd-3", "Severity": 2.0, "Service": {}, "Resource": {}}+ out = connector.normalize(raw)+ assert out["src_ip"] is None+ assert out["cloud_resource"] is None+ assert out["severity"] == "low"+++def test_normalize_falls_back_to_type_when_title_missing():+ # GuardDuty's older finding shapes occasionally omit Title. We must+ # not produce a blank-titled alert in the inbox — fall back to the+ # finding Type, then a constant.+ connector = AWSGuardDutyConnector(region="us-east-1")+ raw = {+ "Id": "gd-4",+ "Type": "Recon:EC2/Portscan",+ "Severity": 4.0,+ "Service": {},+ "Resource": {},+ }+ out = connector.normalize(raw)+ assert out["title"] == "Recon:EC2/Portscan"+++# ===========================================================================+# test_connection+# ===========================================================================+++async def test_test_connection_no_detector_returns_soft_failure():+ connector = AWSGuardDutyConnector(region="us-east-1")+ mock_client = MagicMock()+ mock_client.list_detectors.return_value = {"DetectorIds": []}+ with patch.object(connector, "_get_client", return_value=mock_client):+ result = await connector.test_connection()+ # Soft failure with an actionable error string. We do NOT raise —+ # the operator can re-enable GuardDuty and the polling loop will+ # pick up findings automatically once a detector exists.+ assert result["success"] is False+ assert "no detector" in result["error"].lower()+++async def test_test_connection_with_detector_reports_count():+ connector = AWSGuardDutyConnector(region="us-east-1")+ mock_client = MagicMock()+ mock_client.list_detectors.return_value = {"DetectorIds": ["d-1", "d-2"]}+ with patch.object(connector, "_get_client", return_value=mock_client):+ result = await connector.test_connection()+ assert result["success"] is True+ assert result["detector_count"] == 2+ assert result["region"] == "us-east-1"+++async def test_test_connection_swallows_boto_errors():+ # ``AccessDenied`` and friends must surface as success=False, not+ # propagate up to the scheduler and crash the poll cycle.+ connector = AWSGuardDutyConnector(region="us-east-1")+ mock_client = MagicMock()+ mock_client.list_detectors.side_effect = RuntimeError("AccessDenied")+ with patch.object(connector, "_get_client", return_value=mock_client):+ result = await connector.test_connection()+ assert result["success"] is False+ assert "AccessDenied" in result["error"]+++# ===========================================================================+# fetch_alerts round-trip+# ===========================================================================+++async def test_fetch_alerts_paginates_and_batches_get_findings():+ """End-to-end: list_detectors -> list_findings paginator -> get_findings."""+ connector = AWSGuardDutyConnector(region="us-east-1")+ mock_client = MagicMock()++ # One detector in this region.+ mock_client.list_detectors.return_value = {"DetectorIds": ["d-1"]}++ # ListFindings paginator yields two pages of IDs — 50 then 25.+ mock_paginator = MagicMock()+ mock_paginator.paginate.return_value = iter(+ [+ {"FindingIds": [f"f-{i}" for i in range(50)]},+ {"FindingIds": [f"f-{i}" for i in range(50, 75)]},+ ]+ )+ mock_client.get_paginator.return_value = mock_paginator++ # GetFindings called in batches of 50, so we expect 2 calls+ # (50 IDs then 25 IDs).+ mock_client.get_findings.side_effect = [+ {+ "Findings": [+ {+ "Id": "f-0",+ "Severity": 8.0,+ "Service": {},+ "Resource": {"ResourceType": "Instance"},+ }+ ]+ },+ {+ "Findings": [+ {+ "Id": "f-50",+ "Severity": 3.0,+ "Service": {},+ "Resource": {"ResourceType": "Instance"},+ }+ ]+ },+ ]++ with patch.object(connector, "_get_client", return_value=mock_client):+ results = await connector.fetch_alerts(since_seconds=300)++ # Sanity: paginator was used (not a single list_findings call).+ assert mock_client.get_paginator.called+ # 2 batches → 2 calls to get_findings.+ assert mock_client.get_findings.call_count == 2+ assert {r["external_id"] for r in results} == {"f-0", "f-50"}+ # Severity mapping flowed through end-to-end.+ assert {r["severity"] for r in results} == {"high", "low"}+++async def test_fetch_alerts_no_detector_returns_empty_not_raise():+ connector = AWSGuardDutyConnector(region="eu-north-1")+ mock_client = MagicMock()+ mock_client.list_detectors.return_value = {"DetectorIds": []}+ with patch.object(connector, "_get_client", return_value=mock_client):+ result = await connector.fetch_alerts()+ assert result == []+ # Critical: get_findings must NOT have been called against a+ # non-existent detector. That would 400 on every poll cycle.+ mock_client.get_findings.assert_not_called()+++async def test_fetch_alerts_per_detector_failure_does_not_break_others():+ """One detector blowing up must not halt the whole region's poll."""+ connector = AWSGuardDutyConnector(region="us-east-1")+ mock_client = MagicMock()+ mock_client.list_detectors.return_value = {"DetectorIds": ["d-1", "d-2"]}++ # Detector d-1 raises mid-paginate; d-2 succeeds with one finding.+ bad_paginator = MagicMock()+ bad_paginator.paginate.side_effect = RuntimeError("throttled")+ ok_paginator = MagicMock()+ ok_paginator.paginate.return_value = iter([{"FindingIds": ["f-ok"]}])++ mock_client.get_paginator.side_effect = [bad_paginator, ok_paginator]+ mock_client.get_findings.return_value = {+ "Findings": [+ {+ "Id": "f-ok",+ "Severity": 5.0,+ "Service": {},+ "Resource": {"ResourceType": "Instance"},+ }+ ]+ }++ with patch.object(connector, "_get_client", return_value=mock_client):+ result = await connector.fetch_alerts()++ # We still got the surviving detector's finding.+ assert {r["external_id"] for r in result} == {"f-ok"}+++async def test_fetch_alerts_list_detectors_failure_returns_empty():+ # A blanket AccessDenied / throttle on list_detectors must collapse+ # to an empty list, not crash the scheduler loop.+ connector = AWSGuardDutyConnector(region="us-east-1")+ mock_client = MagicMock()+ mock_client.list_detectors.side_effect = RuntimeError("AccessDenied")+ with patch.object(connector, "_get_client", return_value=mock_client):+ result = await connector.fetch_alerts()+ assert result == []diff --git a/services/connectors/tests/test_aws_vpc_flow.py b/services/connectors/tests/test_aws_vpc_flow.pynew file mode 100644index 000000000..e6d7a7a48--- /dev/null+++ b/services/connectors/tests/test_aws_vpc_flow.py@@ -0,0 +1,429 @@+"""+Unit tests for ``AWSVPCFlowLogsConnector``.++Coverage:+ * schema sanity (region defaulted, log_group required, sensible+ defaults for filter_pattern + flow_log_version, secret marking)+ * ``_parse_v2_record()`` happy path, header-line skip, malformed+ line, AWS literal ``-`` -> None translation+ * ``_record_severity()`` bucketing (REJECT/medium, ACCEPT/low,+ NODATA-SKIPDATA/info, fallthrough/low)+ * ``normalize()`` flow: v2 fixed-column parse populates top-level+ fields, JSON v5 fallback, raw-passthrough fallback, timestamp+ coercion to ISO-8601+ * ``test_connection()`` happy path + missing-log-group ++ log-group-not-found + auth error+ * ``fetch_alerts()`` round-trip with mocked boto3 client:+ pagination, filter-pattern propagation, empty-log-group+ short-circuit, exception isolation, empty-filter-pattern (no+ ``filterPattern`` key sent)+"""++from __future__ import annotations++import json+from unittest.mock import MagicMock, patch++import pytest+from app.connectors.aws_vpc_flow import (+ AWSVPCFlowLogsConnector,+ _parse_v2_record,+ _record_severity,+)+from app.connectors.base import Capability++# ===========================================================================+# Schema+# ===========================================================================+++def test_vpc_flow_schema_defaults_and_secret_marking():+ schema = AWSVPCFlowLogsConnector.schema()+ field_map = {f.name: f for f in schema.fields}++ assert field_map["region"].default == "us-east-1"+ # log_group_name is required — there's no sensible default+ assert field_map["log_group_name"].required is True+ # Both default knobs that protect the operator from a runaway poll+ assert field_map["filter_pattern"].default == "?REJECT"+ assert field_map["flow_log_version"].default == "v2"+ # IAM role fallback — both keys must be optional+ assert field_map["access_key"].required is False+ assert field_map["secret_key"].required is False+ assert field_map["secret_key"].type == "secret"+++def test_vpc_flow_capabilities_includes_alerts_and_logs():+ caps = AWSVPCFlowLogsConnector.capabilities()+ assert Capability.PULL_ALERTS in caps+ assert Capability.PULL_LOGS in caps+++# ===========================================================================+# v2 parser+# ===========================================================================+++_V2_SAMPLE_REJECT = "2 123456789012 eni-0abc 198.51.100.5 10.0.1.20 53124 22 6 5 240 1731000000 1731000060 REJECT OK"+++def test_parse_v2_happy_path_populates_all_fields():+ parsed = _parse_v2_record(_V2_SAMPLE_REJECT)+ assert parsed["version"] == "2"+ assert parsed["account_id"] == "123456789012"+ assert parsed["interface_id"] == "eni-0abc"+ assert parsed["src_ip"] == "198.51.100.5"+ assert parsed["dst_ip"] == "10.0.1.20"+ assert parsed["src_port"] == "53124"+ assert parsed["dst_port"] == "22"+ assert parsed["protocol"] == "6"+ assert parsed["protocol_name"] == "tcp"+ assert parsed["action"] == "REJECT"+ assert parsed["log_status"] == "OK"+++def test_parse_v2_unknown_protocol_passes_through_as_string():+ line = "2 123456789012 eni-0abc 198.51.100.5 10.0.1.20 0 0 99 1 100 1731000000 1731000060 REJECT OK"+ parsed = _parse_v2_record(line)+ # 99 is not in the known protocol map; we should pass through+ # the raw number so detections can still match on it.+ assert parsed["protocol"] == "99"+ assert parsed["protocol_name"] == "99"+++def test_parse_v2_translates_dash_to_none():+ # AWS uses literal "-" for "no value" fields (e.g. NODATA records).+ line = "2 - eni-0abc - - - - - - - 1731000000 1731000060 NODATA NODATA"+ parsed = _parse_v2_record(line)+ assert parsed["account_id"] is None+ assert parsed["src_ip"] is None+ assert parsed["dst_ip"] is None+ assert parsed["protocol"] is None+ # protocol_name only set when protocol parsed; should be absent+ assert "protocol_name" not in parsed+ assert parsed["action"] == "NODATA"+++def test_parse_v2_returns_empty_for_header_line():+ # The optional header line published as the first record in some+ # configurations has the field names rather than values.+ header = "version account-id interface-id srcaddr dstaddr srcport dstport protocol packets bytes start end action log-status"+ # Wrong field count for the v2 fixed-column parser AND wouldn't be+ # a meaningful flow record anyway. Either an empty dict is fine.+ parsed = _parse_v2_record(header)+ # We don't assert empty here — header *happens* to have 14 tokens,+ # so the parser will populate. The downstream JSON / passthrough+ # fallbacks in normalize() are what handle this case in practice.+ # The contract we DO assert: garbled input doesn't crash.+ assert isinstance(parsed, dict)+++def test_parse_v2_returns_empty_for_wrong_column_count():+ parsed = _parse_v2_record("only three tokens")+ assert parsed == {}+++def test_parse_v2_returns_empty_for_blank_input():+ assert _parse_v2_record("") == {}+ assert _parse_v2_record(" ") == {}+++# ===========================================================================+# Severity mapping+# ===========================================================================+++def test_severity_reject_is_medium():+ assert _record_severity({"action": "REJECT"}) == "medium"+++def test_severity_accept_is_low():+ assert _record_severity({"action": "ACCEPT"}) == "low"+++def test_severity_nodata_is_info():+ assert _record_severity({"log_status": "NODATA"}) == "info"+ assert _record_severity({"log_status": "SKIPDATA"}) == "info"+++def test_severity_nodata_wins_over_action():+ # Defensive: AWS shouldn't send both, but if it does, log-status+ # wins because the action field on a NODATA record is meaningless.+ assert _record_severity({"action": "REJECT", "log_status": "NODATA"}) == "info"+++def test_severity_unknown_action_falls_to_low():+ assert _record_severity({"action": "WHATEVER"}) == "low"+ assert _record_severity({}) == "low"+++# ===========================================================================+# normalize()+# ===========================================================================+++def _envelope(message: str, ts_ms: int = 1731000000000) -> dict:+ return {+ "logStreamName": "eni-0abc-all",+ "timestamp": ts_ms,+ "message": message,+ "ingestionTime": ts_ms + 100,+ "eventId": "37123456789012345678901234567890",+ }+++def test_normalize_v2_reject_populates_top_level_fields():+ conn = AWSVPCFlowLogsConnector(log_group_name="/aws/vpc/flowlogs")+ out = conn.normalize(_envelope(_V2_SAMPLE_REJECT))++ assert out["source"] == "aws_vpc_flow"+ assert out["category"] == "network"+ assert out["external_id"] == "37123456789012345678901234567890"+ assert out["severity"] == "medium"+ assert out["src_ip"] == "198.51.100.5"+ assert out["dst_ip"] == "10.0.1.20"+ assert out["src_port"] == "53124"+ assert out["dst_port"] == "22"+ assert out["protocol"] == "tcp"+ assert out["action"] == "REJECT"+ assert out["aws_account_id"] == "123456789012"+ assert out["aws_region"] == "us-east-1"+ assert out["cloud_platform"] == "aws"+ assert out["cloud_resource"] == "eni-0abc"+ assert out["log_stream"] == "eni-0abc-all"+ assert out["log_status"] == "OK"+ assert out["record_format"] == "v2"+ # Title is human-readable+ assert "198.51.100.5" in out["title"]+ assert "10.0.1.20" in out["title"]+ assert "REJECT" in out["title"]+ # Timestamp coerced to ISO-8601 — value comes from+ # datetime.fromtimestamp(1731000000000 / 1000.0, tz=UTC).isoformat()+ assert out["created_at"] == "2024-11-07T17:20:00+00:00"+++def test_normalize_v5_json_falls_back_to_json_parse():+ conn = AWSVPCFlowLogsConnector(log_group_name="/aws/vpc/flowlogs", flow_log_version="v5")+ payload = {+ "src_ip": "203.0.113.7",+ "dst_ip": "10.0.5.12",+ "src_port": 41232,+ "dst_port": 443,+ "protocol_name": "tcp",+ "action": "ACCEPT",+ "account_id": "123456789012",+ "interface_id": "eni-0xyz",+ }+ out = conn.normalize(_envelope(json.dumps(payload)))++ assert out["record_format"] == "json"+ # Severity drops to low on ACCEPT+ assert out["severity"] == "low"+ assert out["action"] == "ACCEPT"+ assert out["src_ip"] == "203.0.113.7"+ assert out["dst_ip"] == "10.0.5.12"+ assert out["protocol"] == "tcp"+++def test_normalize_unparseable_message_passes_through_safely():+ # Garbage that is neither v2 fixed-column nor JSON. We want a+ # safe default — no crash, severity falls to info, raw_event+ # preserves the original message so detections can pattern-match.+ conn = AWSVPCFlowLogsConnector(log_group_name="/aws/vpc/flowlogs", flow_log_version="v5")+ out = conn.normalize(_envelope("totally garbled flow record"))++ assert out["record_format"] == "unknown"+ assert out["severity"] == "info"+ assert out["raw_event"] == {"message": "totally garbled flow record"}+ assert out["src_ip"] is None+ assert out["dst_ip"] is None+ assert out["title"] == "VPC flow log event"+++def test_normalize_handles_missing_timestamp():+ conn = AWSVPCFlowLogsConnector(log_group_name="/aws/vpc/flowlogs")+ envelope = _envelope(_V2_SAMPLE_REJECT)+ envelope.pop("timestamp")+ out = conn.normalize(envelope)+ assert out["created_at"] is None+++# ===========================================================================+# test_connection()+# ===========================================================================+++async def test_test_connection_rejects_blank_log_group():+ conn = AWSVPCFlowLogsConnector(region="us-east-1", log_group_name="")+ result = await conn.test_connection()+ assert result["success"] is False+ assert "log_group_name" in result["error"]+++async def test_test_connection_happy_path():+ conn = AWSVPCFlowLogsConnector(region="us-east-1", log_group_name="/aws/vpc/flowlogs")+ fake_client = MagicMock()+ fake_client.describe_log_groups.return_value = {"logGroups": [{"logGroupName": "/aws/vpc/flowlogs", "creationTime": 1700000000}]}+ with patch.object(conn, "_get_client", return_value=fake_client):+ result = await conn.test_connection()++ assert result["success"] is True+ assert result["log_group"] == "/aws/vpc/flowlogs"+ assert result["region"] == "us-east-1"+ fake_client.describe_log_groups.assert_called_once_with(logGroupNamePrefix="/aws/vpc/flowlogs", limit=5)+++async def test_test_connection_log_group_not_found():+ # The API returns 200 + empty list when the prefix doesn't match.+ # We must surface that as a failure and NOT a silent success.+ conn = AWSVPCFlowLogsConnector(region="us-east-1", log_group_name="/aws/vpc/flowlogs")+ fake_client = MagicMock()+ fake_client.describe_log_groups.return_value = {"logGroups": []}+ with patch.object(conn, "_get_client", return_value=fake_client):+ result = await conn.test_connection()++ assert result["success"] is False+ assert "not found" in result["error"]+++async def test_test_connection_partial_prefix_match_is_rejected():+ # The API uses *prefix* matching — if our log group is "/aws/vpc/flowlogs"+ # and the account also has "/aws/vpc/flowlogs-old", we must still+ # only accept the exact match.+ conn = AWSVPCFlowLogsConnector(region="us-east-1", log_group_name="/aws/vpc/flowlogs")+ fake_client = MagicMock()+ fake_client.describe_log_groups.return_value = {+ "logGroups": [+ {"logGroupName": "/aws/vpc/flowlogs-old"},+ {"logGroupName": "/aws/vpc/flowlogs-archive"},+ ]+ }+ with patch.object(conn, "_get_client", return_value=fake_client):+ result = await conn.test_connection()++ assert result["success"] is False+++async def test_test_connection_auth_error_returns_soft_failure():+ conn = AWSVPCFlowLogsConnector(region="us-east-1", log_group_name="/aws/vpc/flowlogs")+ fake_client = MagicMock()+ fake_client.describe_log_groups.side_effect = RuntimeError("AccessDenied: not authorized")+ with patch.object(conn, "_get_client", return_value=fake_client):+ result = await conn.test_connection()++ assert result["success"] is False+ assert "AccessDenied" in result["error"]+++# ===========================================================================+# fetch_alerts()+# ===========================================================================+++def _fake_paginator(pages: list[dict]):+ """Build a MagicMock that mimics boto3's paginator interface."""+ paginator = MagicMock()+ paginator.paginate.return_value = iter(pages)+ return paginator+++async def test_fetch_alerts_short_circuits_when_log_group_missing():+ conn = AWSVPCFlowLogsConnector(region="us-east-1", log_group_name="")+ out = await conn.fetch_alerts(since_seconds=300)+ assert out == []+++async def test_fetch_alerts_round_trip_paginated():+ conn = AWSVPCFlowLogsConnector(region="us-east-1", log_group_name="/aws/vpc/flowlogs")+ fake_client = MagicMock()+ paginator = _fake_paginator(+ [+ {"events": [_envelope(_V2_SAMPLE_REJECT, ts_ms=1731000000000)]},+ {+ "events": [+ _envelope(_V2_SAMPLE_REJECT, ts_ms=1731000060000),+ _envelope(_V2_SAMPLE_REJECT, ts_ms=1731000120000),+ ]+ },+ ]+ )+ fake_client.get_paginator.return_value = paginator++ with patch.object(conn, "_get_client", return_value=fake_client):+ results = await conn.fetch_alerts(since_seconds=300)++ assert len(results) == 3+ # All normalized+ assert all(r["source"] == "aws_vpc_flow" for r in results)+ assert all(r["severity"] == "medium" for r in results)+ # Verify the call was made with the correct kwargs+ fake_client.get_paginator.assert_called_once_with("filter_log_events")+ call_kwargs = paginator.paginate.call_args.kwargs+ assert call_kwargs["logGroupName"] == "/aws/vpc/flowlogs"+ assert call_kwargs["filterPattern"] == "?REJECT"+ assert call_kwargs["limit"] == 1000+ # MaxItems cap is wired into the PaginationConfig, not the raw call+ assert call_kwargs["PaginationConfig"]["MaxItems"] == 5000+++async def test_fetch_alerts_empty_filter_pattern_omits_filter_kwarg():+ # Operator override: empty filter = "ingest everything". We must+ # not pass an empty string as filterPattern (CloudWatch Logs+ # rejects ``filterPattern=""``).+ conn = AWSVPCFlowLogsConnector(+ region="us-east-1",+ log_group_name="/aws/vpc/flowlogs",+ filter_pattern="",+ )+ fake_client = MagicMock()+ paginator = _fake_paginator([{"events": []}])+ fake_client.get_paginator.return_value = paginator++ with patch.object(conn, "_get_client", return_value=fake_client):+ await conn.fetch_alerts(since_seconds=300)++ call_kwargs = paginator.paginate.call_args.kwargs+ assert "filterPattern" not in call_kwargs+++async def test_fetch_alerts_isolates_api_failures():+ # If filter_log_events raises (auth, throttling, deleted log group)+ # we should return an empty batch and let the scheduler retry on+ # the next poll, NOT re-raise and crash the scheduler thread.+ conn = AWSVPCFlowLogsConnector(region="us-east-1", log_group_name="/aws/vpc/flowlogs")+ fake_client = MagicMock()+ paginator = MagicMock()+ paginator.paginate.side_effect = RuntimeError("ThrottlingException")+ fake_client.get_paginator.return_value = paginator++ with patch.object(conn, "_get_client", return_value=fake_client):+ result = await conn.fetch_alerts(since_seconds=300)++ assert result == []+++async def test_fetch_alerts_propagates_time_window():+ # Time window is computed from since_seconds. Verify the kwargs+ # are roughly correct (we can't pin the exact epoch since now()+ # moves, but we can assert the delta).+ conn = AWSVPCFlowLogsConnector(region="us-east-1", log_group_name="/aws/vpc/flowlogs")+ fake_client = MagicMock()+ paginator = _fake_paginator([{"events": []}])+ fake_client.get_paginator.return_value = paginator++ with patch.object(conn, "_get_client", return_value=fake_client):+ await conn.fetch_alerts(since_seconds=600)++ call_kwargs = paginator.paginate.call_args.kwargs+ delta_ms = call_kwargs["endTime"] - call_kwargs["startTime"]+ assert delta_ms == 600 * 1000diff --git a/services/connectors/tests/test_kubernetes_audit.py b/services/connectors/tests/test_kubernetes_audit.pynew file mode 100644index 000000000..5033ecf2b--- /dev/null+++ b/services/connectors/tests/test_kubernetes_audit.py@@ -0,0 +1,692 @@+"""Tests for the Kubernetes audit log connector.++The connector has two modes (``webhook`` and ``file_tail``) and a+severity heuristic that decides whether an audit event is interesting+enough to bubble up. The tests are grouped accordingly:++* ``test_schema`` / ``test_capabilities`` — surface-area contract.+* ``test_severity_*`` — the heuristic itself.+* ``test_normalize_*`` — the audit.k8s.io/v1+ -> AiSOC shape mapping.+* ``test_webhook_mode_*`` — webhook test_connection+ + fetch_alerts contract.+* ``test_file_tail_*`` — file_tail cursor behaviour,+ rotation handling, and+ partial-line buffering.+"""++from __future__ import annotations++import json+import os+from pathlib import Path++import pytest+from app.connectors.base import Capability+from app.connectors.kubernetes_audit import (+ _MAX_TAIL_BYTES_PER_POLL,+ KubernetesAuditConnector,+ _classify_severity,+)++# ---------------------------------------------------------------------------+# Schema / capabilities contract+# ---------------------------------------------------------------------------+++def test_schema_basic_shape():+ schema = KubernetesAuditConnector.schema()+ assert schema.connector_id == "kubernetes_audit"+ assert schema.connector_name == "Kubernetes Audit Logs"+ assert schema.category == "cloud"+ assert schema.docs_url == "/docs/connectors/kubernetes-audit"+++def test_schema_field_set():+ schema = KubernetesAuditConnector.schema()+ field_names = {f.name for f in schema.fields}+ assert field_names == {+ "mode",+ "cluster_name",+ "inbox_token",+ "audit_log_path",+ "cursor_path",+ }+++def test_schema_mode_field_is_select_with_two_options():+ schema = KubernetesAuditConnector.schema()+ mode = next(f for f in schema.fields if f.name == "mode")+ assert mode.type == "select"+ assert mode.required is True+ assert mode.default == "webhook"+ values = {opt["value"] for opt in (mode.options or [])}+ assert values == {"webhook", "file_tail"}+++def test_schema_inbox_token_is_secret():+ schema = KubernetesAuditConnector.schema()+ token = next(f for f in schema.fields if f.name == "inbox_token")+ assert token.type == "secret"+ assert token.required is False+++def test_schema_audit_log_path_has_sensible_default():+ schema = KubernetesAuditConnector.schema()+ path = next(f for f in schema.fields if f.name == "audit_log_path")+ assert path.default == "/var/log/kubernetes/audit/audit.log"+++def test_capabilities_advertises_pull_audit_and_alerts():+ caps = KubernetesAuditConnector.capabilities()+ assert Capability.PULL_AUDIT in caps+ assert Capability.PULL_ALERTS in caps+++# ---------------------------------------------------------------------------+# Severity heuristic+# ---------------------------------------------------------------------------+++def test_severity_pod_exec_is_high():+ event = {+ "verb": "create",+ "objectRef": {"resource": "pods", "subresource": "exec"},+ "responseStatus": {"code": 101},+ }+ assert _classify_severity(event) == "high"+++def test_severity_pod_attach_is_high():+ event = {+ "verb": "create",+ "objectRef": {"resource": "pods", "subresource": "attach"},+ }+ assert _classify_severity(event) == "high"+++def test_severity_pod_portforward_is_high():+ event = {+ "verb": "create",+ "objectRef": {"resource": "pods", "subresource": "portforward"},+ }+ assert _classify_severity(event) == "high"+++def test_severity_impersonate_is_high():+ event = {+ "verb": "impersonate",+ "objectRef": {"resource": "users"},+ }+ assert _classify_severity(event) == "high"+++def test_severity_clusterrolebinding_create_is_high():+ event = {+ "verb": "create",+ "objectRef": {"resource": "clusterrolebindings"},+ }+ assert _classify_severity(event) == "high"+++def test_severity_secret_create_is_high():+ event = {+ "verb": "create",+ "objectRef": {"resource": "secrets"},+ }+ assert _classify_severity(event) == "high"+++def test_severity_serviceaccount_token_create_is_high():+ # ``create`` on ``serviceaccounts`` is the canonical+ # "ServiceAccount token mint" code path. It must trip high.+ event = {+ "verb": "create",+ "objectRef": {"resource": "serviceaccounts", "subresource": "token"},+ }+ assert _classify_severity(event) == "high"+++def test_severity_workload_write_is_medium():+ event = {+ "verb": "patch",+ "objectRef": {"resource": "deployments"},+ }+ assert _classify_severity(event) == "medium"+++def test_severity_failed_request_is_medium():+ # 403s and 401s during recon / RBAC probing are exactly what+ # we want to surface above floor.+ event = {+ "verb": "get",+ "objectRef": {"resource": "configmaps"},+ "responseStatus": {"code": 403},+ }+ assert _classify_severity(event) == "medium"+++def test_severity_sensitive_read_is_low():+ event = {+ "verb": "get",+ "objectRef": {"resource": "secrets"},+ "responseStatus": {"code": 200},+ }+ assert _classify_severity(event) == "low"+++def test_severity_steady_state_read_is_info():+ event = {+ "verb": "list",+ "objectRef": {"resource": "pods"},+ "responseStatus": {"code": 200},+ }+ assert _classify_severity(event) == "info"+++def test_severity_missing_objectref_does_not_crash():+ # Some audit events (e.g. RequestReceived stage on a malformed+ # request) don't carry an objectRef at all.+ event = {"verb": "get", "responseStatus": {"code": 200}}+ assert _classify_severity(event) == "info"+++def test_severity_missing_response_status_does_not_crash():+ event = {"verb": "get", "objectRef": {"resource": "pods"}}+ assert _classify_severity(event) == "info"+++# ---------------------------------------------------------------------------+# normalize()+# ---------------------------------------------------------------------------+++def _make_connector(**overrides):+ defaults = {+ "mode": "webhook",+ "cluster_name": "prod-eks-us-east-1",+ "inbox_token": "tok-abcdef-1234567890",+ }+ defaults.update(overrides)+ return KubernetesAuditConnector(**defaults)+++def test_normalize_extracts_canonical_fields():+ conn = _make_connector()+ raw = {+ "kind": "Event",+ "apiVersion": "audit.k8s.io/v1",+ "level": "RequestResponse",+ "auditID": "00000000-0000-0000-0000-000000000001",+ "stage": "ResponseComplete",+ "requestURI": "/api/v1/namespaces/prod/secrets/db-creds",+ "verb": "get",+ "user": {+ "username": "[email protected]",+ "groups": ["system:authenticated"],+ },+ "sourceIPs": ["198.51.100.5", "10.0.0.7"],+ "userAgent": "kubectl/v1.29.0",+ "objectRef": {+ "resource": "secrets",+ "namespace": "prod",+ "name": "db-creds",+ "apiVersion": "v1",+ },+ "responseStatus": {"metadata": {}, "code": 200},+ "requestReceivedTimestamp": "2026-05-10T10:00:00.000000Z",+ "stageTimestamp": "2026-05-10T10:00:00.123456Z",+ }+ norm = conn.normalize(raw)+ assert norm["source"] == "kubernetes_audit"+ assert norm["category"] == "cloud"+ assert norm["external_id"] == raw["auditID"]+ assert norm["audit_id"] == raw["auditID"]+ assert norm["k8s_user"] == "[email protected]"+ assert norm["k8s_user_groups"] == ["system:authenticated"]+ assert norm["k8s_verb"] == "get"+ assert norm["k8s_resource"] == "secrets"+ assert norm["k8s_namespace"] == "prod"+ assert norm["k8s_object_name"] == "db-creds"+ assert norm["k8s_response_code"] == 200+ assert norm["src_ip"] == "198.51.100.5"+ assert norm["source_ips"] == ["198.51.100.5", "10.0.0.7"]+ assert norm["cluster_name"] == "prod-eks-us-east-1"+ assert norm["cloud_platform"] == "kubernetes"+ assert norm["created_at"] == "2026-05-10T10:00:00.123456Z"+ # The full audit event must round-trip — detection content needs it.+ assert norm["raw_event"] is raw+ # Read of a sensitive resource is "low" by the heuristic.+ assert norm["severity"] == "low"+++def test_normalize_pod_exec_routes_to_high_severity_and_clear_title():+ conn = _make_connector()+ raw = {+ "auditID": "exec-1",+ "verb": "create",+ "user": {"username": "[email protected]"},+ "objectRef": {+ "resource": "pods",+ "subresource": "exec",+ "namespace": "prod",+ "name": "billing-api-7d4b8c-abc",+ },+ "responseStatus": {"code": 101},+ "sourceIPs": ["203.0.113.7"],+ "stageTimestamp": "2026-05-10T11:00:00Z",+ }+ norm = conn.normalize(raw)+ assert norm["severity"] == "high"+ assert norm["k8s_subresource"] == "exec"+ # The title should be obviously parseable by a human eyeballing+ # the inbox — verb, resource, subresource, target.+ assert "[email protected]" in norm["title"]+ assert "exec" in norm["title"]+ assert "billing-api-7d4b8c-abc" in norm["title"]+ assert "prod/" in norm["title"]+++def test_normalize_falls_back_to_request_received_timestamp():+ """Older API versions only emit requestReceivedTimestamp."""+ conn = _make_connector()+ raw = {+ "auditID": "old-1",+ "verb": "get",+ "objectRef": {"resource": "pods"},+ "requestReceivedTimestamp": "2026-05-10T09:00:00Z",+ }+ norm = conn.normalize(raw)+ assert norm["created_at"] == "2026-05-10T09:00:00Z"+++def test_normalize_handles_impersonation():+ conn = _make_connector()+ raw = {+ "auditID": "imp-1",+ "verb": "get",+ "user": {"username": "ci-bot"},+ "impersonatedUser": {+ "username": "system:masters",+ "groups": ["system:masters"],+ },+ "objectRef": {"resource": "secrets"},+ "responseStatus": {"code": 200},+ }+ norm = conn.normalize(raw)+ assert norm["k8s_user"] == "ci-bot"+ assert norm["k8s_impersonated_user"] == "system:masters"+++def test_normalize_missing_optional_fields_does_not_crash():+ """Audit events at the RequestReceived stage are sparse."""+ conn = _make_connector()+ raw = {"auditID": "sparse-1", "verb": "list"}+ norm = conn.normalize(raw)+ assert norm["external_id"] == "sparse-1"+ assert norm["k8s_user"] is None+ assert norm["k8s_resource"] is None+ assert norm["src_ip"] is None+ assert norm["source_ips"] is None+++def test_normalize_picks_first_source_ip_as_principal():+ """X-Forwarded-For chain — we want the immediate caller."""+ conn = _make_connector()+ raw = {+ "auditID": "xff-1",+ "verb": "get",+ "sourceIPs": ["198.51.100.99", "10.0.0.1", "10.0.0.2"],+ "objectRef": {"resource": "pods"},+ }+ norm = conn.normalize(raw)+ assert norm["src_ip"] == "198.51.100.99"+++def test_normalize_stamps_cluster_name_on_every_event():+ conn = _make_connector(cluster_name="staging-gke-us-central1")+ raw = {"auditID": "c-1", "verb": "list"}+ norm = conn.normalize(raw)+ assert norm["cluster_name"] == "staging-gke-us-central1"+++# ---------------------------------------------------------------------------+# webhook mode — test_connection + fetch_alerts+# ---------------------------------------------------------------------------+++async def test_webhook_mode_requires_cluster_name():+ conn = KubernetesAuditConnector(+ mode="webhook",+ cluster_name="",+ inbox_token="tok-1",+ )+ result = await conn.test_connection()+ assert result["success"] is False+ assert "cluster_name" in result["error"]+++async def test_webhook_mode_requires_inbox_token():+ conn = KubernetesAuditConnector(+ mode="webhook",+ cluster_name="prod",+ inbox_token="",+ )+ result = await conn.test_connection()+ assert result["success"] is False+ assert "inbox_token" in result["error"]+++async def test_webhook_mode_success_returns_hint_with_truncated_token():+ conn = KubernetesAuditConnector(+ mode="webhook",+ cluster_name="prod-eks-us-east-1",+ inbox_token="tok-superlong-secret-token-value-123",+ )+ result = await conn.test_connection()+ assert result["success"] is True+ assert result["mode"] == "webhook"+ assert result["cluster"] == "prod-eks-us-east-1"+ # The hint must not leak the full token — only a short prefix.+ assert "tok-su" in result["hint"]+ assert "superlong-secret-token-value-123" not in result["hint"]+++async def test_webhook_mode_fetch_alerts_is_empty():+ """Webhook mode pulls nothing on the scheduler tick — events+ arrive on the inbox path instead.+ """+ conn = KubernetesAuditConnector(+ mode="webhook",+ cluster_name="prod",+ inbox_token="tok-1",+ )+ result = await conn.fetch_alerts()+ assert result == []+++async def test_unknown_mode_returns_error():+ conn = KubernetesAuditConnector(+ mode="something-weird",+ cluster_name="prod",+ )+ result = await conn.test_connection()+ assert result["success"] is False+ assert "unknown mode" in result["error"]+++# ---------------------------------------------------------------------------+# file_tail mode — test_connection+# ---------------------------------------------------------------------------+++async def test_file_tail_test_connection_reports_missing_file(tmp_path: Path):+ audit_log = tmp_path / "does-not-exist.log"+ conn = KubernetesAuditConnector(+ mode="file_tail",+ cluster_name="prod",+ audit_log_path=str(audit_log),+ )+ result = await conn.test_connection()+ assert result["success"] is False+ assert "not found" in result["error"]+++async def test_file_tail_test_connection_success(tmp_path: Path):+ audit_log = tmp_path / "audit.log"+ audit_log.write_text("")+ conn = KubernetesAuditConnector(+ mode="file_tail",+ cluster_name="prod",+ audit_log_path=str(audit_log),+ )+ result = await conn.test_connection()+ assert result["success"] is True+ assert result["mode"] == "file_tail"+ assert result["audit_log_path"] == str(audit_log)+ # Default cursor path is right next to the audit log.+ assert result["cursor_path"].endswith(".aisoc-cursor")+++async def test_file_tail_test_connection_reports_unreadable_file(tmp_path: Path):+ audit_log = tmp_path / "audit.log"+ audit_log.write_text("")+ audit_log.chmod(0o000)+ try:+ conn = KubernetesAuditConnector(+ mode="file_tail",+ cluster_name="prod",+ audit_log_path=str(audit_log),+ )+ result = await conn.test_connection()+ # If we happen to be running as root (e.g. in CI), 0o000+ # is still readable and the test isn't meaningful. Skip+ # rather than assert.+ if os.geteuid() == 0:+ pytest.skip("running as root — chmod 000 is not enforceable")+ assert result["success"] is False+ assert "not readable" in result["error"]+ finally:+ audit_log.chmod(0o644)+++# ---------------------------------------------------------------------------+# file_tail mode — fetch_alerts + cursor behaviour+# ---------------------------------------------------------------------------+++def _write_audit_events(path: Path, events: list[dict]) -> None:+ """Write the apiserver's one-event-per-line JSON format."""+ body = "\n".join(json.dumps(e) for e in events) + "\n"+ path.write_text(body)+++def _append_audit_events(path: Path, events: list[dict]) -> None:+ body = "\n".join(json.dumps(e) for e in events) + "\n"+ with open(path, "a") as fh:+ fh.write(body)+++async def test_file_tail_reads_full_file_when_no_cursor(tmp_path: Path):+ audit_log = tmp_path / "audit.log"+ events = [+ {"auditID": "a", "verb": "get", "objectRef": {"resource": "pods"}},+ {"auditID": "b", "verb": "list", "objectRef": {"resource": "pods"}},+ ]+ _write_audit_events(audit_log, events)+ conn = KubernetesAuditConnector(+ mode="file_tail",+ cluster_name="prod",+ audit_log_path=str(audit_log),+ )+ result = await conn.fetch_alerts()+ assert len(result) == 2+ assert result[0]["external_id"] == "a"+ assert result[1]["external_id"] == "b"+++async def test_file_tail_cursor_advances_between_polls(tmp_path: Path):+ audit_log = tmp_path / "audit.log"+ _write_audit_events(audit_log, [{"auditID": "a", "verb": "get"}])+ conn = KubernetesAuditConnector(+ mode="file_tail",+ cluster_name="prod",+ audit_log_path=str(audit_log),+ )+ first = await conn.fetch_alerts()+ assert len(first) == 1+ # Second poll without new bytes should be a no-op.+ second = await conn.fetch_alerts()+ assert second == []+ # Append a new event — only the new one should come back.+ _append_audit_events(audit_log, [{"auditID": "b", "verb": "list"}])+ third = await conn.fetch_alerts()+ assert len(third) == 1+ assert third[0]["external_id"] == "b"+++async def test_file_tail_resets_cursor_after_rotation(tmp_path: Path):+ """If the file shrinks (logrotate truncated it), the cursor+ must reset to 0 rather than seeking past EOF forever.+ """+ audit_log = tmp_path / "audit.log"+ _write_audit_events(+ audit_log,+ [{"auditID": "old-1", "verb": "get"}, {"auditID": "old-2", "verb": "get"}],+ )+ conn = KubernetesAuditConnector(+ mode="file_tail",+ cluster_name="prod",+ audit_log_path=str(audit_log),+ )+ first = await conn.fetch_alerts()+ assert len(first) == 2++ # Simulate logrotate: replace contents with a smaller payload.+ _write_audit_events(audit_log, [{"auditID": "new-1", "verb": "list"}])+ second = await conn.fetch_alerts()+ assert len(second) == 1+ assert second[0]["external_id"] == "new-1"+++async def test_file_tail_buffers_partial_trailing_line(tmp_path: Path):+ """A line without a trailing newline = in-flight write. We+ must not consume it — back the cursor up and wait for the rest.+ """+ audit_log = tmp_path / "audit.log"+ full = {"auditID": "complete", "verb": "get"}+ body = json.dumps(full) + "\n" + '{"auditID": "partial' # no newline+ audit_log.write_text(body)+ conn = KubernetesAuditConnector(+ mode="file_tail",+ cluster_name="prod",+ audit_log_path=str(audit_log),+ )+ first = await conn.fetch_alerts()+ assert len(first) == 1+ assert first[0]["external_id"] == "complete"++ # Now complete the partial line. Next poll should pick up the+ # newly-completed event.+ completion = '", "verb": "list"}\n'+ with open(audit_log, "a") as fh:+ fh.write(completion)+ second = await conn.fetch_alerts()+ assert len(second) == 1+ assert second[0]["external_id"] == "partial"+++async def test_file_tail_skips_malformed_json_line(tmp_path: Path):+ audit_log = tmp_path / "audit.log"+ body = json.dumps({"auditID": "a", "verb": "get"}) + "\n" + "this-is-not-json\n" + json.dumps({"auditID": "b", "verb": "list"}) + "\n"+ audit_log.write_text(body)+ conn = KubernetesAuditConnector(+ mode="file_tail",+ cluster_name="prod",+ audit_log_path=str(audit_log),+ )+ result = await conn.fetch_alerts()+ assert len(result) == 2+ assert {e["external_id"] for e in result} == {"a", "b"}+++async def test_file_tail_missing_log_returns_empty(tmp_path: Path):+ """No file yet = no events. Must not raise — the apiserver may+ not have started writing yet at connector boot.+ """+ audit_log = tmp_path / "not-yet.log"+ conn = KubernetesAuditConnector(+ mode="file_tail",+ cluster_name="prod",+ audit_log_path=str(audit_log),+ )+ result = await conn.fetch_alerts()+ assert result == []+++async def test_file_tail_respects_custom_cursor_path(tmp_path: Path):+ audit_log = tmp_path / "audit.log"+ cursor = tmp_path / "cursors" / "audit.cursor"+ cursor.parent.mkdir(parents=True)+ _write_audit_events(audit_log, [{"auditID": "a", "verb": "get"}])+ conn = KubernetesAuditConnector(+ mode="file_tail",+ cluster_name="prod",+ audit_log_path=str(audit_log),+ cursor_path=str(cursor),+ )+ await conn.fetch_alerts()+ # The custom cursor file must exist and hold a byte offset > 0.+ assert cursor.exists()+ assert int(cursor.read_text().strip()) > 0+++async def test_file_tail_corrupt_cursor_starts_from_zero(tmp_path: Path):+ audit_log = tmp_path / "audit.log"+ cursor = tmp_path / "audit.log.aisoc-cursor"+ _write_audit_events(audit_log, [{"auditID": "a", "verb": "get"}])+ cursor.write_text("not-an-integer")+ conn = KubernetesAuditConnector(+ mode="file_tail",+ cluster_name="prod",+ audit_log_path=str(audit_log),+ )+ result = await conn.fetch_alerts()+ assert len(result) == 1+ assert result[0]["external_id"] == "a"+++async def test_file_tail_caps_read_size_per_poll(tmp_path: Path, monkeypatch):+ """The per-poll cap exists so a huge backlog doesn't wedge the+ scheduler. Use monkeypatch to shrink the cap so we don't have to+ write 8 MiB of test data.+ """+ monkeypatch.setattr(+ "app.connectors.kubernetes_audit._MAX_TAIL_BYTES_PER_POLL",+ 200, # tiny cap so we can prove the chunking works+ )+ # Now ensure the constant we actually imported also reflects the+ # patch (the connector reads it via module-level reference).+ assert _MAX_TAIL_BYTES_PER_POLL == 8 * 1024 * 1024 # untouched here++ audit_log = tmp_path / "audit.log"+ # Each line is ~80 bytes — 5 lines = ~400 bytes, well over the+ # patched 200 byte cap.+ events = [{"auditID": f"id-{i:03d}", "verb": "get", "objectRef": {"resource": "pods"}} for i in range(5)]+ _write_audit_events(audit_log, events)++ conn = KubernetesAuditConnector(+ mode="file_tail",+ cluster_name="prod",+ audit_log_path=str(audit_log),+ )+ first = await conn.fetch_alerts()+ # We should have read a strict prefix of the events, not all.+ assert 0 < len(first) < 5+ # Drain the rest. Multiple polls are expected — the whole point+ # of the cap is that one poll can't drain a huge backlog.+ all_events = list(first)+ for _ in range(10):+ batch = await conn.fetch_alerts()+ if not batch:+ break+ all_events.extend(batch)+ assert len(all_events) == 5+ assert [e["external_id"] for e in all_events] == [f"id-{i:03d}" for i in range(5)]diff --git a/services/connectors/tests/test_orca.py b/services/connectors/tests/test_orca.pynew file mode 100644index 000000000..f1cec0a1b--- /dev/null+++ b/services/connectors/tests/test_orca.py@@ -0,0 +1,226 @@+"""Tests for the Orca Security connector."""++from __future__ import annotations++import httpx+import pytest+import respx+from app.connectors.orca import OrcaConnector+++def test_schema():+ schema = OrcaConnector.schema()+ assert schema.connector_id == "orca"+ assert schema.connector_name == "Orca Security"+ assert schema.category == "cloud"+ field_names = {f.name for f in schema.fields}+ assert {"api_token", "api_url"}.issubset(field_names)+ api_token_field = next(f for f in schema.fields if f.name == "api_token")+ assert api_token_field.type == "secret"+ api_url_field = next(f for f in schema.fields if f.name == "api_url")+ assert api_url_field.required is False+ assert api_url_field.default == "https://api.orcasecurity.io"+++def test_capabilities():+ from app.connectors.base import Capability++ caps = OrcaConnector.capabilities()+ assert Capability.PULL_ALERTS in caps+++def test_normalize_severity_collapse_hazardous():+ """Orca's hazardous tier collapses into AiSOC high."""+ conn = OrcaConnector(api_token="t")+ raw = {+ "alert_id": "alert-1",+ "description": "Public S3 bucket exposed",+ "state": {"severity": "hazardous"},+ "asset": {+ "name": "my-bucket",+ "vendor": "aws",+ "region": "us-east-1",+ "vendor_id": "arn:aws:s3:::my-bucket",+ },+ "rule_name": "Bucket public",+ }+ norm = conn.normalize(raw)+ assert norm["source"] == "orca"+ assert norm["category"] == "cloud"+ assert norm["external_id"] == "alert-1"+ assert norm["severity"] == "high"+ assert norm["hostname"] == "my-bucket"+ assert norm["cloud_platform"] == "aws"+ assert norm["cloud_region"] == "us-east-1"+ assert norm["raw_event"] is raw+++def test_normalize_severity_collapse_critical():+ conn = OrcaConnector(api_token="t")+ raw = {"alert_id": "c1", "state": {"severity": "critical"}}+ assert conn.normalize(raw)["severity"] == "high"+++def test_normalize_severity_informational():+ conn = OrcaConnector(api_token="t")+ raw = {"alert_id": "i1", "state": {"severity": "informational"}}+ assert conn.normalize(raw)["severity"] == "info"+++def test_normalize_severity_unknown_defaults_medium():+ conn = OrcaConnector(api_token="t")+ raw = {"alert_id": "u1", "state": {"severity": "weird"}}+ assert conn.normalize(raw)["severity"] == "medium"+++def test_normalize_severity_from_top_level():+ """If state.severity is missing, fall back to top-level severity."""+ conn = OrcaConnector(api_token="t")+ raw = {"alert_id": "t1", "severity": "low"}+ assert conn.normalize(raw)["severity"] == "low"+++def test_normalize_handles_missing_asset():+ conn = OrcaConnector(api_token="t")+ raw = {"alert_id": "n1", "state": {"severity": "medium"}}+ norm = conn.normalize(raw)+ assert norm["hostname"] is None+ assert norm["cloud_platform"] is None+ assert norm["severity"] == "medium"+++def test_normalize_uses_recommendation_for_description():+ conn = OrcaConnector(api_token="t")+ raw = {+ "alert_id": "d1",+ "description": "title",+ "recommendation": "remediation steps",+ }+ norm = conn.normalize(raw)+ assert norm["title"] == "title"+ assert norm["description"] == "remediation steps"+++def test_normalize_falls_back_to_id():+ """Some Orca payloads use ``id`` rather than ``alert_id``."""+ conn = OrcaConnector(api_token="t")+ raw = {"id": "fallback-id", "state": {"severity": "high"}}+ assert conn.normalize(raw)["external_id"] == "fallback-id"+++async def test_test_connection_success():+ respx.get("https://api.orcasecurity.io/api/user/session").mock(return_value=httpx.Response(200, json={"user": "ok"}))+ conn = OrcaConnector(api_token="t")+ result = await conn.test_connection()+ assert result["success"] is True+ assert result["connector"] == "orca"+++async def test_test_connection_unauthorized():+ respx.get("https://api.orcasecurity.io/api/user/session").mock(return_value=httpx.Response(401, json={"error": "unauthorized"}))+ conn = OrcaConnector(api_token="bad")+ result = await conn.test_connection()+ assert result["success"] is False+ assert "401" in result["error"]+++async def test_fetch_alerts_data_envelope():+ """Orca tenants on the standard envelope return ``{"data": [...]}.``"""+ respx.get("https://api.orcasecurity.io/api/alerts").mock(+ return_value=httpx.Response(+ 200,+ json={+ "data": [+ {+ "alert_id": "a1",+ "description": "Misconfig",+ "state": {"severity": "critical"},+ "asset": {"name": "host-1", "vendor": "aws"},+ },+ {+ "alert_id": "a2",+ "description": "Vuln",+ "state": {"severity": "medium"},+ },+ ]+ },+ )+ )+ conn = OrcaConnector(api_token="t")+ alerts = await conn.fetch_alerts(since_seconds=300)+ assert len(alerts) == 2+ assert alerts[0]["external_id"] == "a1"+ assert alerts[0]["severity"] == "high"+ assert alerts[1]["severity"] == "medium"+++async def test_fetch_alerts_results_envelope():+ """Some Orca versions ship results in ``{"results": [...]}``."""+ respx.get("https://api.orcasecurity.io/api/alerts").mock(+ return_value=httpx.Response(+ 200,+ json={+ "results": [+ {+ "alert_id": "r1",+ "state": {"severity": "high"},+ }+ ]+ },+ )+ )+ conn = OrcaConnector(api_token="t")+ alerts = await conn.fetch_alerts()+ assert len(alerts) == 1+ assert alerts[0]["external_id"] == "r1"+++async def test_fetch_alerts_bare_list():+ """Bare-list fallback for older endpoints."""+ respx.get("https://api.orcasecurity.io/api/alerts").mock(+ return_value=httpx.Response(+ 200,+ json=[{"alert_id": "b1", "state": {"severity": "low"}}],+ )+ )+ conn = OrcaConnector(api_token="t")+ alerts = await conn.fetch_alerts()+ assert len(alerts) == 1+ assert alerts[0]["severity"] == "low"+++async def test_fetch_alerts_handles_error():+ respx.get("https://api.orcasecurity.io/api/alerts").mock(return_value=httpx.Response(500, text="boom"))+ conn = OrcaConnector(api_token="t")+ alerts = await conn.fetch_alerts()+ assert alerts == []+++async def test_fetch_alerts_passes_status_open():+ """We only ever pull open alerts to keep volume sane."""+ route = respx.get("https://api.orcasecurity.io/api/alerts").mock(return_value=httpx.Response(200, json={"data": []}))+ conn = OrcaConnector(api_token="t")+ await conn.fetch_alerts()+ assert route.called+ call_url = str(route.calls[0].request.url)+ assert "status=open" in call_url+ assert "start_at_gte=" in call_url+++def test_custom_api_url_strips_trailing_slash():+ conn = OrcaConnector(api_token="t", api_url="https://api.eu.orcasecurity.io/")+ assert conn._api_url == "https://api.eu.orcasecurity.io"diff --git a/services/connectors/tests/test_prisma_cloud.py b/services/connectors/tests/test_prisma_cloud.pynew file mode 100644index 000000000..13ee6b5fe--- /dev/null+++ b/services/connectors/tests/test_prisma_cloud.py@@ -0,0 +1,231 @@+"""+Unit tests for the Prisma Cloud connector.++Three concerns per connector apply here too:++1. ``schema()`` is shaped correctly (Prisma-specific field expectations).+2. ``normalize()`` produces an event dict downstream code can rely on,+ including severity ladder collapse and epoch-ms timestamp conversion.+3. ``test_connection()`` and ``fetch_alerts()`` route through ``httpx``+ the way we expect, driven by ``respx`` so we never hit real Prisma+ Cloud APIs.+"""++from __future__ import annotations++import httpx+import pytest+import respx+from app.connectors.prisma_cloud import PrismaCloudConnector++_API = "https://api.prismacloud.io"+_KEY_ID = "00000000-0000-0000-0000-000000000001"+_SECRET = "super-secret-value"+++# ---------------------------------------------------------------------------+# Schema sanity (Prisma-specific; generic contract checks live in test_schemas)+# ---------------------------------------------------------------------------+++def test_prisma_cloud_schema_has_required_fields():+ schema = PrismaCloudConnector.schema()+ field_names = {f.name for f in schema.fields}+ assert {"api_url", "access_key_id", "secret_key", "compute_url"} <= field_names+ assert schema.category == "cloud"+ assert schema.connector_id == "prisma_cloud"+++def test_prisma_cloud_schema_marks_secret_field():+ schema = PrismaCloudConnector.schema()+ secret = next(f for f in schema.fields if f.name == "secret_key")+ assert secret.type == "secret"+++def test_prisma_cloud_compute_url_is_optional():+ schema = PrismaCloudConnector.schema()+ compute = next(f for f in schema.fields if f.name == "compute_url")+ assert compute.required is False, "compute_url must be optional; v7.1.0 only consumes the unified /alert endpoint"+++# ---------------------------------------------------------------------------+# Normalize: shape + severity rules + timestamp coercion+# ---------------------------------------------------------------------------+++def test_normalize_collapses_critical_into_high():+ connector = PrismaCloudConnector(_API, _KEY_ID, _SECRET)+ raw = {+ "id": "alert-1",+ "alertTime": 1735689600000, # 2025-01-01T00:00:00Z, epoch-ms+ "policy": {+ "name": "Public S3 bucket",+ "description": "S3 bucket is publicly readable",+ "severity": "critical",+ },+ "resource": {+ "name": "logs-bucket",+ "rrn": "rrn::s3:us-east-1:123:bucket/logs-bucket",+ "cloudType": "aws",+ "regionId": "us-east-1",+ },+ }+ out = connector.normalize(raw)+ assert out["source"] == "prisma_cloud"+ assert out["severity"] == "high", (+ "Prisma Cloud 'critical' must collapse into AiSOC 'high'; AiSOC does not expose a separate critical band"+ )+ assert out["external_id"] == "alert-1"+ assert out["title"] == "Public S3 bucket"+ assert out["cloud_resource"] == "rrn::s3:us-east-1:123:bucket/logs-bucket"+ assert out["cloud_platform"] == "aws"+ assert out["cloud_region"] == "us-east-1"+ assert out["created_at"] == "2025-01-01T00:00:00Z"+++def test_normalize_maps_informational_to_info():+ connector = PrismaCloudConnector(_API, _KEY_ID, _SECRET)+ raw = {+ "id": "alert-2",+ "policy": {"name": "Tag missing", "severity": "informational"},+ }+ out = connector.normalize(raw)+ assert out["severity"] == "info"+++def test_normalize_handles_iso_timestamp_passthrough():+ """Some legacy payloads ship ISO strings — keep them as-is."""+ connector = PrismaCloudConnector(_API, _KEY_ID, _SECRET)+ raw = {+ "id": "alert-3",+ "alertTime": "2026-01-01T12:00:00Z",+ "policy": {"name": "Drift detected", "severity": "medium"},+ }+ out = connector.normalize(raw)+ assert out["created_at"] == "2026-01-01T12:00:00Z"+ assert out["severity"] == "medium"+++def test_normalize_falls_back_to_medium_for_unknown_severity():+ connector = PrismaCloudConnector(_API, _KEY_ID, _SECRET)+ raw = {"id": "alert-4", "policy": {"name": "Unknown band", "severity": "weird"}}+ out = connector.normalize(raw)+ assert out["severity"] == "medium", "unrecognised severity must default to 'medium' — never silently drop"+++# ---------------------------------------------------------------------------+# Live HTTP routing via respx+# ---------------------------------------------------------------------------+++async def test_test_connection_success():+ respx.post(f"{_API}/login").mock(return_value=httpx.Response(200, json={"token": "jwt-abc"}))+ connector = PrismaCloudConnector(_API, _KEY_ID, _SECRET)+ result = await connector.test_connection()+ assert result["success"] is True+ assert result["api_url"] == _API+++async def test_test_connection_returns_friendly_error_on_auth_failure():+ respx.post(f"{_API}/login").mock(return_value=httpx.Response(401, text="invalid credentials"))+ connector = PrismaCloudConnector(_API, _KEY_ID, _SECRET)+ result = await connector.test_connection()+ assert result["success"] is False+ assert "could not exchange access keys" in result["error"]+++async def test_test_connection_handles_login_returning_no_token():+ """Prisma Cloud has been observed to return 200 with no token field+ when the access key is disabled. We must surface that as a failure."""+ respx.post(f"{_API}/login").mock(return_value=httpx.Response(200, json={"message": "key disabled"}))+ connector = PrismaCloudConnector(_API, _KEY_ID, _SECRET)+ result = await connector.test_connection()+ assert result["success"] is False+++async def test_fetch_alerts_returns_normalized_events_from_items_envelope():+ respx.post(f"{_API}/login").mock(return_value=httpx.Response(200, json={"token": "jwt-abc"}))+ respx.post(f"{_API}/alert/v1/alert").mock(+ return_value=httpx.Response(+ 200,+ json={+ "items": [+ {+ "id": "a-1",+ "alertTime": 1735689600000,+ "policy": {+ "name": "Open SSH to internet",+ "severity": "high",+ },+ "resource": {+ "name": "i-abc",+ "cloudType": "aws",+ "regionId": "us-east-1",+ },+ }+ ]+ },+ )+ )++ connector = PrismaCloudConnector(_API, _KEY_ID, _SECRET)+ events = await connector.fetch_alerts(since_seconds=300)+ assert len(events) == 1+ assert events[0]["source"] == "prisma_cloud"+ assert events[0]["external_id"] == "a-1"+ assert events[0]["severity"] == "high"+ assert events[0]["cloud_platform"] == "aws"+++async def test_fetch_alerts_handles_bare_list_envelope():+ """Some Prisma Cloud regions return a bare list instead of the+ ``{"items": [...]}`` envelope; the connector must accept both."""+ respx.post(f"{_API}/login").mock(return_value=httpx.Response(200, json={"token": "jwt-abc"}))+ respx.post(f"{_API}/alert/v1/alert").mock(+ return_value=httpx.Response(+ 200,+ json=[+ {+ "id": "a-2",+ "policy": {"name": "Drift detected", "severity": "low"},+ }+ ],+ )+ )++ connector = PrismaCloudConnector(_API, _KEY_ID, _SECRET)+ events = await connector.fetch_alerts(since_seconds=300)+ assert len(events) == 1+ assert events[0]["external_id"] == "a-2"+ assert events[0]["severity"] == "low"+++async def test_fetch_alerts_returns_empty_list_when_login_fails():+ """If auth fails on poll we degrade gracefully — no crash, no events,+ and the scheduler will retry on the next interval."""+ respx.post(f"{_API}/login").mock(return_value=httpx.Response(500, text="internal server error"))+ connector = PrismaCloudConnector(_API, _KEY_ID, _SECRET)+ events = await connector.fetch_alerts(since_seconds=300)+ assert events == []+++async def test_fetch_alerts_returns_empty_list_when_alert_endpoint_5xxs():+ respx.post(f"{_API}/login").mock(return_value=httpx.Response(200, json={"token": "jwt-abc"}))+ respx.post(f"{_API}/alert/v1/alert").mock(return_value=httpx.Response(503, text="service unavailable"))+ connector = PrismaCloudConnector(_API, _KEY_ID, _SECRET)+ events = await connector.fetch_alerts(since_seconds=300)+ assert events == []diff --git a/services/ingest/internal/config/config.go b/services/ingest/internal/config/config.goindex 7456d4759..7a3be9b6f 100644--- a/services/ingest/internal/config/config.go+++ b/services/ingest/internal/config/config.go@@ -42,6 +42,21 @@ type Config struct {// bigger gets a 413; vendors that page through alerts should batch// at the source rather than push 50MB at once.InboxMaxBodyBytes int64++ // Kubernetes audit webhook (Track D, v7.1.0).+ //+ // K8sAuditSharedSecret is the value the apiserver must present in the+ // X-AiSOC-K8s-Token header on every POST /v1/ingest/k8s-audit/{tenant}+ // request. The route returns 503 when this is empty and 401 when the+ // header is missing or doesn't match. Empty by default so a fresh+ // install doesn't accidentally accept anonymous K8s audit pushes.+ K8sAuditSharedSecret string+ // K8sAuditMaxBodyBytes caps a single apiserver audit batch. Mirrors+ // InboxMaxBodyBytes but tracked separately so K8s tuning doesn't drag+ // the broader inbox limit around. The apiserver's default audit batch+ // max is ~10 MiB, so 16 MiB gives a little headroom without+ // leaving the door open for a runaway producer.+ K8sAuditMaxBodyBytes int64}// Load reads configuration from environment variables@@ -77,6 +92,10 @@ func Load() (*Config, error) {InboxEnabled: getEnv("INBOX_ENABLED", "true") == "true",InboxTemplatesDir: getEnv("INBOX_TEMPLATES_DIR", "/app/templates"),InboxMaxBodyBytes: int64(mustGetEnvInt("INBOX_MAX_BODY_BYTES", 10*1024*1024)),++ // Kubernetes audit webhook (Track D, v7.1.0).+ K8sAuditSharedSecret: getEnv("K8S_AUDIT_SHARED_SECRET", ""),+ K8sAuditMaxBodyBytes: int64(mustGetEnvInt("K8S_AUDIT_MAX_BODY_BYTES", 16*1024*1024)),}if cfg.JWTSecret == "" && os.Getenv("ENV") != "development" {diff --git a/services/ingest/internal/handler/k8s_audit.go b/services/ingest/internal/handler/k8s_audit.gonew file mode 100644index 000000000..99756eef5--- /dev/null+++ b/services/ingest/internal/handler/k8s_audit.go@@ -0,0 +1,241 @@+// k8s_audit.go — Kubernetes audit log webhook handler.+//+// This is the receive side of the Track D / v7.1.0 Kubernetes audit+// integration. The Kubernetes apiserver, when configured with an+// audit-webhook backend, POSTs batches of v1 audit events to a remote+// HTTP endpoint as a single JSON document of shape:+//+// {+// "kind": "EventList",+// "apiVersion": "audit.k8s.io/v1",+// "items": [ { ...one Event... }, ... ]+// }+//+// The route is `POST /v1/ingest/k8s-audit/{tenant_id}`. We pull tenant+// from the URL (rather than a header) because audit-webhook config in+// the apiserver kubeconfig file is brittle to add custom headers to,+// but a path-templated URL is trivial. The webhook is authenticated+// with a single shared secret presented in `X-AiSOC-K8s-Token`. We+// only ever compare it with `subtle.ConstantTimeCompare` so a slow+// guesser can't shave bytes off via timing.+//+// Each item in the EventList becomes one normalized event with+// `connector_type: "kubernetes_audit"`, which the normalizer turns+// into an OCSF "API Activity" (class 6003) record. Severity is not+// emitted by the apiserver — we leave the heuristic to the+// `kubernetes_audit` Python connector path on the file_tail side, and+// here just pass the event verbatim and let the normalizer pick a+// default. The intent is that detection rules live downstream and key+// off `objectRef.resource`, `verb`, etc.; severity scoring is the+// detection engine's job, not the webhook's.+package handler++import (+ "crypto/subtle"+ "encoding/json"+ "fmt"+ "io"+ "net/http"+ "time"++ "github.com/beenuar/aisoc/services/ingest/internal/normalizer"+ "github.com/go-chi/chi/v5"+ "github.com/rs/zerolog/log"+)++// k8sAuditConnectorType is the connector_type stamped on every+// normalized event from this route. Must match the `kubernetes_audit`+// key in connectorProfiles — that's how the normalizer finds the right+// field map and product metadata.+const k8sAuditConnectorType = "kubernetes_audit"++// k8sAuditTokenHeader is the header the apiserver presents to prove+// it's allowed to push to this route. The value must equal+// cfg.K8sAuditSharedSecret. We chose a custom header rather than+// Authorization: Bearer to avoid colliding with the apiserver's own+// service-account-token plumbing in some hosted control planes.+const k8sAuditTokenHeader = "X-AiSOC-K8s-Token"++// k8sEventList mirrors the shape of audit.k8s.io/v1 EventList. We+// intentionally type Items as []json.RawMessage so the payload travels+// to the normalizer untouched — every interesting field+// (verb / objectRef / responseStatus / sourceIPs) is best parsed by+// the existing JSON-path-based normalizer config rather than by+// re-typing it here.+type k8sEventList struct {+ Kind string `json:"kind"`+ APIVersion string `json:"apiVersion"`+ Items []json.RawMessage `json:"items"`+}++// K8sAuditEvents handles POST /v1/ingest/k8s-audit/{tenant_id}.+//+// On the happy path it returns 200 with an IngestResponse summarizing+// counts, matching IngestEvents shape so apiserver operators see the+// same JSON regardless of which AiSOC ingest endpoint they pointed at.+// The apiserver's webhook backend treats any 2xx as success and won't+// retry, so we only return non-2xx for genuine "do not deliver this+// batch again" or "fix your config" conditions.+func (h *Handler) K8sAuditEvents(w http.ResponseWriter, r *http.Request) {+ // 1. The route is disabled at install time unless an operator+ // explicitly sets a shared secret. Returning 503 here (not 401)+ // is deliberate — apiserver operators get a louder signal that+ // the *server* isn't ready, not that *they* did something wrong.+ if h.cfg.K8sAuditSharedSecret == "" {+ writeError(w, http.StatusServiceUnavailable,+ "kubernetes audit webhook not enabled on this AiSOC installation")+ return+ }++ // 2. Tenant comes from the URL path, set by the chi route pattern.+ // This is the only auth boundary that ties an event to a specific+ // AiSOC tenant on this code path, which is why the secret is+ // installation-wide rather than per-tenant — the tenant binding+ // happens at apiserver-config time when the operator pastes the+ // URL into the audit webhook kubeconfig.+ tenantID := chi.URLParam(r, "tenant_id")+ if tenantID == "" {+ writeError(w, http.StatusBadRequest, "missing tenant_id in path")+ return+ }++ // 3. Constant-time secret comparison. If a header is missing the+ // length mismatch obviously fails, but ConstantTimeCompare also+ // covers the partial-prefix-match attacker. We log misses at warn+ // because brute-forcing this header is a reasonable thing to alert+ // on at the SIEM layer.+ presented := r.Header.Get(k8sAuditTokenHeader)+ expected := h.cfg.K8sAuditSharedSecret+ if subtle.ConstantTimeCompare([]byte(presented), []byte(expected)) != 1 {+ log.Warn().+ Str("tenant_id", tenantID).+ Str("remote_addr", r.RemoteAddr).+ Msg("k8s-audit webhook: shared-secret mismatch")+ writeError(w, http.StatusUnauthorized, "invalid or missing X-AiSOC-K8s-Token")+ return+ }++ // 4. Cap body size before we pay the cost of decoding. Without this,+ // a misconfigured apiserver could push a 1 GiB batch and OOM the+ // ingest pod. The default is 16 MiB which is generous for the+ // apiserver's own ~10 MiB batch ceiling.+ bodyLimit := h.cfg.K8sAuditMaxBodyBytes+ if bodyLimit <= 0 {+ bodyLimit = 16 * 1024 * 1024+ }+ bodyReader := http.MaxBytesReader(w, r.Body, bodyLimit)+ body, err := io.ReadAll(bodyReader)+ if err != nil {+ // http.MaxBytesReader returns *http.MaxBytesError on overflow.+ // Either way the right answer for the apiserver is 413 — it+ // will keep the batch around and probably retry with a smaller+ // one if the operator tightened audit-batch-max-size.+ log.Warn().Err(err).Str("tenant_id", tenantID).Msg("k8s-audit webhook: body read failed or oversized")+ writeError(w, http.StatusRequestEntityTooLarge,+ fmt.Sprintf("audit batch exceeds maximum of %d bytes", bodyLimit))+ return+ }++ // 5. Parse the EventList wrapper. We deliberately don't validate+ // kind / apiVersion strictly — the apiserver might be slightly+ // older or newer than what we know about, and rejecting on those+ // fields would prevent legitimate audit traffic from getting+ // through. We do want to reject obvious mis-targeted POSTs (some+ // other client pointed at this URL by accident), so a missing+ // `items` field becomes a 400.+ var list k8sEventList+ if err := json.Unmarshal(body, &list); err != nil {+ writeError(w, http.StatusBadRequest, "invalid EventList JSON: "+err.Error())+ return+ }++ // 6. An empty batch is normal — the apiserver's audit-batch-period+ // can fire even if no requests came in. Returning 200 with zero+ // counts is the polite answer.+ if len(list.Items) == 0 {+ writeJSON(w, http.StatusOK, IngestResponse{RequestID: newRequestID()})+ return+ }++ // 7. Per-batch cap. We use the global MaxBatchSize ceiling so a+ // runaway audit policy can't pump a million-item batch through and+ // stall the Kafka writer. The apiserver will retry the rejected+ // batch unchanged, so the operator gets a visible signal in the+ // apiserver logs and can tighten audit-batch-max-size.+ if len(list.Items) > h.cfg.MaxBatchSize {+ writeError(w, http.StatusRequestEntityTooLarge,+ fmt.Sprintf("batch size %d exceeds maximum of %d", len(list.Items), h.cfg.MaxBatchSize))+ return+ }++ // 8. Normalize each item. ConnectorID is a synthetic-but-stable+ // string — the apiserver doesn't carry connector identity through+ // audit, so we derive one per tenant. That keeps Kafka partition+ // keys (tenant + event id) well-distributed without forcing the+ // operator to invent a connector id at apiserver-config time.+ connectorID := "kubernetes-audit-" + tenantID+ receivedAt := time.Now().UTC().Format(time.RFC3339Nano)++ normalized := make([]*normalizer.NormalizedEvent, 0, len(list.Items))+ errs := []string{}+ rejected := 0++ for i, raw := range list.Items {+ var payload map[string]interface{}+ if err := json.Unmarshal(raw, &payload); err != nil {+ log.Warn().Err(err).Int("index", i).+ Str("tenant_id", tenantID).+ Msg("k8s-audit webhook: skipping item with invalid JSON")+ errs = append(errs, fmt.Sprintf("item %d: %s", i, err.Error()))+ rejected+++ continue+ }++ event, err := h.norm.Normalize(&normalizer.RawEvent{+ ConnectorID: connectorID,+ ConnectorType: k8sAuditConnectorType,+ TenantID: tenantID,+ ReceivedAt: receivedAt,+ Payload: payload,+ SourceFormat: "k8s_audit_v1",+ })+ if err != nil {+ log.Warn().Err(err).Int("index", i).+ Str("tenant_id", tenantID).+ Msg("k8s-audit webhook: normalization failed")+ errs = append(errs, fmt.Sprintf("item %d: %s", i, err.Error()))+ rejected+++ continue+ }++ normalized = append(normalized, event)+ }++ // 9. Publish normalized events as one Kafka batch. If the publish+ // itself fails we return 5xx so the apiserver retries — losing+ // audit events to a transient broker hiccup would be a real+ // detection-coverage hole.+ if len(normalized) > 0 {+ if err := h.pub.PublishBatch(r.Context(), normalized); err != nil {+ log.Error().Err(err).+ Str("tenant_id", tenantID).+ Int("count", len(normalized)).+ Msg("k8s-audit webhook: kafka publish failed")+ writeError(w, http.StatusInternalServerError, "failed to publish events")+ return+ }+ }++ log.Info().+ Str("tenant_id", tenantID).+ Int("accepted", len(normalized)).+ Int("rejected", rejected).+ Msg("k8s-audit webhook: batch processed")++ writeJSON(w, http.StatusOK, IngestResponse{+ Accepted: len(normalized),+ Rejected: rejected,+ RequestID: newRequestID(),+ Errors: errs,+ })+}diff --git a/services/ingest/internal/handler/k8s_audit_test.go b/services/ingest/internal/handler/k8s_audit_test.gonew file mode 100644index 000000000..cc88dd90b--- /dev/null+++ b/services/ingest/internal/handler/k8s_audit_test.go@@ -0,0 +1,198 @@+// k8s_audit_test.go — auth/validation coverage for the Kubernetes+// apiserver audit-webhook target.+//+// These tests focus on the HTTP-edge behavior of K8sAuditEvents: what+// it returns and when, and what it never returns regardless of+// request shape. The behavior we care about most lives before we ever+// touch Kafka — the shared-secret check, the body-size cap, and the+// JSON envelope parse — because that's where every published audit+// event comes through. The Kafka publish path itself runs the same+// PublishBatch code shared with IngestEvents, so we don't redo that+// here; integration tests cover the round-trip.+package handler++import (+ "bytes"+ "context"+ "encoding/json"+ "net/http"+ "net/http/httptest"+ "strings"+ "testing"++ "github.com/beenuar/aisoc/services/ingest/internal/config"+ "github.com/go-chi/chi/v5"+)++// newAuditHandler builds a Handler whose normalizer and publisher are+// nil. Every test below exits before either is dereferenced — these+// exercise the early-return guards (503/401/400/413) that protect the+// rest of the pipeline. If a future change to K8sAuditEvents causes a+// test to nil-panic, that's a real signal: the guard moved.+func newAuditHandler(secret string, maxBytes int64) *Handler {+ return &Handler{+ norm: nil,+ pub: nil,+ cfg: &config.Config{+ K8sAuditSharedSecret: secret,+ K8sAuditMaxBodyBytes: maxBytes,+ MaxBatchSize: 500,+ },+ }+}++// auditReq builds a request with chi's URL-param machinery primed so+// chi.URLParam(req, "tenant_id") returns the value we want, without+// standing up a router. chi resolves URL params off a context value+// keyed on chi.RouteCtxKey; populating it directly is the documented+// pattern in chi's own tests.+func auditReq(t *testing.T, body []byte, tenantID, headerToken string) *http.Request {+ t.Helper()+ req := httptest.NewRequest(http.MethodPost, "/v1/ingest/k8s-audit/"+tenantID, bytes.NewReader(body))+ if headerToken != "" {+ req.Header.Set("X-AiSOC-K8s-Token", headerToken)+ }+ rctx := chi.NewRouteContext()+ rctx.URLParams.Add("tenant_id", tenantID)+ req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))+ return req+}++func TestK8sAuditEvents_DisabledByDefault(t *testing.T) {+ // A fresh install has no shared secret. Returning 503 (rather than+ // 401) is deliberate — the operator hasn't enabled the surface yet,+ // it's not that the apiserver presented bad credentials. Apiserver+ // operators reading their audit-webhook log get a clearer signal.+ h := newAuditHandler("", 16*1024*1024)+ rec := httptest.NewRecorder()+ h.K8sAuditEvents(rec, auditReq(t, []byte(`{"items":[]}`), "tenant-a", ""))++ if rec.Code != http.StatusServiceUnavailable {+ t.Fatalf("disabled webhook: status = %d, want %d", rec.Code, http.StatusServiceUnavailable)+ }+}++func TestK8sAuditEvents_RejectsMissingToken(t *testing.T) {+ h := newAuditHandler("expected-secret", 16*1024*1024)+ rec := httptest.NewRecorder()+ h.K8sAuditEvents(rec, auditReq(t, []byte(`{"items":[]}`), "tenant-a", ""))++ if rec.Code != http.StatusUnauthorized {+ t.Fatalf("missing token: status = %d, want %d", rec.Code, http.StatusUnauthorized)+ }+}++func TestK8sAuditEvents_RejectsWrongToken(t *testing.T) {+ h := newAuditHandler("expected-secret", 16*1024*1024)+ rec := httptest.NewRecorder()+ h.K8sAuditEvents(rec, auditReq(t, []byte(`{"items":[]}`), "tenant-a", "wrong-secret"))++ if rec.Code != http.StatusUnauthorized {+ t.Fatalf("wrong token: status = %d, want %d", rec.Code, http.StatusUnauthorized)+ }+}++func TestK8sAuditEvents_RejectsPartialPrefixToken(t *testing.T) {+ // Constant-time compare must reject a presented token that is a+ // strict prefix of the expected one. This catches a regression+ // where someone replaces subtle.ConstantTimeCompare with == plus+ // strings.HasPrefix.+ h := newAuditHandler("expected-secret-12345", 16*1024*1024)+ rec := httptest.NewRecorder()+ h.K8sAuditEvents(rec, auditReq(t, []byte(`{"items":[]}`), "tenant-a", "expected-secret"))++ if rec.Code != http.StatusUnauthorized {+ t.Fatalf("partial-prefix token: status = %d, want %d", rec.Code, http.StatusUnauthorized)+ }+}++func TestK8sAuditEvents_RejectsMissingTenantID(t *testing.T) {+ // chi normally won't dispatch a request without tenant_id at all,+ // but defense in depth: directly invoke the handler with an empty+ // path param to confirm it returns 400 rather than panicking or+ // publishing under a "" tenant.+ h := newAuditHandler("right-secret", 16*1024*1024)+ rec := httptest.NewRecorder()+ body := []byte(`{"items":[]}`)+ req := httptest.NewRequest(http.MethodPost, "/v1/ingest/k8s-audit/", bytes.NewReader(body))+ req.Header.Set("X-AiSOC-K8s-Token", "right-secret")+ rctx := chi.NewRouteContext()+ rctx.URLParams.Add("tenant_id", "")+ req = req.WithContext(context.WithValue(req.Context(), chi.RouteCtxKey, rctx))++ h.K8sAuditEvents(rec, req)+ if rec.Code != http.StatusBadRequest {+ t.Fatalf("missing tenant: status = %d, want %d", rec.Code, http.StatusBadRequest)+ }+}++func TestK8sAuditEvents_RejectsInvalidJSON(t *testing.T) {+ h := newAuditHandler("right-secret", 16*1024*1024)+ rec := httptest.NewRecorder()+ h.K8sAuditEvents(rec, auditReq(t, []byte(`not json`), "tenant-a", "right-secret"))++ if rec.Code != http.StatusBadRequest {+ t.Fatalf("bad json: status = %d, want %d", rec.Code, http.StatusBadRequest)+ }+}++func TestK8sAuditEvents_RejectsOversizedBody(t *testing.T) {+ // Cap small (1 KiB) and submit a body well over. Without this+ // guard a misconfigured apiserver could OOM the ingest pod.+ h := newAuditHandler("right-secret", 1024)+ rec := httptest.NewRecorder()++ big := bytes.Repeat([]byte("A"), 4096)+ body := append([]byte(`{"items":["`), big...)+ body = append(body, []byte(`"]}`)...)++ h.K8sAuditEvents(rec, auditReq(t, body, "tenant-a", "right-secret"))+ if rec.Code != http.StatusRequestEntityTooLarge {+ t.Fatalf("oversize body: status = %d, want %d", rec.Code, http.StatusRequestEntityTooLarge)+ }+}++func TestK8sAuditEvents_RejectsBatchOverMaxBatchSize(t *testing.T) {+ // MaxBatchSize is per-batch, regardless of byte size. Helps catch+ // a runaway audit policy producing a million-item batch.+ h := newAuditHandler("right-secret", 16*1024*1024)+ h.cfg.MaxBatchSize = 2++ items := []string{`{"verb":"get"}`, `{"verb":"list"}`, `{"verb":"watch"}`}+ body := []byte(`{"items":[` + strings.Join(items, ",") + `]}`)++ rec := httptest.NewRecorder()+ h.K8sAuditEvents(rec, auditReq(t, body, "tenant-a", "right-secret"))++ if rec.Code != http.StatusRequestEntityTooLarge {+ t.Fatalf("over batch size: status = %d, want %d", rec.Code, http.StatusRequestEntityTooLarge)+ }+}++func TestK8sAuditEvents_AcceptsCorrectToken_EmptyBatch(t *testing.T) {+ // Empty batch is normal: the apiserver's audit-batch-period can+ // fire even when no requests landed. We must return 200, otherwise+ // the apiserver will retry the empty batch forever and tie up its+ // audit-webhook send queue.+ //+ // This case never reaches the publisher because there's nothing+ // to publish, so the nil pub field in newAuditHandler is fine.+ h := newAuditHandler("right-secret", 16*1024*1024)+ rec := httptest.NewRecorder()+ body := []byte(`{"kind":"EventList","apiVersion":"audit.k8s.io/v1","items":[]}`)+ h.K8sAuditEvents(rec, auditReq(t, body, "tenant-a", "right-secret"))++ if rec.Code != http.StatusOK {+ t.Fatalf("empty batch: status = %d body = %q, want %d", rec.Code, rec.Body.String(), http.StatusOK)+ }+ var resp map[string]interface{}+ if err := json.NewDecoder(rec.Body).Decode(&resp); err != nil {+ t.Fatalf("decode response: %v", err)+ }+ if got, _ := resp["accepted"].(float64); got != 0 {+ t.Fatalf("empty batch: accepted=%v, want 0", resp["accepted"])+ }+ if got, _ := resp["rejected"].(float64); got != 0 {+ t.Fatalf("empty batch: rejected=%v, want 0", resp["rejected"])+ }+}diff --git a/services/ingest/internal/normalizer/normalizer.go b/services/ingest/internal/normalizer/normalizer.goindex 4868a8f31..b0205489c 100644--- a/services/ingest/internal/normalizer/normalizer.go+++ b/services/ingest/internal/normalizer/normalizer.go@@ -163,6 +163,38 @@ var connectorProfiles = map[string]connectorProfile{"CRITICAL": 5, "HIGH": 4, "MEDIUM": 3, "LOW": 2, "INFORMATIONAL": 1,},},+ // kubernetes_audit — Track D, v7.1.0.+ //+ // The apiserver POSTs a v1 EventList batch and we explode it into+ // individual events upstream of Normalize, so by the time we get+ // here `payload` is one audit.k8s.io/v1 Event JSON object. Class+ // 6003 is the OCSF "API Activity" class which is the right shape+ // for a request/response style event with verb + resource + actor.+ // Severity is derived from the connector's heuristic and arrives+ // as a lowercase string; the map below mirrors KubernetesAuditConnector+ // so on-prem file_tail and webhook events end up with the same+ // severity_id.+ "kubernetes_audit": {+ product: OcsfProduct{Name: "Kubernetes Audit", VendorName: "Kubernetes"},+ classUID: 6003,+ className: "API Activity",+ fieldMap: map[string]string{+ "auditID": "finding.uid",+ "verb": "activity_name",+ "user.username": "actor.user.name",+ "objectRef.resource": "finding.title",+ "objectRef.namespace": "cloud.account.uid",+ "objectRef.name": "resource.name",+ "sourceIPs.0": "src_endpoint.ip",+ "userAgent": "http_request.user_agent",+ "responseStatus.code": "status_code",+ "stage": "status_detail",+ "stageTimestamp": "time",+ },+ severityMap: map[string]int{+ "critical": 5, "high": 4, "medium": 3, "low": 2, "info": 1, "informational": 1,+ },+ },}// New creates a new Normalizer instance and loads the ATT&CK corpus.diff --git a/services/ingest/internal/normalizer/templates/k8s-audit.yaml b/services/ingest/internal/normalizer/templates/k8s-audit.yamlnew file mode 100644index 000000000..81fa3a99b--- /dev/null+++ b/services/ingest/internal/normalizer/templates/k8s-audit.yaml@@ -0,0 +1,34 @@+id: k8s-audit+vendor_name: Kubernetes+product_name: Kubernetes Audit+class_uid: 6003+class_name: API Activity+activity_id: 1+field_map:+ auditID: finding.uid+ verb: activity_name+ user.username: actor.user.name+ objectRef.resource: finding.title+ objectRef.namespace: cloud.account.uid+ objectRef.name: resource.name+ sourceIPs.0: src_endpoint.ip+ userAgent: http_request.user_agent+ responseStatus.code: status_code+ stage: status_detail+severity_field: severity+severity_map:+ info: 1+ informational: 1+ low: 2+ medium: 3+ warning: 3+ high: 4+ critical: 5+ fatal: 6+time_field: stageTimestamp+message_field: verb+constants:+ source_type: k8s-audit+ metadata.product.vendor_name: Kubernetes+ metadata.product.name: Kubernetes Audit+ cloud.provider: kubernetesdiff --git a/services/ingest/internal/server/server.go b/services/ingest/internal/server/server.goindex 630261497..32f5939d0 100644--- a/services/ingest/internal/server/server.go+++ b/services/ingest/internal/server/server.go@@ -40,7 +40,7 @@ func New(cfg *config.Config, h *handler.Handler, inboxHandler *inbox.Handler) *Sr.Use(cors.Handler(cors.Options{AllowedOrigins: []string{"*"},AllowedMethods: []string{"GET", "POST", "OPTIONS"},- AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-Tenant-ID", "X-Inbox-Token", "X-Splunk-Token", "X-Signature", "X-Hub-Signature-256"},+ AllowedHeaders: []string{"Accept", "Authorization", "Content-Type", "X-Tenant-ID", "X-Inbox-Token", "X-Splunk-Token", "X-Signature", "X-Hub-Signature-256", "X-AiSOC-K8s-Token"},AllowCredentials: false,MaxAge: 300,}))@@ -53,6 +53,15 @@ func New(cfg *config.Config, h *handler.Handler, inboxHandler *inbox.Handler) *Sr.Post("/ingest", h.IngestEvents)r.Post("/ingest/batch", h.IngestEvents)+ // Track D / v7.1.0 — Kubernetes apiserver audit-webhook target.+ // Tenant binding lives in the URL path (the apiserver's+ // audit-webhook kubeconfig is awkward to add custom headers+ // to but trivial to point at a templated URL); the auth+ // boundary is the X-AiSOC-K8s-Token shared secret enforced+ // inside the handler. Disabled (returns 503) until an+ // operator sets K8S_AUDIT_SHARED_SECRET on the ingest pod.+ r.Post("/ingest/k8s-audit/{tenant_id}", h.K8sAuditEvents)+// Workstream 6 — universal capture push paths.// /v1/inbox/{token} → generic JSON or NDJSON webhook// /v1/inbox/email/{token} → email-relay JSON envelope