# Server-side enforcement

The coding-agent hook stops a destructive command **before it runs on the agent's machine**. It
cannot stop an agent that calls a cloud API some other way: an SDK, a script it wrote, a
credential it found. Server-side enforcement compiles the same verified policy into the
platform's own controls, so the platform refuses the call whatever the client.

← back to the [README](https://github.com/moneytool/aegis-devops#readme) · design: [`dev/DESIGN-v0.3-server-side.md`](https://github.com/moneytool/aegis-devops/blob/main/docs/dev/DESIGN-v0.3-server-side.md)

> **Status: preview.** `aegis compile aws` is implemented, and every action mapping was verified
> on 2026-09-28 in a sandbox AWS Organization: compiled SCPs denied each mapped action to an agent
> identity and allowed it to trusted, break-glass and path-qualified SSO roles, by live calls and
> the IAM policy simulator ([`dev/aws-acceptance/`](https://github.com/moneytool/aegis-devops/blob/main/docs/dev/aws-acceptance/README.md)). A mapping
> added later starts unverified, and the coverage report says so per rule.

**What the second layer adds, and what it doesn't.** The client hook and the compiled policy
come from the same signed policy, so a rule that is wrong is wrong in both. The server-side
layer adds enforcement for calls the hook never sees (an SDK script, a credential used from
somewhere else); it doesn't add a second opinion on whether the rule is right. For that,
review `coverage.md` and keep an independently written guardrail (your own SCPs, RBAC, admission
policies) alongside Aegis.

## How it fits together

1. **The verified snapshot.** Compilers start from `aegis snapshot`: only constraints that are
   signed, intact, authorized and source-verified. A tampered, forged or unauthorized rule never
   reaches a compiled policy ([CLI: Verified snapshot](cli.md#verified-snapshot)).
2. **The identity model.** A cloud API sees which identity made the call, not who typed the
   command, so compiled policies apply to agent identities. `agents.yaml` says which those are —
   by default every identity you have not listed as trusted
   ([Configuration: agents.yaml](configuration.md#agentsyaml-identity-model)).
3. **The compiler** writes policy files, a coverage report and a manifest. Aegis never holds
   cloud write credentials: you review the output and apply it with your own infrastructure as
   code.

## AWS: Service Control Policies

```bash
aegis compile aws --account 123456789012 --out build/aegis-aws
```

A **Service Control Policy** sits above the account, so an agent holding IAM rights inside the
account cannot detach it. Every statement is an explicit `Deny` with the identity model's
condition:

- `deny-by-default`: applies unless `aws:PrincipalArn` is a trusted or break-glass role/user, or
  `aws:SourceIdentity` a trusted source identity;
- `agents-only`: applies when `aws:PrincipalArn` is a listed agent (or its `aws:SourceIdentity`
  is), and never to break-glass.

### Trusted source identities

**Trusted source identities must never carry an agent.** Source identity is set when a session
starts and survives role chaining. If a developer whose session carries a trusted source
identity runs an agent in that session, the agent's calls carry it too and are exempt. The
self-protection statements stop an agent from *setting* an exempt source identity; they cannot
stop it *inheriting* one. List a source identity as trusted only if no agent ever runs under
it, and give agents their own role and source identity (for example `agent:<name>`).
`aegis agents` warns about every trusted source identity (`source-identity-inherited`) until
the entry says `no_agents: true`
([Configuration: agents.yaml](configuration.md#agentsyaml-identity-model)).

`--account` is the **member account** the SCPs attach to. Its environment comes from
`environments.yaml` (`aws.accounts`), so an `env: prod` rule compiles into the prod account's
policy unconditionally and is left out of the others. An account with no environment mapping
gets env-scoped rules unconditionally (over-enforced, as the CLI escalates an unresolved
environment).

### What compiles

| Policy construct | In the SCP | Coverage |
|---|---|---|
| `BLOCK` on (aws, action, resource pattern) | `Deny` on the mapped IAM actions and ARNs | exact, as far as the action map goes |
| `ESCALATE` | `Deny` (a cloud API cannot ask) | over-enforced; `--escalate omit` leaves them client-only |
| `scope.env`, `scope.account` | compiled per account | exact |
| `scope.region` | `aws:RequestedRegion` | exact; over-enforced for global services (IAM, Route 53, Organizations) |
| other scope keys (`profile`, parameters) | dropped | over-enforced: the deny applies more widely |
| resource name patterns | ARN globs; a rule covering every name denies the action on any resource | exact for `*`/`?`; a `[...]` class becomes `?` (over-enforced). "Any resource" includes another account's resources reached cross-account, which the CLI blocks too |
| recurring `time_window`, `rate_limit` | none | not enforced: stays client-side |
| a resource type or action not in the action map | none | not enforced — never widened |
| rules for other providers | none | not applicable |

The action map (`src/aegis_core/compile/actions/aws.yaml`) is keyed by what the CLI parser
produces (`ec2/instance`, `s3/bucket`, `rds/db-instance`, …), so a rule written for the CLI
compiles. For each rule the coverage report also lists **same-effect actions** it does not block
— deleting a bucket's objects through a lifecycle rule, removing a stack's resources by updating
its template — so a rule never looks stronger than it is.

### Self-protection

Every compile includes statements that stop an agent from becoming an exempt identity or
escaping the policy (design §4.3). In `deny-by-default`:

- no `sts:AssumeRole` into a trusted or break-glass role, and no `iam:PassRole` of one;
- no changes to a trusted role's trust or permissions (e.g. to let the agent assume it), and no
  new credentials for a trusted user;
- no setting an exempt source identity on a session (`sts:SetSourceIdentity` with that value);
- no `organizations:LeaveOrganization` (an account outside the organization sheds its SCPs).

`agents-only` instead restricts agents to assuming and passing agent roles, and to creating no
new users or keys (they would be unlisted, hence exempt).

What this layer **does not** enforce is listed in every coverage report: the management account
and service-linked roles (SCPs never apply to them), federated role assumption
(`AssumeRoleWithWebIdentity`/`SAML`, which depends on trust policies — keep CI subjects
workflow-bound), and delegation to services that already run with exempt roles.

### Output

```
build/aegis-aws/
  manifest.json        snapshot digest, identity-model hash, per-file sha256, Sid → rule map
  coverage.json        every constraint: exact / over-enforced / partial / not-enforced / not-applicable
  coverage.md          the same, for review
  report-only/scp-1.json   while agents.yaml says enforcement: report-only
  scp-1.json               once it says enforce
```

Statements merge exactly — same resources pool their actions, same actions pool their
resources, never creating an action/resource pair that was not compiled — so the identity
condition is repeated as little as possible. SCP files are minified and each fits the
5,120-character limit; statements are split across up
to `--max-policies` SCPs (default 4, since one of the five a target can hold is usually
`FullAWSAccess`). If the policy cannot fit, the compile fails rather than drop anything.
Statement ids are `Aegis1`, `Aegis2`, … (AWS allows only alphanumerics); `manifest.json` maps each
to its rule or self-protection entry. `policy_description` identifies the snapshot, so put it in
the SCP's description when you attach it.

### Report first, then enforce

With `enforcement: report-only` (the default) the policies land under `report-only/` and the
manifest says `"deployable": false`. Review `coverage.md`, find every existing identity the
policy would restrict (`aegis audit-identity aws --would-restrict`, see
[CLI: Identity audit](cli.md#identity-audit)) and add the
legitimate ones — backup jobs, cleanup functions, deploy roles — to `trusted`. Then set
`enforcement: enforce` in `agents.yaml`, sign it, and compile again.

### Keep it in sync

```bash
aegis compile aws --account 123456789012 --check build/aegis-aws
```

exits 1 and names every file that is missing, different or stale. Run it in CI next to the
committed output so a policy change without a recompile fails the build.

### Is it denying anything?

`--check` says the committed policies are the ones the policy compiles to; it cannot say the
attached SCPs are doing anything. Zero denials over a month looks the same as a policy that was
detached. `aegis report aws` reads CloudTrail's record of denied calls (read-only) and answers
that:

```bash
aegis report aws --compiled build/aegis-aws --collect --days 30 \
    --policy-id p-abc12345 --test-principal 'arn:aws:iam::*:role/aegis-test-*'
```

- **Attribution.** A call an SCP denied carries "with an explicit deny in a service control
  policy" in its error, *sometimes* followed by the policy's ARN. With the ARN and the
  `--policy-id` you attached the Aegis SCP as, the denial is Aegis's; without the ARN it is
  reported as an SCP denial that may be Aegis's. The message never names the statement, so the
  rules shown are those whose mapped actions cover the denied call: the IAM action the message
  names, or else CloudTrail's operation name translated to it (Lambda's `DeleteFunction20150331`
  is `lambda:DeleteFunction`; S3's `PutBucketEncryption` is `s3:PutEncryptionConfiguration`).
  An explicit SCP deny counts whatever the service calls the error (SNS: `AuthorizationError`). EC2 encodes its reasons;
  those denials are counted as undetermined (`aws sts decode-authorization-message` shows one).
- **Real or a test.** Denials by `--test-principal` identities (the acceptance roles, say) are
  deliberate tests; the rest are real.
- **The warning.** No real denial in a window of at least `--quiet-days` (default 30) exits 1:
  that is not proof the policy works. Check it is attached
  (`aws organizations list-policies-for-target`) and that its tests still deny.
- **Events** come from `--collect` (`aws cloudtrail lookup-events`, the last 1–90 days, with
  your credentials; LookupEvents cannot filter on errors, so every management event in the
  window is read) or from files: that command's output, CloudTrail log files (`Records`,
  gzipped or not) or JSON lines. With `--collect` the window is the one queried, so a quiet
  month with few events still counts as a month. If CloudTrail had more events than were read
  (a `NextToken` left over), the window is cut back to the oldest event read and the report
  says so, rather than claim silence over days it never saw. `--json` for machines.

## Kubernetes: ValidatingAdmissionPolicy

```bash
aegis compile kubernetes --cluster prod-us-east --out build/aegis-k8s
kubectl apply -f build/aegis-k8s/policies.yaml
```

The API server evaluates **ValidatingAdmissionPolicies** itself (CEL, GA since Kubernetes
1.30): there is no webhook to run and no policy key in the cluster. Each compiled rule becomes
one policy and one binding, labelled `app.kubernetes.io/managed-by: aegis`. Every policy carries
a `matchConditions` expression generated from `agents.yaml`, so it applies only to agents, and
fails closed (`failurePolicy: Fail`).

`--cluster` is the cluster or kube context name; its environment comes from `environments.yaml`
(`kubernetes.clusters`, then `contexts`), so an `env: prod` rule compiles only into the prod
cluster's policies.

**The control plane is always exempt in `deny-by-default`**: `system:*` users other than
ServiceAccounts (the controller manager, scheduler, kubelets), `system:nodes` and kube-system
ServiceAccounts. Restricting them would stop the ReplicaSet controller replacing pods or the
namespace controller emptying a namespace you meant to delete. List your own controllers (Argo
CD, Flux) in `trusted`.

### What compiles

| Rule | At admission | Coverage |
|---|---|---|
| `delete` | DELETE; for pods also the eviction a `kubectl drain` sends. The name comes from `request.name`, else the object's — a `delete --all` is admitted per item with an empty `request.name` | exact |
| `create`, `run` | CREATE (an object created with `generateName` has no name yet, so a name-specific rule does not match it) | exact |
| `apply` | CREATE or UPDATE of the object (not its subresources) | over-enforced: admission sees the request, not the verb, so every create and update of the kind by an agent is denied (`create`, `set image`, `label`, `annotate`); `kubectl scale` updates the `scale` subresource and is not matched |
| `update`, `patch`, `edit`, `replace` | UPDATE — all the same request at the API | over-enforced: `label`, `annotate`, `scale`, `set image` and `rollout restart` are UPDATEs too, so they are denied as well; the client matches only the verb named |
| `scale` | the `scale` subresource, or an UPDATE that changes `spec.replicas` | exact |
| `set-image`, `rollout-restart`, `cordon`, `taint`, `label`, `annotate` | an UPDATE whose old and new objects differ in that field (images: containers and init containers) | exact |
| `rollout-undo` | an UPDATE that changes the pod template (metadata included) | over-enforced: admission cannot tell an undo from any other template change, so a restart, `set image` or `apply` of a changed template is denied too |
| `drain` | its cordon; its pod evictions are not tied to the node at admission | partial — add a pod `delete` rule |
| `exec`, `attach`, `port-forward` | CONNECT on the pod subresource | exact |
| `delete` on `*/*` scoped to a namespace | also DELETE of that namespace (the client parser emits the same cascade) | exact |
| `scope.namespace` | `request.namespace`, which must be non-empty | exact; a cluster-scoped kind has no namespace, so it is not enforced there (the client never matches it either) |
| `scope.env` / `cluster` / `context` | compiled per cluster | exact |
| other scope keys | dropped | over-enforced |
| name and namespace globs | RE2 regular expressions | exact |
| a kind that is not built in (a CRD) | that resource name in any API group | over-enforced |
| `ESCALATE` | Deny (admission cannot ask) | over-enforced; `--escalate omit` leaves it client-only |
| reads, `logs`, impersonation, time windows, rate limits | never admitted, or no clock at admission | not enforced |

**Client parity is reported separately.** The coverage status says whether a rule's meaning reaches
the cluster, not whether both layers refuse the same commands. The client hook decides on the
kubectl verb, and a policy decides on the request, which does not name the verb. So a `set-image`
rule is `exact` and the policy also denies `kubectl patch`, `edit`, `replace`, `apply` or `rollout
undo` when they change the image, while the client hook lets those verbs through unless another
rule covers them. Each rule in `coverage.json` has a `client_parity` record, and `coverage.md`
shows the same list:

```json
"status": "exact",
"client_parity": {"status": "wider-than-client",
                  "widened_verbs": ["apply", "edit", "patch", "replace", "rollout-undo"]}
```

`client_parity.status` is `same`, `wider-than-client` or `not-compiled` (no policy for this rule).
The list covers the kubectl verbs the hook knows, not every client of the API: a controller, an SDK
or `curl` sends the same requests under no verb at all. It names verbs, and a verb is listed when any
of its flags makes it send a request the policy covers, since the client hook sees only the verb. A
`delete` rule lists `replace` (`--force`) and `apply` (`--prune`, `--force` on an immutable field),
and on pods also `drain` (evictions, `--disable-eviction`), `run` (`--rm`) and `debug` (`--copy-to
--replace`). A rule on `patch` or `update` lists everything that updates the kind, `rollout pause`
and `rollout resume` included. A `create` rule on services lists `run` (`--expose`), a `delete` rule
on them lists `run` too (`--rm --expose`), and `create` appears on subresource rules such as `exec`
or a pod `delete` because `create --raw` can POST to any URI. A rule's own verb is never listed: the
client decides on it too, for the objects behind a name as well (`kubectl exec deploy/web` against a
`pod/*` `exec` rule, `kubectl delete all --all` against a `deployment/*` `delete` rule, `kubectl run
web --expose` against a `service/*` `run` rule; see
[Kubernetes resource names](constraints.md#kubernetes-resource-names)). Commands the hook cannot
parse are refused on the client, so they are not listed: `set env` and the other `set` subcommands
except `set image`, `diff -f`, `proxy`. Nor are `expose` and `autoscale` on a `create` rule for
services or HorizontalPodAutoscalers: the client reads them as creating that object (the Service
named by `--name` or after the source), so the rule holds there too.

### Guardrails

A policy named `aegis-guardrails` stops the identity escapes admission can see: agents cannot
mint a token for another ServiceAccount (`serviceaccounts/token`), and pods or pod templates
they create or update must run as the agent's own ServiceAccount (or `default` for an agent that
is not a ServiceAccount).

Admission cannot protect the policies themselves — ValidatingAdmissionPolicies, their bindings
and webhook configurations are never admitted (verified on kind) — so agents must have no RBAC
write access to `admissionregistration.k8s.io`, and no `impersonate` verb (impersonation happens
before admission, which then sees the impersonated identity). Both are listed in every coverage
report under "not enforced by this layer".
`aegis audit-identity kubernetes` asks the API server which identities the policies restrict
still hold those permissions ([CLI: Identity audit](cli.md#identity-audit)).

### Report first, then enforce

With `enforcement: report-only` the bindings use `validationActions: [Warn, Audit]`: agents see a
warning and the audit log records it, but nothing is denied. After review, `enforcement:
enforce` compiles `[Deny, Audit]`. `--check DIR` reports drift, as for AWS.

### Is it denying anything? (Kubernetes)

The bindings carry the `Audit` action, so the API server writes every failed validation into
the request's audit event (the annotation
`validation.policy.admission.k8s.io/validation_failure`, naming the policy and the binding's
actions). `aegis report kubernetes` reads the audit log, read-only:

```bash
aegis report kubernetes --compiled build/aegis-kube --audit-log /var/log/kubernetes/audit.log \
    --test-principal 'system:serviceaccount:aegis-test:*'
```

- **Attribution is exact.** Each policy is named after its rule (`manifest.json` lists them),
  so a denial counts for that rule; `aegis-guardrails` is self-protection. A request an agent
  made by impersonation counts as the identity it impersonated.
- **Report-only.** With `[Warn, Audit]` the request goes through and is counted as *warned*.
  A binding that ran with other actions than the compiled ones (edited by hand, or an older
  apply) is reported as `binding-drift`; an `aegis-*` policy that the output does not list
  (left from an older compile) as `stale-policy`.
- **The warning.** No real denial in at least `--quiet-days` (default 30) exits 1, as for AWS.
  When enforcing, only a denial counts: a warning from a drifted binding does not. In
  report-only mode the warnings are what the bindings produce, so they count. An empty log
  also exits 1. The audit policy must log writes at `Metadata` level or above, or no
  denial can show up (`no-writes` says so).
- **Events** are the files `--audit-log-path` writes (JSON lines, rotated `.gz` files fine), an
  `EventList`, or for EKS the output of `aws logs filter-log-events` on the cluster's
  `kube-apiserver-audit` log streams (control-plane audit logging must be on). GKE and AKS
  export audit logs in their own formats; convert them to `audit.k8s.io/v1` events first. A
  server-side dry run (`--dry-run=server`) fails validation exactly like the real request and
  the audit event does not say which it was, so run tests as a `--test-principal` identity.
  Verified on kind (Kubernetes 1.36.1) with the acceptance rules: denials, a test identity, an
  impersonated request and a `[Warn, Audit]` binding (`tests/fixtures/kube-audit/`).

### Verified

`scripts/kube_acceptance.py` applies a compiled policy to a local kind cluster and runs 22 cases
as an agent ServiceAccount, the admin and a break-glass identity, comparing the agent's result
with the client-side verdict for the same kubectl command. On Kubernetes 1.36.1: 66 of 66 as
expected; the two layers agreed on every case that exists on both, and differed only where the
coverage report says so (`rollout-undo`)
([`dev/kube-acceptance/`](https://github.com/moneytool/aegis-devops/blob/main/docs/dev/kube-acceptance/README.md)).
