Skip to content

Principal-aware test mode: enforce IAM authorization in composition tests #411

Closed

Description

@scttfrdmn

Summary

Substrate already has a real IAM policy evaluator (emulator/iam_eval.go: Deny → Allow → ImplicitDeny) and an enforcing AuthController.CheckAccess that returns AccessDeniedException (403). But CheckAccess short-circuits when reqCtx.Principal == nil, and the common test-harness path (SDK client pointed at the server with no principal wired) never sets one — so in practice every authorization check is skipped in composition tests.

Net effect: a caller that is missing a required permission passes cleanly against Substrate and only fails on real AWS. This is the "request/response error-code fidelity" part of the charter (scope.md: make every API observation accurate including error codes) — not workload execution — so it's in scope.

Why this matters (concrete, from a real consumer)

In spore-host/spawn's pooled-execution work (spawn#70), a worker instance was launched with an IAM instance profile that granted no SQS permissions. On real AWS its GetQueueUrl returned NonExistentQueue (SQS masks access-denied as not-found) and the worker died — the pool never drained. The Substrate-backed composition tests were fully green because no principal was set, so the missing permission was invisible. It took a paid real-AWS smoke to find it. A whole class of "forgot a permission / policy too narrow" bugs is exactly what an enforced-IAM test mode would catch in CI.

Proposed capability

A way for a test to execute API calls as a specific IAM principal/role, so AuthController evaluates the principal's actual policies against the (already-built) action + resource ARN:

  • A test helper / request option to set RequestContext.Principal to a role or user the test created via the IAM plugin (e.g. an instance profile with a scoped inline policy), so subsequent calls on that client are authorized against it.
  • Opt-in: the nil-Principal "always pass" default stays for the many tests that don't care about authz, so this is non-breaking. A test that wants enforcement sets the principal explicitly.
  • Bonus: honor an EC2 instance's attached IamInstanceProfile as the principal for calls that a test attributes to that instance, so "does this instance's role actually allow what its bootstrap does?" becomes testable end-to-end.

Acceptance

  • A test can create a role with a scoped policy, make an SQS/S3/etc. call as that role, and get AccessDeniedException when the policy doesn't allow it — and success when it does.
  • Existing tests (nil principal) are unaffected.

Scope note

This is higher-fidelity emulation of an existing observable (the authz decision + error code), consistent with scope.md — it does not execute any workload. Substrate already has the evaluator; this exposes it to tests.

Reported from spore-host/spawn#70 pooled-execution validation.

Activity

  1. added
    type: feature
    area: iam
    area: server
    priority: high
    on Aug 1, 2026
  2. added this to the v0.82.0 milestone on Aug 1, 2026
  3. scttfrdmn commented on Aug 1, 2026

    @scttfrdmn
    OwnerAuthor

    Triaged to v0.82.0, separately from its three siblings (#406, #412, #413 → v0.81.0).

    Those three are self-contained fidelity fixes in one plugin each. This one is architectural: it needs RequestContext.Principal populated along the SDK-client path, a supported way for a test to say "run as this role", and a decision about attributing calls to an EC2 instance's attached profile. Bundling it would hold up three small fixes behind a much larger change.

    Confirming the premise holds on main: CheckAccess does short-circuit on a nil principal, and the test-server path never sets one — so the evaluator exists and is simply unreachable from composition tests. Your framing matches the scope boundary in CLAUDE.md: the authorization decision and its error code are observable through an API call, so raising fidelity there is in scope, and no workload gets executed.

    Two things worth settling before implementation, both from the acceptance criteria:

    1. SQS masking. You note real SQS returns NonExistentQueue rather than AccessDenied for an unauthorized GetQueueUrl — which is what made the original bug hard to spot. If substrate returns AccessDeniedException there, a consumer's error branch still won't match what AWS sends. The per-service masking probably belongs in this issue rather than a follow-up, or the fix reproduces the original problem under a different code.
    2. Opt-in default. Keeping nil-principal-passes preserves existing tests, but it also means enforcement is off unless a test remembers to ask. Worth deciding whether the test-server and pytest helpers should make the enforcing mode the obvious one to reach for.

    No work started; this is triage only.

  4. modified the milestones: v0.84.0, v0.85.0, v0.86.0 on Aug 1, 2026
  5. scttfrdmn commented on Aug 2, 2026

    @scttfrdmn
    OwnerAuthor

    Moved from the v0.85.0 milestone to v0.86.0. v0.85.0 is cut and closed.

    Still deferred as feature-scale: plumbing a caller principal through
    RequestContext and enforcing IAM authorization against it touches every plugin's
    request path, which is not a change to make alongside unrelated defect fixes.

    One correction to note, since it narrows this issue's remaining scope. The
    issue's framing implies substrate refuses nothing on authorization grounds.
    As of v0.85.0 that is no longer strictly true: #458 landed enforcement of S3
    Block Public Access, so PutBucketAcl, PutObjectAcl and PutBucketPolicy now
    return 403 AccessDenied for a public ACL or a public bucket policy on a blocked
    bucket.

    That is not principal-aware authorization, and it does not overlap with what
    this issue asks for — BPA is evaluated from the request content and the bucket's
    own configuration, with no notion of who is calling. It is worth flagging because
    it means substrate now has one 403-producing path, and whatever this issue builds
    should sit beside it rather than duplicate or subsume it. The relevant
    distinction, from that work: substrate has no unauthenticated or cross-account
    request path at all, which is exactly why IgnorePublicAcls and
    RestrictPublicBuckets stayed recorded-only — they govern who a request comes
    from, which is precisely the gap this issue exists to close.

    No work has started here.

  6. modified the milestones: v0.86.0, v0.87.0, v0.88.0 on Aug 2, 2026
  7. 8 remaining items

  8. modified the milestones: v0.90.0, v0.91.0 on Aug 4, 2026
  9. scttfrdmn commented on Aug 4, 2026

    @scttfrdmn
    OwnerAuthor

    Moved to v0.91.0. This is the fifth deferral, and saying so plainly is more
    useful than another quiet milestone bump: v0.90.0 is a bug-fix release closing six
    silent-wrong-observable defects, and this is a feature with real design decisions in
    it. It keeps losing to defects that came from live consumers, which is the right
    priority ordering but a bad pattern to leave unremarked.

    Nothing in v0.89.0 or v0.90.0 changes this issue's analysis, but v0.89.0 sharpened
    its central open question. StackDeployer.dispatch still builds a RequestContext
    with no Principal, and #520 added a rollback path that dispatches resource
    deletes through that same identity-less context. So enforcement now has to answer
    one more question than when this was filed: what principal does a rollback's deletes
    run as?

    The plausible answers all have consequences worth choosing deliberately rather than
    discovering:

    • The creating caller's principal — matches CloudFormation's own model (a stack
      operates with the caller's permissions unless a service role is set), but means a
      rollback can fail on authorization, which needs a status (ROLLBACK_FAILED already
      exists for it) and makes a partial rollback reachable.
    • An implicit service principal — rollbacks always succeed, but then substrate is
      enforcing IAM on creates and exempting the deletes that undo them, which is exactly
      the kind of asymmetry that lets a missing permission stay invisible — the thing this
      issue exists to stop.
    • A stack's RoleARN — the faithful answer, and the one that requires modelling
      service roles first.

    Recording it here so the design pass in v0.91.0 starts from it rather than rediscovering
    it mid-implementation.

  10. scttfrdmn commented on Aug 4, 2026

    @scttfrdmn
    OwnerAuthor

    Moved to v0.92.0 — the sixth deferral. Saying so plainly again, but this
    comment is only worth more than the previous five if it stops restating the blocker
    and answers it. So: the answer first, then the two findings that change this issue's
    shape.

    The blocking question, answered

    The question holding this up has been what principal a CloudFormation rollback's
    deletes run as
    . A rollback's deletes run as the principal that created the
    stack.
    Reasons, in order of weight:

    1. It is CloudFormation's own model absent a service role — a stack operates with
      the calling principal's permissions, and nothing about a rollback re-derives an
      identity.
    2. ROLLBACK_FAILED already exists in substrate, so the awkward case (the principal
      could create a resource but cannot delete it) has a faithful terminal state to
      land in rather than needing one invented.
    3. The alternative — an exempt service principal whose deletes always succeed —
      reintroduces exactly the blind spot this issue exists to remove. Enforcing on
      creates while exempting the deletes that undo them is the asymmetry, not a way
      around it.

    Modelling a stack RoleARN (an explicit service role the deploy assumes, which the
    rollback then also uses) is the faithful long-term answer and is strictly larger than
    this issue. Filed as #562 rather than folded in here, and it depends on this one.

    Two findings that change the shape of the work

    Measured on main (31cff92) while scoping v0.91.0. This issue has been described
    more than once as "wire a principal into a test". It is not — it is three coupled
    decisions.

    1. The CLI server can never enforce, whatever a test does.
    RequestContext.Principal is set in exactly one place, emulator/server.go:536-546,
    and only when opts.Credentials != nil:

    if s.opts.Credentials != nil {
        accessKey := extractAccessKeyFromAuth(r.Header.Get("Authorization"))
        if entry, ok := s.opts.Credentials.Lookup(accessKey); ok {
            reqCtx.AccountID = entry.AccountID
            reqCtx.Principal = &Principal{ARN: buildCallerARN(entry.AccountID, accessKey), Type: "IAMUser"}
        }
    }

    cmd/substrate/main.go:173 wires Auth: authCtrl but never Credentials, and
    no config section exists for it. So substrate server cannot enforce authorization
    at all, independent of anything a test harness does. Delivering this issue therefore
    means adding that config section — a new public surface, which is a large part of why
    it is not a one-liner.

    2. A principal with no policies is denied, not allowed.
    loadPoliciesForPrincipal returns an empty slice for a principal with no attached or
    inline policies, and Evaluate (emulator/iam_eval.go:54) returns implicit deny
    for an empty policy set. So enabling enforcement server-wide without first giving
    every existing test's principal a policy would deny everything at once. The opt-in
    has to be per-principal, not per-server — a decision about the public API, not a
    wiring detail. This issue's "existing tests (nil principal) are unaffected" criterion
    survives, but only under a per-principal opt-in.

    3. The IaC path bypasses enforcement entirely — unchanged from the previous
    comment, restated because it interacts with the answer above.
    StackDeployer.dispatch (emulator/cfn_deployer.go:3925) builds a RequestContext
    with no Principal, and RouteRequest never calls CheckAccess; enforcement lives
    only in the HTTP path. So resources created through CloudFormation bypass
    authorization, and #520's rollback dispatches its deletes through that same path.
    cfnIdentity (:807) already carries account and region, and its doc comment
    already says propagating Principal is "a separate decision". That is the decision
    answered at the top of this comment.

    Why it defers rather than ships now

    v0.91.0 is a three-plugin wire-format rewrite (#529, plus the routing fixes #561 and
    the API Gateway v2 prerequisite tracked on #529). Landing a new public config surface
    and a change to when authorization is enforced beside it would put two large
    behaviour changes in one release, and the second can break a consumer's tests in a
    way that is hard to attribute when it arrives alongside the first.

    v0.92.0 now starts from a decision rather than a question.

  11. modified the milestones: v0.91.0, v0.92.0 on Aug 4, 2026
  12. scttfrdmn commented on Aug 5, 2026

    @scttfrdmn
    OwnerAuthor

    Four measurements taken while planning v0.92.0, each of which changes this issue's shape. All were probed against main (a533ced), not inferred from reading.

    1. An assumed-role principal already fails OPEN. This issue says "the nil-Principal 'always pass' default stays for the many tests that don't care about authz, so this is non-breaking". That understates it: loadPoliciesForPrincipal (emulator/authz.go:101) returns an error for any entity type outside user/role, and CheckAccess (:38-42) fails open on that error. Probe result: a request as arn:aws:sts::123456789012:assumed-role/worker/sess1 is allowed with no policies attached at all, while the same call as user/… or role/… is correctly denied. That is the exact shape STS itself mints (emulator/sts_plugin.go:189), so the principals a consumer would most want to test are the ones enforcement silently skips.

    IAMPlugin.authorize (emulator/iam_plugin.go:1348) has the same switch and denies in that case. Two policy loaders, two opposite answers for one ARN.

    2. The server's principal ARN names the access key, not the IAM user. buildCallerARN (emulator/credentials.go:88) produces arn:aws:iam::<acct>:user/AKIATEST12345678901. Probe: an IAM user alice with an inline sqs:* Allow is ALLOWED as user/alice and DENIED as user/AKIATEST…. So even with ServerOptions.Credentials wired, enforcement can never resolve a real principal's policies — the "wire a principal into a test" framing cannot work as written.

    3. The IaC path is not authorized at all. CheckAccess has exactly one non-test call site (emulator/server.go:564). PluginRegistry.RouteRequest never calls it, and StackDeployer.dispatch (emulator/cfn_deployer.go:3920-3931) builds a RequestContext with no Principal. Every resource a CloudFormation stack creates, updates, rolls back or deletes bypasses authorization entirely.

    4. Wiring Credentials into the CLI server would be breaking. cmd/substrate/main.go:173 wires Auth but never Credentials, so the long-running server cannot enforce whatever a test does. But the obvious fix — wire the registry — also switches on VerifySigV4 (emulator/server.go:548), and a key absent from the registry is InvalidClientTokenId (403). AKIAIOSFODNN7EXAMPLE, the credential every e2e check and the README use, is not registered. It would 403 the documented quickstart.

    Consequences for the design

    Principal resolution is therefore being decoupled from the credential registry: the server resolves the caller from state (iam:accesskey:<id> → IAMAccessKey.UserName, and sts:session:<id> → the assumed-role ARN — a key AssumeRole writes today and nothing has ever read), independent of whether Credentials is wired. That costs one state.Get per request carrying an Authorization header and breaks nothing.

    Opt-in decision: existence in state is the opt-in — no config flag. Enforcement runs when the caller resolves to an IAM user or role that exists; an unknown key, the built-in test key and AKIAIOSFODNN7EXAMPLE continue to pass unenforced. This matches this issue's own acceptance wording ("a test can create a role with a scoped policy, make a call as that role…"), keeps every existing test green (only 3 test files set a Principal and only 1 wires Credentials), and avoids a global switch that would deny a policy-less-but-existing principal in tests that never asked for authz. A state read that genuinely fails (I/O) still fails open, because that is a broken backend rather than an unknown caller.

    Taken in v0.92.0 alongside #562.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    area: iamarea: serverpriority: hightype: feature

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions