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(2.5): model AWS permissions boundaries, and version the snapshot
Beenu Arora34e396ac34b5
diff --git a/services/api/app/services/effective_permissions/aws.py b/services/api/app/services/effective_permissions/aws.pyindex a01cac497..962b1f03b 100644--- a/services/api/app/services/effective_permissions/aws.py+++ b/services/api/app/services/effective_permissions/aws.py@@ -10,7 +10,9 @@ The resolver consumes a *snapshot* JSON document of shape::"principals": [{"id": "...", "arn": "...", "type": "user|role","groups": ["...", ...], "attached_policies": ["..."],- "inline_policies": ["..."]},+ "inline_policies": ["..."],+ # policy id, resolved in "policies" below like any other+ "permissions_boundary": "p4"},...],"groups": [@@ -30,7 +32,7 @@ The resolver consumes a *snapshot* JSON document of shape::"action_catalogue": {"s3": ["s3:GetObject", "s3:PutObject", ...], ...}}-The model captures the four sources of allow/deny that govern an IAM call:+The model captures the five sources of allow/deny that govern an IAM call:1. **Identity-based policies** attached to the user, the user's groups, orthe role's inline policies. Any explicit ``Allow`` here is necessary@@ -42,26 +44,50 @@ The model captures the four sources of allow/deny that govern an IAM call:3. **Service Control Policies (SCPs)** at the organisation level. They*cannot* grant — they only narrow. The resolver intersects the candidateaction set with the union of SCP-allowed actions.-4. **Explicit deny** anywhere — always wins.+4. **Permissions boundaries** attached to the principal. A boundary is a+ managed policy that *caps* what identity-based policies may grant: the+ effective identity permission is the intersection of the two, and a+ boundary never grants anything by itself.++ The part that changes the answer on real estates, and is easy to get+ wrong: a boundary does **not** cap a resource-based policy that names the+ principal directly. A bucket policy granting this role ``s3:GetObject``+ works whether or not the boundary mentions S3. Intersecting the whole+ candidate set with the boundary would therefore *under*-report a real,+ reachable permission — and under-reporting on a containment decision+ reads as "this identity cannot touch the data" when it can.++ A ``Deny`` written inside a boundary document is an ordinary explicit+ deny and wins over everything, resource policies included.++5. **Explicit deny** anywhere — always wins.For each ``(principal, resource)`` pair the algorithm is:* Collect all statements that match the principal + resource ARN (withwildcard expansion against the resource's ``service_actions`` catalogue).* Partition by effect into ``allow_actions`` and ``deny_actions``.+* Cap the identity-derived allows by the permissions boundary, if any.* Compute the SCP-allowed action set (union over SCP allow statements thatmatch the resource ARN).-* The final ``actions`` = ``allow_actions − deny_actions ∩ scp_allowed``.-* The ``deny_actions`` list returned to the UI is the intersection of- ``allow_actions`` and the deny set — i.e. the actions some upstream policy- *tried* to grant but a higher-priority policy blocked.--The full set of IAM features (NotAction, NotResource, condition operators-beyond StringEquals/StringLike, session policies, permissions boundaries) is-not modelled — those are flagged as ``notes`` on :class:`ResolverResult` so-the UI can surface "this resolver doesn't yet model X" instead of silently-returning a wrong answer. The synthesised simulator fixture exercises every-feature the resolver does model so the test gate is meaningful.+* The final ``actions`` =+ ``((identity_allow ∩ boundary) ∪ resource_allow) − deny_actions ∩ scp_allowed``.+* The ``deny_actions`` list returned to the UI is every action some policy+ *tried* to grant that something higher-priority removed — an explicit+ deny, an SCP that excluded it, or a boundary that capped it away. A+ boundary-capped action is reported even though it never entered the+ candidate set, because the whole value of a boundary to a reviewer is+ seeing what it stopped, and an action that silently never appears is+ indistinguishable from one nobody ever granted.++Still not modelled: ``NotAction``, ``NotResource``, condition operators+beyond StringEquals/StringLike, and session policies. Those are flagged as+``notes`` on :class:`ResolverResult` so the UI can surface "this resolver+doesn't yet model X" instead of silently returning a wrong answer — as is a+boundary that is attached to the principal but absent from the snapshot,+which cannot be applied and would otherwise over-permit in exactly the case+the boundary exists to prevent. The synthesised simulator fixture exercises+every feature the resolver does model so the test gate is meaningful."""from __future__ import annotations@@ -220,6 +246,17 @@ class AwsIamResolver(Resolver):identity_policy_refs = self._collect_identity_policies(principal, groups_by_id)notes: list[str] = []+ boundary_id = principal.get("permissions_boundary")+ if boundary_id and boundary_id not in policies_by_id:+ # The principal is capped by a policy the snapshot does not+ # contain, so the cap cannot be applied. Reporting the+ # uncapped answer silently would over-permit in exactly the+ # case the boundary exists to prevent.+ notes.append(+ f"permissions boundary {boundary_id!r} is attached to the principal but absent from "+ f"the snapshot — the cap could not be applied and these actions may over-permit"+ )+decisions: list[ResolvedPermission] = []for resource in snap.get("resources", []):decision = self._resolve_resource(@@ -233,9 +270,6 @@ class AwsIamResolver(Resolver):if decision is not None:decisions.append(decision)- if any(p.get("permissions_boundary") for p in [principal]):- notes.append("permissions-boundary present on principal — not modelled; deny-side may over-permit")-return ResolverResult(provider=self.provider,principal_id=principal_id,@@ -346,8 +380,63 @@ class AwsIamResolver(Resolver):))- candidate_allow = identity_allow | resource_allow- candidate_deny = identity_deny | resource_deny+ # Permissions boundary. A boundary is a managed policy attached to a+ # principal that caps what its *identity* policies can grant: the+ # effective identity permission is the intersection of the two, and a+ # boundary never grants anything on its own.+ #+ # The exception is the part that is easy to get wrong and changes the+ # answer on real estates: AWS does **not** apply the boundary to a+ # resource-based policy that names the principal directly. A bucket+ # policy granting this role `s3:GetObject` works whether or not the+ # boundary mentions S3, so intersecting the whole candidate set with+ # the boundary would under-report a real, reachable permission -- and+ # under-reporting on a containment decision reads as "this identity+ # cannot touch the data" when it can.+ boundary_allowed: set[str] | None = None+ # Kept separate from identity_deny and resource_deny rather than+ # folded into either. Both of those flow into one `candidate_deny`+ # union below, so adding a boundary deny to either would have the+ # same effect and adding it to both is dead code that reads as+ # though it covers two arms.+ boundary_deny: set[str] = set()+ boundary_allow: set[str] = set()+ boundary_id = principal.get("permissions_boundary")+ boundary = policies_by_id.get(boundary_id) if boundary_id else None+ if boundary is not None:+ boundary_allow, boundary_deny = self._evaluate_policy(+ policy=boundary,+ principal_arn=principal["arn"],+ resource_arn=resource_arn,+ context=context,+ catalogue=service_catalogue,+ principal_match_required=False,+ )+ boundary_allowed = boundary_allow++ identity_capped = identity_allow+ boundary_blocked: set[str] = set()+ if boundary_allowed is not None:+ identity_capped = identity_allow & boundary_allowed+ boundary_blocked = identity_allow - boundary_allowed+ if boundary_allow or boundary_blocked:+ chain.append(+ PolicyChainStep(+ kind="permissions-boundary",+ id=boundary_id,+ name=boundary.get("name", boundary_id),+ # A cap reads as a deny in the provenance pane,+ # because what an analyst needs to see is the hop+ # that removed an action somebody granted.+ effect="deny" if boundary_blocked else "allow",+ )+ )++ candidate_allow = identity_capped | resource_allow+ # A Deny written inside a boundary document is an ordinary explicit+ # deny, not a cap, so it joins the deny set and outranks the+ # resource-policy arm as well as the identity arm.+ candidate_deny = identity_deny | resource_deny | boundary_deny# Track the *pre-SCP* allow set so shadowed-denies surfaces actions# that some upstream policy tried to grant but were blocked at the@@ -399,9 +488,15 @@ class AwsIamResolver(Resolver):final_actions = candidate_allow - candidate_deny# shadowed = (1) actions both sides tried to allow + an explicit deny- # blocked, OR (2) actions an identity/resource policy granted that- # the SCP excluded from the org allow-set.- shadowed_denies = (pre_scp_allow & candidate_deny) | scp_blocked+ # blocked, (2) actions an identity/resource policy granted that+ # the SCP excluded from the org allow-set, or (3) actions an identity+ # policy granted that the permissions boundary caps away.+ #+ # (3) is reported even though the action never entered candidate_allow:+ # the whole value of a boundary to a reviewer is seeing *what it+ # stopped*, and an action that silently never appears is+ # indistinguishable from one nobody ever granted.+ shadowed_denies = (pre_scp_allow & candidate_deny) | scp_blocked | boundary_blockedif not final_actions and not shadowed_denies:return Nonediff --git a/services/api/migrations/103_posture_snapshots.sql b/services/api/migrations/103_posture_snapshots.sqlnew file mode 100644index 000000000..3cb1e7200--- /dev/null+++ b/services/api/migrations/103_posture_snapshots.sql@@ -0,0 +1,136 @@+-- 103: versioned posture snapshots (depth plan 2.5).+--+-- Why a table and not a cache+-- ---------------------------+-- The resolver in `services/api/app/services/effective_permissions/` is pure:+-- it takes a snapshot and computes what a principal can do. Until now the+-- only production snapshot source returned `{}`, so every live call 412'd and+-- the whole subsystem had never answered a question about a real estate.+--+-- Collecting one is half the job. The other half is *when* it was true. An+-- alert is triaged minutes to days after the event, and the question an+-- analyst asks is "what could this identity do **at the time it acted**" --+-- not what it can do now, after someone revoked the role. A single mutable+-- "current posture" row answers the second question while appearing to answer+-- the first, which is the worse failure of the two because the number looks+-- right.+--+-- So snapshots are versioned and closed rather than overwritten:+-- `valid_until IS NULL` is the live one, and a lookup at an event timestamp+-- selects the row whose interval contains it.+--+-- Spelling+-- --------+-- `valid_from` / `valid_until`, matching `identity_edges` in migration 018 --+-- the one existing table in this database that bounds a fact in time. The+-- depth plan says `valid_to`; adopting it would put two spellings of one+-- concept in one schema, so the existing one wins and the deviation is+-- recorded in DEPTH_PROGRESS.md rather than made silently.++CREATE TABLE IF NOT EXISTS posture_snapshots (+ id uuid PRIMARY KEY DEFAULT gen_random_uuid(),+ tenant_id uuid NOT NULL,++ -- The identity provider the snapshot describes, not the connector that+ -- fetched it: two connectors may both be able to read AWS IAM, and a+ -- resolver asks for a provider.+ provider text NOT NULL,+ -- Which connector actually produced it, so an operator can tell a stale+ -- snapshot's source without reading the blob.+ connector_id text NOT NULL,+ connector_instance_id uuid,++ snapshot jsonb NOT NULL,++ -- sha256 over the canonical form of `snapshot`. A collector that runs+ -- every hour against an estate nobody changed would otherwise write a new+ -- version every hour, and "when did this posture last change" -- the+ -- question a drift reviewer asks -- would be unanswerable because every+ -- row is a change. An unchanged collection extends the live row instead.+ content_hash text NOT NULL,++ -- Counted at write time from the snapshot the collector returned, so a+ -- reader can see an empty or truncated collection without parsing jsonb.+ -- A snapshot that collected nothing is a real and important state: it+ -- means the credential lost its read permission, not that the estate is+ -- empty.+ principal_count integer NOT NULL DEFAULT 0,+ resource_count integer NOT NULL DEFAULT 0,+ policy_count integer NOT NULL DEFAULT 0,++ -- What the collector could not see. Carried as data rather than logged,+ -- because the resolver's answer is only as complete as its input and the+ -- triage surface has to be able to say so.+ partial boolean NOT NULL DEFAULT false,+ collection_notes jsonb NOT NULL DEFAULT '[]'::jsonb,++ -- When the collector finished reading the provider. Distinct from+ -- valid_from, which is when this *version* became the one in force --+ -- they differ on a re-collection that found no change.+ collected_at timestamptz NOT NULL DEFAULT now(),+ collection_ms integer,++ valid_from timestamptz NOT NULL DEFAULT now(),+ -- NULL means in force. Set when a later version supersedes it.+ valid_until timestamptz,++ created_at timestamptz NOT NULL DEFAULT now(),++ CONSTRAINT posture_snapshots_provider_check CHECK (+ provider IN ('aws', 'azure', 'gcp', 'gws', 'github', 'okta')+ ),+ -- An interval that ends before it starts would silently match nothing,+ -- and a lookup returning no snapshot is indistinguishable from a tenant+ -- that never collected one.+ CONSTRAINT posture_snapshots_interval_check CHECK (+ valid_until IS NULL OR valid_until >= valid_from+ )+);++-- At most one live version per provider per tenant. This is the invariant the+-- whole table rests on: two rows with `valid_until IS NULL` make "the current+-- posture" ambiguous, and the resolver would pick whichever the planner+-- returned first. A partial unique index refuses it in the database rather+-- than trusting every writer to close the old row first.+CREATE UNIQUE INDEX IF NOT EXISTS posture_snapshots_live_idx+ ON posture_snapshots (tenant_id, provider)+ WHERE valid_until IS NULL;++-- The point-in-time lookup: newest version whose interval contains an event+-- timestamp.+CREATE INDEX IF NOT EXISTS posture_snapshots_at_idx+ ON posture_snapshots (tenant_id, provider, valid_from DESC);++-- "Has this estate's posture changed since we last looked", without reading+-- the blob.+CREATE INDEX IF NOT EXISTS posture_snapshots_hash_idx+ ON posture_snapshots (tenant_id, provider, content_hash);++COMMENT ON TABLE posture_snapshots IS+ 'Versioned identity-posture snapshots per provider. valid_until IS NULL is the version in force; '+ 'a lookup at an event timestamp selects the version that was in force when the event happened, '+ 'because what an identity can do now is a different question from what it could do when it acted.';++COMMENT ON COLUMN posture_snapshots.content_hash IS+ 'sha256 of the canonical snapshot. An unchanged re-collection extends the live row rather than '+ 'writing a new version, so every row in the history is a real posture change.';++COMMENT ON COLUMN posture_snapshots.partial IS+ 'True when the collector could not read part of the estate. The resolver answer is only as '+ 'complete as its input, and a surface that cannot say so will present a gap as an absence.';++DO $$+BEGIN+ EXECUTE 'ALTER TABLE posture_snapshots ENABLE ROW LEVEL SECURITY';+ EXECUTE 'ALTER TABLE posture_snapshots FORCE ROW LEVEL SECURITY';+ EXECUTE 'DROP POLICY IF EXISTS tenant_isolation ON posture_snapshots';+ EXECUTE+ 'CREATE POLICY tenant_isolation ON posture_snapshots '+ 'USING (tenant_id = current_tenant_id() OR current_tenant_id() IS NULL) '+ 'WITH CHECK (tenant_id = current_tenant_id())';++ IF EXISTS (SELECT 1 FROM pg_roles WHERE rolname = 'aisoc_app') THEN+ EXECUTE 'GRANT SELECT, INSERT, UPDATE, DELETE ON posture_snapshots TO aisoc_app';+ END IF;+END+$$;diff --git a/services/api/tests/fixtures/aws_iam_complex.json b/services/api/tests/fixtures/aws_iam_complex.jsonindex 8544ea505..79f1a2c18 100644--- a/services/api/tests/fixtures/aws_iam_complex.json+++ b/services/api/tests/fixtures/aws_iam_complex.json@@ -1,27 +1,48 @@{- "_about": "Complex AWS IAM fixture for the T3.2 effective-permissions resolver. Exercises identity-based policies (direct + via group), resource-based policies (S3 bucket policy, KMS key policy, SQS queue policy), Service Control Policies (allow-list + explicit deny), wildcard expansion against a per-resource action catalogue, conditions (StringEquals, StringLike), and deny-overrides. The aligned `aws_iam_simulator.json` next to this fixture is the synthesised IAM Policy Simulator reference set the test gate compares against — it captures, for 50 (principal, resource) pairs, the exact allow set every public IAM call resolves to with the same input.",+ "_about": "Complex AWS IAM fixture for the T3.2 effective-permissions resolver. Exercises identity-based policies (direct + via group), resource-based policies (S3 bucket policy, KMS key policy, SQS queue policy), Service Control Policies (allow-list + explicit deny), wildcard expansion against a per-resource action catalogue, conditions (StringEquals, StringLike), and deny-overrides. The aligned `aws_iam_simulator.json` next to this fixture is the synthesised IAM Policy Simulator reference set the test gate compares against \u2014 it captures, for 50 (principal, resource) pairs, the exact allow set every public IAM call resolves to with the same input.","account_id": "111122223333","action_catalogue": {"s3": [- "s3:GetObject", "s3:PutObject", "s3:DeleteObject", "s3:ListBucket",- "s3:GetBucketAcl", "s3:PutBucketAcl", "s3:GetObjectVersion",- "s3:PutBucketPolicy", "s3:DeleteBucket", "s3:GetBucketLocation"+ "s3:GetObject",+ "s3:PutObject",+ "s3:DeleteObject",+ "s3:ListBucket",+ "s3:GetBucketAcl",+ "s3:PutBucketAcl",+ "s3:GetObjectVersion",+ "s3:PutBucketPolicy",+ "s3:DeleteBucket",+ "s3:GetBucketLocation"],"kms": [- "kms:Decrypt", "kms:Encrypt", "kms:GenerateDataKey", "kms:DescribeKey",- "kms:ListKeys", "kms:ScheduleKeyDeletion"+ "kms:Decrypt",+ "kms:Encrypt",+ "kms:GenerateDataKey",+ "kms:DescribeKey",+ "kms:ListKeys",+ "kms:ScheduleKeyDeletion"],"sqs": [- "sqs:SendMessage", "sqs:ReceiveMessage", "sqs:DeleteMessage",- "sqs:GetQueueAttributes", "sqs:PurgeQueue"+ "sqs:SendMessage",+ "sqs:ReceiveMessage",+ "sqs:DeleteMessage",+ "sqs:GetQueueAttributes",+ "sqs:PurgeQueue"],"ec2": [- "ec2:DescribeInstances", "ec2:StartInstances", "ec2:StopInstances",- "ec2:TerminateInstances", "ec2:RunInstances"+ "ec2:DescribeInstances",+ "ec2:StartInstances",+ "ec2:StopInstances",+ "ec2:TerminateInstances",+ "ec2:RunInstances"],"iam": [- "iam:GetRole", "iam:PassRole", "iam:CreateRole", "iam:DeleteRole",- "iam:ListRoles", "iam:AttachRolePolicy"+ "iam:GetRole",+ "iam:PassRole",+ "iam:CreateRole",+ "iam:DeleteRole",+ "iam:ListRoles",+ "iam:AttachRolePolicy"]},"principals": [@@ -29,23 +50,34 @@"id": "u-alice","arn": "arn:aws:iam::111122223333:user/alice","type": "user",- "groups": ["g-data-readers"],- "attached_policies": ["p-alice-direct"],+ "groups": [+ "g-data-readers"+ ],+ "attached_policies": [+ "p-alice-direct"+ ],"inline_policies": []},{"id": "u-bob","arn": "arn:aws:iam::111122223333:user/bob","type": "user",- "groups": ["g-data-writers"],+ "groups": [+ "g-data-writers"+ ],"attached_policies": [],- "inline_policies": ["p-bob-inline"]+ "inline_policies": [+ "p-bob-inline"+ ]},{"id": "u-carol","arn": "arn:aws:iam::111122223333:user/carol","type": "user",- "groups": ["g-data-readers", "g-data-writers"],+ "groups": [+ "g-data-readers",+ "g-data-writers"+ ],"attached_policies": [],"inline_policies": []},@@ -54,7 +86,9 @@"arn": "arn:aws:iam::111122223333:user/dave","type": "user","groups": [],- "attached_policies": ["p-dave-admin"],+ "attached_policies": [+ "p-dave-admin"+ ],"inline_policies": []},{@@ -62,7 +96,9 @@"arn": "arn:aws:iam::111122223333:role/pipeline-runner","type": "role","groups": [],- "attached_policies": ["p-pipeline-cicd"],+ "attached_policies": [+ "p-pipeline-cicd"+ ],"inline_policies": []},{@@ -70,7 +106,30 @@"arn": "arn:aws:iam::111122223333:user/erin","type": "user","groups": [],- "attached_policies": ["p-erin-conditional"],+ "attached_policies": [+ "p-erin-conditional"+ ],+ "inline_policies": []+ },+ {+ "id": "u-frank",+ "arn": "arn:aws:iam::111122223333:user/frank",+ "type": "user",+ "groups": [+ "g-data-writers"+ ],+ "attached_policies": [],+ "inline_policies": [],+ "permissions_boundary": "p-boundary-s3-read"+ },+ {+ "id": "u-gina",+ "arn": "arn:aws:iam::111122223333:user/gina",+ "type": "user",+ "groups": [+ "g-data-writers"+ ],+ "attached_policies": [],"inline_policies": []}],@@ -78,13 +137,18 @@{"id": "g-data-readers","name": "DataReaders",- "attached_policies": ["p-readers-s3"],+ "attached_policies": [+ "p-readers-s3"+ ],"inline_policies": []},{"id": "g-data-writers","name": "DataWriters",- "attached_policies": ["p-writers-s3", "p-writers-sqs"],+ "attached_policies": [+ "p-writers-s3",+ "p-writers-sqs"+ ],"inline_policies": []}],@@ -98,7 +162,10 @@"Statement": [{"Effect": "Allow",- "Action": ["kms:Decrypt", "kms:DescribeKey"],+ "Action": [+ "kms:Decrypt",+ "kms:DescribeKey"+ ],"Resource": "arn:aws:kms:us-east-1:111122223333:key/finance"}]@@ -143,7 +210,10 @@"Statement": [{"Effect": "Allow",- "Action": ["s3:Get*", "s3:List*"],+ "Action": [+ "s3:Get*",+ "s3:List*"+ ],"Resource": ["arn:aws:s3:::artifacts-prod","arn:aws:s3:::artifacts-prod/*"@@ -169,7 +239,9 @@"Action": "s3:GetObject","Resource": "arn:aws:s3:::reports-prod/*","Condition": {- "StringEquals": {"aws:RequestedRegion": "us-east-1"}+ "StringEquals": {+ "aws:RequestedRegion": "us-east-1"+ }}}]@@ -184,7 +256,10 @@"Statement": [{"Effect": "Allow",- "Action": ["s3:GetObject", "s3:ListBucket"],+ "Action": [+ "s3:GetObject",+ "s3:ListBucket"+ ],"Resource": ["arn:aws:s3:::reports-prod","arn:aws:s3:::reports-prod/*"@@ -202,7 +277,10 @@"Statement": [{"Effect": "Allow",- "Action": ["s3:PutObject", "s3:DeleteObject"],+ "Action": [+ "s3:PutObject",+ "s3:DeleteObject"+ ],"Resource": "arn:aws:s3:::reports-prod/*"}]@@ -217,7 +295,10 @@"Statement": [{"Effect": "Allow",- "Action": ["sqs:SendMessage", "sqs:GetQueueAttributes"],+ "Action": [+ "sqs:SendMessage",+ "sqs:GetQueueAttributes"+ ],"Resource": "arn:aws:sqs:us-east-1:111122223333:ingest-queue"}]@@ -238,7 +319,9 @@},{"Effect": "Allow",- "Principal": {"AWS": "arn:aws:iam::111122223333:role/pipeline-runner"},+ "Principal": {+ "AWS": "arn:aws:iam::111122223333:role/pipeline-runner"+ },"Action": "s3:PutObject","Resource": "arn:aws:s3:::reports-prod/*"}@@ -254,9 +337,22 @@"Statement": [{"Effect": "Allow",- "Principal": {"AWS": "*"},+ "Principal": {+ "AWS": "*"+ },"Action": "s3:GetObject","Resource": "arn:aws:s3:::artifacts-prod/*"+ },+ {+ "Effect": "Allow",+ "Principal": {+ "AWS": "arn:aws:iam::111122223333:user/frank"+ },+ "Action": [+ "s3:PutObject",+ "s3:DeleteObject"+ ],+ "Resource": "arn:aws:s3:::artifacts-prod/*"}]}@@ -270,8 +366,14 @@"Statement": [{"Effect": "Allow",- "Principal": {"AWS": "arn:aws:iam::111122223333:user/alice"},- "Action": ["kms:Decrypt", "kms:Encrypt", "kms:DescribeKey"],+ "Principal": {+ "AWS": "arn:aws:iam::111122223333:user/alice"+ },+ "Action": [+ "kms:Decrypt",+ "kms:Encrypt",+ "kms:DescribeKey"+ ],"Resource": "*"},{@@ -292,7 +394,9 @@"Statement": [{"Effect": "Allow",- "Principal": {"AWS": "arn:aws:iam::111122223333:role/pipeline-runner"},+ "Principal": {+ "AWS": "arn:aws:iam::111122223333:role/pipeline-runner"+ },"Action": "sqs:SendMessage","Resource": "*"}@@ -309,7 +413,11 @@{"Effect": "Allow","Action": [- "s3:*", "kms:*", "sqs:*", "ec2:Describe*", "iam:Get*"+ "s3:*",+ "kms:*",+ "sqs:*",+ "ec2:Describe*",+ "iam:Get*"],"Resource": "*"}@@ -325,7 +433,11 @@"Statement": [{"Effect": "Deny",- "Action": ["iam:CreateRole", "iam:DeleteRole", "iam:AttachRolePolicy"],+ "Action": [+ "iam:CreateRole",+ "iam:DeleteRole",+ "iam:AttachRolePolicy"+ ],"Resource": "*"},{@@ -335,9 +447,35 @@}]}+ },+ {+ "id": "p-boundary-s3-read",+ "name": "BoundaryS3ReadOnly",+ "kind": "identity",+ "document": {+ "Version": "2012-10-17",+ "Statement": [+ {+ "Effect": "Allow",+ "Action": [+ "s3:Get*",+ "s3:List*"+ ],+ "Resource": "*"+ },+ {+ "Effect": "Deny",+ "Action": "s3:DeleteObject",+ "Resource": "*"+ }+ ]+ }}],- "scps": ["p-scp-allow-baseline", "p-scp-deny-iam-write"],+ "scps": [+ "p-scp-allow-baseline",+ "p-scp-deny-iam-write"+ ],"resources": [{"id": "res-bucket-reports",@@ -345,11 +483,15 @@"kind": "s3:object","service": "s3","service_actions": [- "s3:GetObject", "s3:PutObject", "s3:DeleteObject",+ "s3:GetObject",+ "s3:PutObject",+ "s3:DeleteObject","s3:GetObjectVersion"],"resource_policy_id": "p-bucket-reports",- "context": {"aws:RequestedRegion": "us-east-1"}+ "context": {+ "aws:RequestedRegion": "us-east-1"+ }},{"id": "res-bucket-reports-bucket",@@ -357,8 +499,11 @@"kind": "s3:bucket","service": "s3","service_actions": [- "s3:ListBucket", "s3:DeleteBucket", "s3:GetBucketAcl",- "s3:PutBucketAcl", "s3:GetBucketLocation"+ "s3:ListBucket",+ "s3:DeleteBucket",+ "s3:GetBucketAcl",+ "s3:PutBucketAcl",+ "s3:GetBucketLocation"],"resource_policy_id": "p-bucket-reports"},@@ -367,7 +512,11 @@"arn": "arn:aws:s3:::artifacts-prod/build.tgz","kind": "s3:object","service": "s3",- "service_actions": ["s3:GetObject", "s3:PutObject"],+ "service_actions": [+ "s3:GetObject",+ "s3:PutObject",+ "s3:DeleteObject"+ ],"resource_policy_id": "p-bucket-artifacts"},{@@ -375,7 +524,10 @@"arn": "arn:aws:s3:::artifacts-prod","kind": "s3:bucket","service": "s3",- "service_actions": ["s3:ListBucket", "s3:GetBucketLocation"],+ "service_actions": [+ "s3:ListBucket",+ "s3:GetBucketLocation"+ ],"resource_policy_id": "p-bucket-artifacts"},{@@ -384,8 +536,11 @@"kind": "kms:key","service": "kms","service_actions": [- "kms:Decrypt", "kms:Encrypt", "kms:GenerateDataKey",- "kms:DescribeKey", "kms:ScheduleKeyDeletion"+ "kms:Decrypt",+ "kms:Encrypt",+ "kms:GenerateDataKey",+ "kms:DescribeKey",+ "kms:ScheduleKeyDeletion"],"resource_policy_id": "p-key-finance"},@@ -395,8 +550,11 @@"kind": "sqs:queue","service": "sqs","service_actions": [- "sqs:SendMessage", "sqs:ReceiveMessage", "sqs:DeleteMessage",- "sqs:GetQueueAttributes", "sqs:PurgeQueue"+ "sqs:SendMessage",+ "sqs:ReceiveMessage",+ "sqs:DeleteMessage",+ "sqs:GetQueueAttributes",+ "sqs:PurgeQueue"],"resource_policy_id": "p-queue-ingest"},@@ -406,7 +564,10 @@"kind": "iam:role","service": "iam","service_actions": [- "iam:GetRole", "iam:PassRole", "iam:CreateRole", "iam:DeleteRole",+ "iam:GetRole",+ "iam:PassRole",+ "iam:CreateRole",+ "iam:DeleteRole","iam:AttachRolePolicy"]}diff --git a/services/api/tests/test_effective_permissions_aws.py b/services/api/tests/test_effective_permissions_aws.pyindex 5ba70cac7..b6cb6d274 100644--- a/services/api/tests/test_effective_permissions_aws.py+++ b/services/api/tests/test_effective_permissions_aws.py@@ -130,8 +130,15 @@ def reference_is_allowed(Implements the public AWS evaluation rules:explicit deny anywhere → DENYSCP doesn't allow → DENY (across the org boundary)- identity allow OR (resource allow on named principal) → ALLOW+ (identity allow AND permissions boundary allows)+ OR (resource allow on named principal) → ALLOWotherwise → DENY (default deny)++ The boundary clause is deliberately written as a conjunction on the+ *identity* arm only. A permissions boundary does not cap a+ resource-based policy that names the principal directly, so hoisting it+ to the whole disjunction would be the plausible wrong answer — and one+ that under-reports access an attacker really has."""principal = next(p for p in snapshot["principals"] if p["id"] == principal_id)@@ -149,6 +156,14 @@ def reference_is_allowed(if scp_id in policies_by_id:deny_sources.append(policies_by_id[scp_id])+ # A Deny written inside a boundary document is an ordinary explicit deny+ # and outranks even a resource policy, so it belongs here rather than in+ # the capping step below.+ boundary_id = principal.get("permissions_boundary")+ boundary = policies_by_id.get(boundary_id) if boundary_id else None+ if boundary is not None:+ deny_sources.append(boundary)+for policy in deny_sources:is_resource_policy = policy.get("kind") == "resource"for stmt in _as_list(policy.get("document", {}).get("Statement")):@@ -184,9 +199,12 @@ def reference_is_allowed(if not scp_allows:return False- # 3. Identity allow OR resource allow on named principal.- for policy in _gather_identity_policies(principal, snapshot):- for stmt in _as_list(policy.get("document", {}).get("Statement")):+ # 3a. Does the boundary permit this action at all? Computed once, before+ # the identity arm, because it gates that arm and nothing else.+ boundary_permits = True+ if boundary is not None:+ boundary_permits = False+ for stmt in _as_list(boundary.get("document", {}).get("Statement")):if stmt.get("Effect") != "Allow":continueif not _resource_match(stmt.get("Resource", "*"), resource_arn):@@ -194,7 +212,22 @@ def reference_is_allowed(if not _condition_match(stmt.get("Condition"), ctx):continueif _action_match(stmt.get("Action"), action):- return True+ boundary_permits = True+ break++ # 3b. Identity allow (capped by the boundary) OR resource allow on a+ # named principal (not capped).+ if boundary_permits:+ for policy in _gather_identity_policies(principal, snapshot):+ for stmt in _as_list(policy.get("document", {}).get("Statement")):+ if stmt.get("Effect") != "Allow":+ continue+ if not _resource_match(stmt.get("Resource", "*"), resource_arn):+ continue+ if not _condition_match(stmt.get("Condition"), ctx):+ continue+ if _action_match(stmt.get("Action"), action):+ return Trueif rp_id and rp_id in policies_by_id:rp = policies_by_id[rp_id]@@ -258,9 +291,21 @@ def test_fixture_exposes_at_least_50_pairs(snapshot: dict[str, Any]) -> None:@pytest.fixture(scope="module")def reference_pairs(snapshot: dict[str, Any]) -> list[tuple[str, str, set[str]]]:- """Compute reference allow-sets for 50 pairs (42 base + 8 extras)."""+ """Compute reference allow-sets for **every** principal × resource pair.++ This used to take ``pairs[:50]`` against a fixture that produced exactly+ 50. Adding the two permissions-boundary principals took the product to+ 56, so the slice started *rotating* coverage rather than extending it —+ and the pair it dropped first was the uncapped control, which is the+ one that proves the cap is doing the work. A slice that silently+ narrows when the fixture grows is a gate that weakens as the thing it+ guards gets more interesting.++ The floor below stays, because the point of the original number was+ "enough pairs to be meaningful", and that is worth keeping as an+ assertion rather than as a comment.+ """- base = _all_pairs(snapshot)extras = [# Same fixture re-evaluated — exercises the resolver's caching boundary.("u-alice", "res-key-finance"),@@ -272,17 +317,17 @@ def reference_pairs(snapshot: dict[str, Any]) -> list[tuple[str, str, set[str]]]("u-erin", "res-bucket-reports"),("u-alice", "res-bucket-artifacts"),]- pairs = base + extras+ pairs = _all_pairs(snapshot) + extrasassert len(pairs) >= 50, f"expected ≥50 pairs, got {len(pairs)}"- return [(pid, rid, reference_decision(snapshot, pid, rid)) for pid, rid in pairs[:50]]+ return [(pid, rid, reference_decision(snapshot, pid, rid)) for pid, rid in pairs]-def test_resolver_matches_reference_simulator_on_50_pairs(+def test_resolver_matches_reference_simulator_on_every_pair(snapshot: dict[str, Any],reference_pairs: list[tuple[str, str, set[str]]],) -> None:"""Resolver allow-set must equal the reference simulator's allow-set on- every one of the 50 sampled (principal, resource) pairs.+ every (principal, resource) pair the fixture can produce."""resolver = AwsIamResolver(snapshot=snapshot)@@ -437,3 +482,131 @@ def test_resolver_result_serialises_to_dict(snapshot: dict[str, Any]) -> None:if payload["decisions"]:decision = payload["decisions"][0]assert {"actions", "policy_chain", "resource_id"} <= decision.keys()+++# ---------------------------------------------------------------------------+# Permissions boundaries (depth plan 2.5)+#+# Before this, `aws.py` detected a boundary and appended a note saying the+# deny side "may over-permit" — so the resolver returned the *uncapped*+# answer and labelled it. A containment decision taken on that answer+# over-states what an identity can reach.+#+# The three cases below are the ones that distinguish a correct model from+# a plausible wrong one, so each is asserted separately rather than folded+# into the 50-pair cross-check.+# ---------------------------------------------------------------------------+++def _actions_for(result: Any, resource_id: str) -> set[str]:+ for decision in result.decisions:+ if decision.resource_id == resource_id:+ return set(decision.actions)+ return set()+++def _denies_for(result: Any, resource_id: str) -> set[str]:+ for decision in result.decisions:+ if decision.resource_id == resource_id:+ return set(decision.deny_actions)+ return set()+++def test_a_boundary_caps_what_an_identity_policy_granted(+ snapshot: dict[str, Any],+) -> None:+ """frank's group grants s3:PutObject on reports-prod; his boundary+ permits only reads. The capped action must be gone."""++ frank = AwsIamResolver(snapshot=snapshot).resolve("u-frank")+ assert "s3:PutObject" not in _actions_for(frank, "res-bucket-reports")+++def test_the_cap_is_the_boundary_and_not_something_else_about_frank(+ snapshot: dict[str, Any],+) -> None:+ """The positive control. gina carries identical group membership and no+ boundary, so she must keep the action frank lost.++ Without this, a resolver that dropped the grant for an unrelated reason+ — a broken group walk, a bad ARN match — would pass the test above and+ look like a working boundary."""++ resolver = AwsIamResolver(snapshot=snapshot)+ gina = resolver.resolve("u-gina")+ frank = resolver.resolve("u-frank")++ assert "s3:PutObject" in _actions_for(gina, "res-bucket-reports")+ assert "s3:PutObject" not in _actions_for(frank, "res-bucket-reports")+++def test_a_boundary_does_not_cap_a_resource_policy_naming_the_principal(+ snapshot: dict[str, Any],+) -> None:+ """The case a plausible wrong implementation gets backwards.++ The artifacts bucket policy names frank's ARN and grants s3:PutObject.+ His boundary does not permit PutObject anywhere. AWS applies a boundary+ to identity-based policies only, so this grant stands — and a resolver+ that intersected the whole candidate set with the boundary would report+ that frank cannot write to a bucket he can write to."""++ frank = AwsIamResolver(snapshot=snapshot).resolve("u-frank")+ assert "s3:PutObject" in _actions_for(frank, "res-bucket-artifacts")+++def test_a_deny_inside_a_boundary_outranks_a_resource_policy(+ snapshot: dict[str, Any],+) -> None:+ """A Deny written in a boundary document is an ordinary explicit deny,+ not a cap, so it wins over the resource-policy arm too."""++ frank = AwsIamResolver(snapshot=snapshot).resolve("u-frank")+ for resource_id in ("res-bucket-reports", "res-bucket-artifacts"):+ assert "s3:DeleteObject" not in _actions_for(frank, resource_id)+++def test_a_capped_action_is_reported_rather_than_silently_absent(+ snapshot: dict[str, Any],+) -> None:+ """What the boundary stopped is the whole reason a reviewer looks.++ An action that simply never appears is indistinguishable from one+ nobody ever granted, so the cap surfaces in deny_actions and the+ boundary appears as a hop in the provenance chain."""++ frank = AwsIamResolver(snapshot=snapshot).resolve("u-frank")+ assert "s3:PutObject" in _denies_for(frank, "res-bucket-reports")++ kinds = {+ step.kind+ for decision in frank.decisions+ for step in decision.policy_chain+ }+ assert "permissions-boundary" in kinds+++def test_an_unresolvable_boundary_says_so_instead_of_over_permitting(+ snapshot: dict[str, Any],+) -> None:+ """A boundary attached to the principal but missing from the snapshot+ cannot be applied. Reporting the uncapped answer silently would+ over-permit in exactly the case the boundary exists to prevent, so the+ result carries a note naming the policy id."""++ broken = json.loads(json.dumps(snapshot))+ broken["policies"] = [p for p in broken["policies"] if p["id"] != "p-boundary-s3-read"]++ result = AwsIamResolver(snapshot=broken).resolve("u-frank")+ assert any("p-boundary-s3-read" in note for note in result.notes)+ assert any("over-permit" in note for note in result.notes)+++def test_the_resolver_no_longer_claims_boundaries_are_unmodelled(+ snapshot: dict[str, Any],+) -> None:+ """The note this replaced said the deny side 'may over-permit' whenever+ a boundary was present. It must not fire when the boundary resolved."""++ frank = AwsIamResolver(snapshot=snapshot).resolve("u-frank")+ assert not any("not modelled" in note for note in frank.notes)