Skip to content

Replay bypasses authorization, quota, consistency and fault injection #833

Closed

Description

@scttfrdmn

Problem

ReplayEngine does not replay a request through the request pipeline. It calls the plugin registry directly:

// emulator/replay.go:296
resp, err := r.registry.RouteRequest(reqCtx, event.Request)

handleAWSRequest (emulator/server.go:630) documents a nine-step pipeline in its own doc comment (:615-629). Replay enters at step 5. Steps skipped:

  • Step 1.5/1.6 — credential resolution and SigV4 verification
  • Step 2 — auth.CheckAccess() (:798-807)
  • Step 3 — quota.CheckQuota() (:811)
  • Step 4 — consistency.CheckRead() (:826)
  • Step 4.5 — fault injection (:842)

So a replay of a recorded run can produce a different outcome from the recording in the direction that matters most: a request the live run refused with AccessDenied, throttled, or failed with an injected fault is re-executed on replay and succeeds. The event store exists so that a failing run replays exactly; four of the five ways a request can be refused before it reaches a plugin are not replayed at all.

Evidence this is unintended

QuotaController.CheckQuota carries a guard written specifically for replay (emulator/quota.go:87, isReplaying(reqCtx) at :167-177), and ReplayEngine dutifully sets the flag it reads (emulator/replay.go:278, "replaying": true, in the reqCtx built at :270-280). But because quota is never consulted during replay, the guard is dead code on this path — it can only fire for a caller who drives a Server with a hand-built replaying context. Someone wrote both halves of a contract whose two ends never meet.

Interaction with #817

#817 wants replay to deep-compare response bodies. It cannot be satisfied honestly while this stands: a recorded 403 body and a replayed 200 body would be reported as a body mismatch when the actual defect is that the authorization step never ran. Whatever normalisation policy #817 lands will otherwise be tuned to paper over this.

Complication: recorded bodies

Events carry no request or response body unless EventStoreConfig.IncludeBodies is set, which defaults to false (emulator/config.go:605, emulator/eventstore.go:385-388), and replayEvent skips an event with a nil request (emulator/replay.go:261-264). So today a default-configured recording replays almost nothing. Any fix has to be clear about which of these two facts is limiting a given replay.

Acceptance criteria

  • A replay of a recorded run in which a request was refused by authorization reports the same refusal, not a success.
  • Same for a request refused by quota — and if the answer is that quota is deliberately exempt on replay (which isReplaying suggests was the intent), then the exemption is reached through the pipeline and isReplaying stops being dead code, rather than the whole step being skipped.
  • Same for a request that a fault rule failed.
  • Consistency (CheckRead) is either applied on replay or documented as deliberately exempt with the reason.
  • The decision for each of the five skipped steps is stated in emulator/replay.go and in docs/, so "replay is not a full pipeline" is a documented property rather than a discovery.
  • A test drives a recording whose request is refused pre-plugin and asserts the replay agrees.
  • docs/ states plainly what a replay does and does not re-execute, and what IncludeBodies changes about that.

Provenance

Nothing to verify against AWS — this is entirely substrate's own replay contract.

Found while auditing the quota path for #818.

Activity

  1. added this to the v0.115.0 milestone on Sep 13, 2026
  2. added
    type: bug
    on Sep 13, 2026
  3. scttfrdmn commented on Sep 14, 2026

    @scttfrdmn
    OwnerAuthor

    Research for v0.115.0 went through this end to end. Four corrections to the description, and a split that lets the cheap half ship now.

    The dead isReplaying contract is two-thirds larger than stated

    The issue names one site. There are three, all on controllers the replay path never reaches:

    • emulator/quota.go:87
    • emulator/consistency.go:85
    • emulator/consistency.go:127

    replayEvent sets Metadata["replaying"] = true (emulator/replay.go:278) and then calls r.registry.RouteRequest directly (:296). Quota, consistency and every other pre-plugin step live in Server.handleAWSRequest, which replay does not use — so all three guards are unreachable from a replay, and the flag they read is written only for them.

    The refusal points skipped are nine, not four

    replayEvent enters the pipeline at step 5. The steps it skips, from handleAWSRequest's own numbered list (server.go:615-629) plus two the list does not number:

    1. RPC v2 CBOR target conflict (server.go:664)
    2. Region validation (:711-727) — not in the issue
    3. Credential resolution / principal (:736-779)
    4. SigV4 verification (:782-787)
    5. Presigned-URL expiry (:792-795) — not in the issue
    6. auth.CheckAccess (:799)
    7. quota.CheckQuota (:811)
    8. consistency.CheckRead (:827)
    9. Fault injection (:843)

    handleAWSRequest cannot be reused as-is, and there are now four dispatch paths

    It reads the live *http.Request at seven points and writes through an http.ResponseWriter. Meanwhile the tree has four dispatchers with four different subsets of the pipeline:

    Path Pipeline steps
    handleAWSRequest all nine
    StackDeployer.dispatch (cfn_deployer.go:4477-4547) auth + cost + record
    replayEvent (replay.go:260) none
    Server.stateAtSequence (debug_ui.go:285-307) none, plus a fresh registry and a zero-value clock

    So the execution half is "introduce a shared request-pipeline type", which does not exist yet. That is the size of this issue, and it is why it is not landing in v0.115.0.

    Two hard ceilings on replaying an authorization decision

    • The SigV4 canonical request cannot be reconstructed from a recorded event. The raw query string is never recorded — parser.go:107 keeps r.URL.Path only — and the body is overwritten with a JSON re-encoding of the parsed form for iam/sts/sqs/sns (server.go:691-697).
    • A key minted mid-stream does not survive replay. Substrate mints identifiers from crypto/rand (78 non-test generate* functions across 31 files that import it), so a recorded CreateAccessKey or AssumeRole mints a different AKIA… on replay. The recorded Authorization header then names a key absent from replayed state, resolvePrincipal returns nil, and CheckAccess fails open the instant reqCtx.Principal == nil (authz.go:151-153). So authorization fidelity under replay is blocked on deterministic identifier minting, which is now filed separately.

    What ships in v0.115.0: the reporting half

    Separable from all of the above, much cheaper, and squarely this release's theme (a value nothing wrote):

    1. A skipped event is counted as a success. replayEvent increments SkippedEvents and returns nil for a nil request (replay.go:261-264); the driver then increments SuccessEvents because the error was nil (:233-235). A skipped event increments both.
    2. A recorded refusal that replays as a success reports zero differences. The error comparison sits wholly inside the if err != nil arm (:297-318), so nothing consults event.Error when the replay succeeds; and the status comparison is guarded on event.Response != nil (:320), which is always nil for a pre-plugin refusal — every refusal records with resp = nil (server.go:801, :813, :829, :849). A recorded 403 replaying as a 200 is reported as no difference at all, and counted as a success.
    3. ValidateState is inert on every recorded stream. IncludeStateHashes is declared (config.go:175-176, eventstore.go:81-83), plumbed (config.go:197) and defaulted (:606, :697) — and never read. StateHashBefore/StateHashAfter (eventstore.go:162-166) are never written outside a hand-built event in replay_test.go:291-292. Both comparisons (replay.go:282, :332) are guarded on a field that is always "".

    And the reason none of this was caught: IncludeBodies defaults to false (config.go:605) and StartTestServer uses DefaultConfig() with no option to change it (testing.go:184-192), so no event on a default-configured stream carries a request at all. The flagship e2e test proves the consequence — it asserts FailedEvents == 0 and passes having re-executed nothing:

    $ go test . -run TestJourney_RecordAndReplay -v     # test/e2e
    journey_replay_test.go:67: replay total=2 success=2 failed=0 --- PASS
    

    This issue stays open for the execution half. The reporting fixes name it without a closing keyword.

  4. scttfrdmn commented on Sep 14, 2026

    @scttfrdmn
    OwnerAuthor

    Moved to v0.116.0. v0.115.0 shipped this issue's reporting half (#857); the execution half is larger than the issue describes and is now blocked on #856.

    What shipped

    Three defects, all of the "a value read from a field nothing wrote" shape this release was about:

    1. A skipped event was counted as a success. replayEvent incremented SkippedEvents and returned a nil error; the driver read the nil error as a success, so a skipped event incremented both. Since IncludeBodies defaults to false, no event on a default-configured stream carried a request — so every event was skipped and a replay reported total=N success=N having executed none of them. That is why TestJourney_RecordAndReplay passed while re-executing nothing. The three counters now partition the stream, stated as an invariant, and SuccessEvents is documented as "re-executed without returning an error", not "matched the recording".
    2. A recorded refusal that replayed as a success reported zero differences. The error comparison ran only when the replay errored, and the status comparison was guarded on event.Response != nil, which is always nil for a pre-plugin refusal. A recorded 403 replaying 200 was reported as no difference at all. It is now a critical difference, matching the reverse case already there.
    3. ValidateState was inert on every stream. IncludeStateHashes was declared, plumbed and defaulted and never read; StateHashBefore/StateHashAfter were never written outside a hand-built test event. The server and the CloudFormation deployer now record both, through one stateSnapshotHash so the recorded and replayed hashes cannot be two answers.
    4. StartTestServer gained WithRecordedBodies() and WithRecordedStateHashes(), without which any test written against this issue's criteria measures the wrong thing.

    Two of this issue's own statements were narrower than the tree

    • isReplaying is dead at three sites, not one — quota, and consistency twice. A replay calls RouteRequest directly and never enters the pipeline that would set it, so the dead contract is three times the size described here.
    • replayEvent skips nine pre-plugin refusal points, not four. The issue omits region validation and presigned-URL expiry.

    What the execution half actually needs

    • ReplayEngine holds no controllers at all and NewReplayEngine's six positional parameters offer no way to pass one, so replayEvent enters the pipeline at step 5 (RouteRequest).
    • handleAWSRequest cannot be reused as-is: it reads the live *http.Request at seven points and writes through an http.ResponseWriter.
    • The tree now has four dispatch paths with four different subsets of the pipeline — handleAWSRequest (all nine refusal points), StackDeployer.dispatch (auth + cost + record), replayEvent (none), and Server.stateAtSequence (none, plus a fresh registry and a zero-value clock). A shared pipeline type would have to be introduced; it does not exist.

    Two hard ceilings, both independent of effort:

    ValidateState becoming live already surfaces the #856 problem: enabling it on a stream containing a create reports a mismatch, because the minted identifier differs and lands in the hashed state. That is the honest answer, and it is the concrete evidence for #856 rather than an argument against having made the comparison run.

    Blocked on #856. Everything else here is a refactor with a clear shape.

  5. modified the milestones: v0.115.0, v0.116.0 on Sep 14, 2026
  6. scttfrdmn commented on Sep 15, 2026

    @scttfrdmn
    OwnerAuthor

    Deferred to v0.117.0. One quarter of this issue was discharged by v0.116.0 and it changes the scope materially, so recording what remains. Verified at bd1dca7.

    Authorization is no longer bypassed

    #855 replaced the replay command's empty PluginRegistry and nil StateManager with a real emulator, and the wiring includes an auth controller: newReplayEngineWiring (cmd/substrate/main.go:236, :255) builds NewAuthController(state, logger, WithAuthTimeController(tc)) and passes it to RegisterDefaultPlugins via WithPluginAuth. A replayed request now reaches each plugin's own p.authorize(…) call the same way a live one does.

    Before that, the registry was empty and every event routed to ServiceNotAvailable, so "replay bypasses authorization" was true only in the weakest sense: replay bypassed everything, including dispatch.

    Three of the four remain. newServerCmd builds a quota controller (main.go:336), a consistency controller (:338) and a fault controller (newFaultController, :95), plus the credential registry (:385). None of the four is in newReplayEngineWiring. So this issue is now about quota, consistency and fault injection — and, separately, whether signature verification should apply to a replay at all.

    One design question the new wiring surfaces, which this issue should settle

    newReplayEngineWiring deliberately hands the plugins a recording-disabled event store rather than the one being replayed, because the CloudFormation deployer records its in-process resource calls (cfn_deployer.go:4543, :4554) and a replay must not append to the log it reads. The one cost is recorded in the code: Cost Explorer is the only plugin that reads the log, so a ce operation replays against no history.

    The fault controller raises the same class of question more sharply: a fault injected during a replay is not a fault that occurred during the recording. Whether a replay should re-inject from config, replay the recorded outcomes, or refuse both is a decision to make explicitly here rather than inherit from whichever controller happens to be wired.

    What else changed the analysis

    On the minting dependency

    #856 was corrected and deferred. Its cheap form — derive an identifier from its inputs — unblocks nothing here, because this issue needs CreateAccessKey (iam_plugin.go:1475) and AssumeRole (sts_plugin.go:285, :506) reproducible, and neither has a unique-name input to derive from. Both are in the collision class, where identical inputs must legitimately yield distinct identifiers. See the correction on #856 for the seven verified collision sites, the corrected inventory, and why Event.Sequence and TimeController.Now() are both unavailable as derivation inputs.

  7. modified the milestones: v0.116.0, v0.117.0 on Sep 15, 2026
  8. scttfrdmn commented on Sep 16, 2026

    @scttfrdmn
    OwnerAuthor

    Moved to the v0.118.0 milestone. The release did not start this issue's execution half, but it removed
    the reason the issue could not be stated precisely: until v0.117.0 the replay path was not running an
    emulator at all, so "replay bypasses authorization, quota, consistency and fault injection" was
    indistinguishable from "replay bypasses everything, including plugins".

    Discharged this release:

    Still blocking: #856, for the two operations this issue names specifically. CreateAccessKey and
    AssumeRole are both in the collision class — identical inputs must legitimately yield distinct
    identifiers — so neither can be made reproducible by deriving from its request, which is why #856's
    cheap scoping does not unblock this issue and its full form does. That correction is on #856.

    The remaining scope is therefore what it always was and is now purely about replayEvent: which of the
    authorization, quota, consistency and fault-injection paths a replayed request goes through, and which
    it must skip by design.

  9. modified the milestones: v0.117.0, v0.118.0 on Sep 16, 2026
  10. scttfrdmn commented on Sep 17, 2026

    @scttfrdmn
    OwnerAuthor

    Implementing this now, at d93b7c5. The per-step decision, the one correction it forces to my
    own earlier comment, and where each decision is written down.

    The blocker I recorded twice is not one: authorization does not need #856

    Both earlier comments say authorization fidelity is blocked on deterministic minting, on this
    reasoning: a mid-stream CreateAccessKey or AssumeRole mints a different key on replay, so the
    recorded Authorization header names a key absent from replayed state, resolvePrincipal returns
    nil, and CheckAccess fails open at authz.go:151-153.

    That is true of re-resolving the recorded access key, and it is the wrong input. The event
    already records the answer: Event.Principal is the caller ARN (eventstore.go:165-166,
    written at :438-439), and every consumer of a principal in the authorization path takes the
    ARN, not the key — AuthController.CheckAccess resolves the entity with
    resolveIAMEntity(ctx, state, reqCtx.Principal.ARN) (authz.go:163), and each plugin's own door
    does the same (IAMPlugin.authorizeWith, iam_plugin.go:1787).

    And an ARN survives a replay where a key does not, because it is name-derived on both sides of
    the fork this issue worried about:

    • an IAM user ARN is arn:aws:iam::<acct>:user/<path><name> — the name and path are the
      CreateUser request's own inputs;
    • an assumed-role ARN is arn:aws:sts::<acct>:assumed-role/<RoleName>/<RoleSessionName> — both
      segments are the AssumeRole request's own inputs.

    The access key ID is the one part of that record that is minted, and nothing in the authorization
    path reads it. So the fix is to restore the principal from the recorded ARN and never look at the
    key: replayPrincipal sets ARN from Event.Principal, Type through the existing
    cfnPrincipalType (whose doc comment already records that nothing evaluates Type —
    authorization resolves the ARN), Tags through the existing iamPrincipalTags(ctx, state, arn),
    which reads the replayed entity's record, and UserName from the ARN only when that record
    exists.

    That last guard is #745's rule, not caution: a registry hit with no IAM entity behind it
    synthesizes …:user/<access-key-id> (server.go:810-813), and deriving a user name from that
    ARN would publish a credential ID as aws:username in a policy comparison.

    The residue that does stay with #856 is one condition key: aws:userid. An IAM user's AIDA…
    and an assumed role's <role-id>:<session-name> are minted, are not recoverable from the ARN, and
    the replay's own value would be a different identifier rather than the recorded one. So a
    replayed principal publishes no aws:userid at all, which is the shape Principal.UserID's doc
    comment already defines for a caller substrate has no ID for, and the answer #745 chose over a
    substituted-but-wrong value. A policy conditioning on aws:userid therefore replays as though the
    key were absent; that is stated in the code and in the docs, and it is the only part of
    authorization that #856 still owes.

    An event whose Principal is empty — an unsigned request, which is most of them — restores a nil
    principal and is unenforced on replay exactly as it was live. That is a reproduction, not a bypass.

    Worth noting what this alone fixes: today a replayed request carries no principal at all, so
    every plugin's own p.authorize(…) door is unenforced on replay too, not just the pipeline's step
    2. Restoring the principal makes both doors live.

    The five steps the issue names, and the four it does not

    Step On replay Why
    2 auth.CheckAccess re-decided principal restored from the recorded ARN, above
    3 quota.CheckQuota consulted, exempt AC 2's own alternative; the guard stops being dead code
    4 consistency.CheckRead consulted, exempt below
    4.5 fault injection re-decided, controller rewound below
    1.5 credential resolution replaced superseded by principal restoration; the recorded key resolves to nothing
    1.6 SigV4 skipped the canonical request cannot be reconstructed — the raw query string is never recorded and the body is re-encoded for iam/sts/sqs/sns (server.go:728-733). A replay also re-executes a request whose signature was already verified once
    1.65 presigned expiry skipped same class: it is a statement about the wall-clock moment the URL was signed, which the recording already settled
    1.1 rpc-v2-cbor/target conflict skipped a property of the HTTP request, which no event carries
    1.4 region allow-list skipped a property of the replay's configuration rather than of the recorded run; refusing here would report a divergence caused by the config file the replay was started with

    Consistency is exempt, and the reason is stronger than "it was already guarded": RecordWrite
    is guarded on the same flag (consistency.go:127), so no propagation window ever opens during a
    replay. A CheckRead that enforced would be refusing against a window that does not exist. It is
    consulted anyway so that the decision lives at the controller — where the two other guards are —
    instead of in a step the replay skips.

    Fault injection is re-decided, with the controller rewound to the state it was armed in at the
    start of the replay, beside ResetPlugins in resetState. Without the rewind a rule that fired
    during the recording has spent its Times bound and its per-rule PRNG has advanced, so an
    in-process record-then-replay would replay the unfaulted path — which is precisely the bug this
    issue is about, arriving through the fix. This is the same class as #886/#902/#903: mutable state a
    controller keeps on itself that must return to its start-of-run value, and UpdateConfig already
    re-seeds ruleRNGs for the same reason (fault.go:288-298). A latency rule's delay is not
    slept on replay; the recorded Duration is what the live run took, and no replay may consume wall
    clock.

    This creates one honest dependency worth stating rather than discovering: a rule's draw sequence
    depends on the requests it sees, so a stream that skipped events for want of include_bodies
    shifts every later draw. Reproducing a probabilistic fault requires a fully-bodied stream.

    Shape

    A shared prePluginGates runs steps 2, 3, 4 and 4.5 in one place and returns which step refused,
    so the live path and the replay path cannot answer differently — the two ends of the contract this
    issue found unconnected. Server.handleAWSRequest keeps its own per-step recording and metrics by
    switching on the returned step; the ordering, the nil-controller skips and the latency-then-error
    sequence are preserved exactly.

    ReplayEngine gains the controllers through one variadic option (WithReplayPipeline), following
    NewEventStore's option pattern rather than growing a seventh positional parameter, and
    newReplayEngineWiring builds all four from the same config sections substrate server reads.
    A replay reproduces a recorded refusal only when it is configured as the recording was; a
    configuration difference is reported as a divergence rather than hidden.

    Not in scope, and stated so: unifying all four dispatch paths. StackDeployer.dispatch and
    Server.stateAtSequence keep their own subsets; this issue is about replayEvent, and a shared
    gate for the four controllers is what its acceptance criteria need.

    A refusal on replay is compared against event.Error and counted in FailedEvents, which is what
    a recorded plugin-level error already does — FailedEvents means "returned an error", not
    "diverged". A refusal that disagrees with the recording is an EventDifference; the reverse case
    (recording refused, replay succeeded) has been critical since #857.

    The decisions land in emulator/replay.go (per step, at the call site) and in
    docs/testing-guide.md under a new What a replay re-executes section, next to what
    include_bodies changes about it.

  11. scttfrdmn commented on Sep 17, 2026

    @scttfrdmn
    OwnerAuthor

    Update from #818, which lands S3 per-prefix request-rate accounting: the "Interaction with #817" section of this issue is now present tense rather than prospective.

    #817 shipped in this milestone, so replay does deep-compare recorded and replayed response bodies. Combined with step 3 being skipped, that means a recorded quota refusal now produces a reported body difference on every replay: the recording carries S3's <Error><Code>SlowDown</Code> document (or ThrottlingException for any other service) and the replay carries the success body of the request being re-executed. The divergence report is correct about the bytes and misleading about the cause — the defect is that the gate never ran, not that the plugin answered differently.

    Two consequences for this issue's scope, neither of which changes the acceptance criteria:

    Nothing here alters the analysis above; it removes the conditional from it.

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

    type: bug

    Type

    No type

    Projects

    No projects

      Milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions