Skip to content

feat(iam): GetRole reports RoleLastUsed, written by AssumeRole (#816) - #840

Merged
scttfrdmn merged 2 commits into
mainfrom
feat/816-role-last-used
Sep 13, 2026
Merged

scttfrdmn merged 2 commits into
mainfrom
feat/816-role-last-used

Conversation

@scttfrdmn

@scttfrdmn scttfrdmn commented Sep 13, 2026 •

Copy link
Copy Markdown
Owner

Closes #816

GetRole did not report AWS's RoleLastUsed structure. It does now, written where the role is actually used, and #807's placeholder comment at emulator/iam_xml.go:201-208 is replaced by the implementation.

What changed

  • IAMRole.RoleLastUsed *IAMRoleLastUsed (emulator/iam_types.go), omitempty, with IAMRoleLastUsed carrying LastUsedDate and Region.
  • STSPlugin.recordRoleLastUsed (emulator/sts_plugin.go), called from assumeRole after the session credentials are stored.
  • iamRoleLastUsedXML (emulator/iam_xml.go), modeled on iamPermissionsBoundaryXML, called from iamSingleRoleXML only.
  • emulator/iam_role_last_used_test.go, docs/services.md, CHANGELOG.md.

Design rationale

It is a write on a read path, and AssumeRole is the writer. RoleLastUsed advances when the role is used, and an assume is the only use an emulator that models no workload can observe. So an STS operation now stamps an IAM record — nothing else in substrate writes from an operation whose purpose is not to mutate, which the code names rather than buries. It costs one Put and no extra read: assumeRole already reads the role record at sts_plugin.go:251 to evaluate its trust policy. The stamp lands after the session Put, so a caller the trust policy refuses records no use — that refusal returns well before it. AssumeRoleWithWebIdentity and AssumeRoleWithSAML do not exist in this codebase, so there is exactly one write site; adding either later must call the same helper.

A projection over the recorded AssumeRole events was considered and rejected, though #816 guessed it the better answer. The direct write is replay-safe for exactly the reason a projection would be: replayEvent (replay.go:260-296) re-executes each recorded request with the simulated clock set to the event's timestamp and the request context's region taken from the event, so a re-executed AssumeRole re-derives LastUsedDate from that same simulated clock and Region from that same recorded request, writes the identical value, and the StateHashAfter check at replay.go:332 agrees. What a projection adds is a dependency no plugin has: IAMPlugin would have to hold an *EventStore and scan it on every GetRole, making the answer to a read depend on the event log rather than on state. The reasoning is stated in a code comment on recordRoleLastUsed, not only here.

The date is the simulated clock's (STSPlugin.now() off the injected *TimeController) and the region is the request's (RequestContext.Region), rendered in IAM's 2006-01-02T15:04:05Z form.

AWS doc citations (verified against the API reference for this PR)

API_RoleLastUsed — scope:

This data type is returned as a response element in the GetRole and GetAccountAuthorizationDetails operations.

and on LastUsedDate:

This field is null if the role has not been used within the IAM tracking period.

LastUsedDate — Type: Timestamp, Required: No. Region — "The name of the AWS Region in which the role was last used", Type: String, Required: No.

API_ListRoles — exclusion:

IAM resource-listing operations return a subset of the available attributes for the resource. This operation does not return the following attributes, even though they are an attribute of the returned object: PermissionsBoundary / RoleLastUsed / Tags. To view all of the information for a role, see GetRole.

API_GetRole's sample response fixes the shape and child order the renderer emits:

<RoleLastUsed>
  <LastUsedDate>2019-11-20T17:09:20Z</LastUsedDate>
  <Region>us-east-1</Region>
</RoleLastUsed>

GetAccountAuthorizationDetails

Substrate does not implement it at all — it appears only in the vendored authorization reference (emulator/authz_reference_gen.go) as a known action name, and in no plugin dispatch. So it did not gain the member, and there is no shared helper it would have gained it through. GetRole is the whole of the member's reach here; if that operation is added later it renders a role through iamSingleRoleXML and gains RoleLastUsed with it. Noted in the renderer's doc comment and in docs/services.md.

CreateRole and CreateServiceLinkedRole share iamSingleRoleXML and render nothing — a role created a moment ago has not been assumed, which is also what AWS's CreateRole sample shows. iamRoleListXML and iamRoleMembersXML never call the renderer.

What is substrate's choice rather than AWS's

Omitting the whole RoleLastUsed element until the role is assumed. AWS's page settles neither half of the question: API_RoleLastUsed says only that LastUsedDate "is null if the role has not been used within the IAM tracking period" — a statement about a tracked role falling out of the trailing 400 days, not about a role never assumed at all. It says nothing about Region in that case, and nothing about whether the structure itself is present or absent. Both members are Required: No, so omitting the wrapper is admissible, and it is what #816's acceptance criterion asked for: it is the only answer that lets a consumer distinguish "not yet assumed" from "assumed", where a rendered wrapper holding a zero date and an empty region would publish values AWS never does. docs/services.md records this as substrate's choice and quotes AWS's actual wording, so a reader is not left thinking AWS mandated it.

Substrate also keeps whatever the run recorded rather than expiring the value after 400 days, since a run is not 400 days long.

Fail-before / pass-after

The new test file compiles unchanged against main (it references no new exported symbol), so it was run there in a throwaway worktree at 34b39e7:

Test against main on this branch
TestIAMRoleLastUsed_GetRole FAIL — expected the element, actual "" pass
TestIAMRoleLastUsed_ListRolesNeverRenders FAIL — the guard require.NotEmpty on the same run's GetRole is empty, so the ListRoles assertion would have been vacuous pass
TestIAMRoleLastUsed_RegionIsTheRequests FAIL — all three regions, actual "" pass
TestIAMRoleLastUsed_SurvivesReplay FAIL — nothing to replay into pass
TestIAMRoleLastUsed_SeededRecord FAIL in 3 of 4 subtests (assumed, offset date, escaped region); never assumed passes, correctly pass
TestIAMRoleLastUsed_StoreFailureFailsTheAssume FAIL — no write to refuse, AssumeRole answers 200 pass
TestIAMRoleLastUsed_CreateRole passes on main too — it asserts absence, which was already true pass

The one that passes on main is the absence assertion, which is supposed to hold in both directions; every test that asserts the new member fails without the change.

AssumeRole now writes two records, so a test pins what happens when the second fails: a state store that refuses the IAM write fails the assume as a whole rather than answering a session whose use was silently not recorded. Its fault store keys on the IAM record's key alone, so the session write under session: in the STS namespace still succeeds and the arm reached is the intended one. recordRoleLastUsed is 85.7% covered; the remaining arm is the json.Marshal failure, unreachable for a valid IAMRole.

Tests freeze the simulated clock at scale 0 rather than merely starting it at a fixed instant: a TimeController at the default scale of 1.0 advances with wall time, and the member is rendered to the second, so asserting the literal value under scale 1.0 would fail whenever a run straddled a second boundary. The ListRoles assertion is against raw XML, because a decoded map cannot distinguish an absent member from an empty one.

Compatibility

AssumeRole becomes a writer of IAM state, so the state hash recorded after an AssumeRole event differs from the one an earlier version recorded for the same request: replaying a pre-#816 event log with ValidateState enabled reports a state_hash_after difference on every AssumeRole, and a fixture exported from such a log should be re-recorded. A role record written by an earlier version reads back with no last use — the same thing a never-assumed role is — and gains the field the first time it is assumed. Nothing a consumer reads changes for a role that is never assumed.

Verification

All green:

gofmt -l . && go build ./... && go vet ./...        clean
golangci-lint run ./...                             0 issues
make test                                           ok (race)
GOTOOLCHAIN=go1.26.6 make test                      ok (race)
GOTOOLCHAIN=go1.26.6 make coverage                  emulator 83.7%, total 83.1% (baseline: 83.7% / 83.1% — no regression)
make docs-reference docs-reference-check docs-versions authz-reference-check
                                                    "docs/services.md already up to date (67 plugins)", all checks pass
npm --prefix docs run build                         build complete
go vet -C test/e2e ./... && go test -C test/e2e ./...   ok

golangci-lint's misspell locale caught one test fixture name (travelling-role → roaming-role); docs/services.md keeps its British spelling, which is unlinted, and carries #816 rather than a version number so scripts/check-doc-versions.sh stays happy.


Rebased onto c226f69 (#815, PermissionsBoundaryUsageCount). Both collisions were in prose: the ### Which members each entity shape reports table now reports PermissionsBoundaryUsageCount and RoleLastUsed on one row each, and the "One member is deliberately unmodelled" paragraph is deleted rather than rewritten — with #815 and #816 both landed, no member of these shapes is unmodelled, so the paragraph now records that and points at the two sections that say what was decided. The CHANGELOG entry sits in #815's existing ### Added section rather than a second one. emulator/iam_xml.go auto-merged: #815 threads a count into the field renderer, #816 appends a sibling element in the single-role wrapper, and they do not touch the same lines. Full gate re-run after the rebase: unchanged (emulator 83.7%, total 83.1%).

@scttfrdmn scttfrdmn added the area: iam Issues relating to the iam component label Sep 13, 2026
@scttfrdmn scttfrdmn added this to the v0.114.0 milestone Sep 13, 2026
@codecov

codecov Bot commented Sep 13, 2026 •

Copy link
Copy Markdown

Codecov Report

❌ Patch coverage is 95.23810% with 1 line in your changes missing coverage. Please review.

Files with missing lines Patch % Lines
emulator/sts_plugin.go 91.66% 1 Missing ⚠️

📢 Thoughts on this report? Let us know!

@scttfrdmn
scttfrdmn force-pushed the feat/816-role-last-used branch from 6b89fde to ea984c1 Compare September 13, 2026 03:42
AWS's `Role` type carries a `RoleLastUsed` structure holding `LastUsedDate` and
`Region`. Substrate neither stored nor rendered it, so `GetRole` reported nothing
about a role's use and a consumer could not tell an assumed role from an untouched
one. #807 recorded the gap in a comment at iam_xml.go:201-208 with its cost; this
is that cost paid, and that comment is now the implementation's.

The interesting half is that it is a write on a read path. `RoleLastUsed` advances
when the role is *used*, and an assume is the only use an emulator that models no
workload can observe — so `STSPlugin.assumeRole` stamps the IAM record, making an
STS operation a writer of IAM state. Nothing else in substrate writes from an
operation whose purpose is not to mutate, which is worth naming rather than
burying. It costs one Put and no extra read: assumeRole already reads the role
record at sts_plugin.go:251 to evaluate its trust policy, so the new
recordRoleLastUsed takes the value it already holds. The stamp lands after the
session credentials are stored, so a caller the trust policy refuses records no
use — that refusal returns at sts_plugin.go:270 long before here.
`AssumeRoleWithWebIdentity` and `AssumeRoleWithSAML` do not exist in this
codebase, so this is the single write site rather than one of three.

A projection over the recorded `AssumeRole` events was considered and rejected,
even though #816 guessed it the better answer. The direct write is replay-safe for
exactly the reason a projection would be: replayEvent (replay.go:260-296)
re-executes each recorded request with the simulated clock set to the event's
timestamp and the request context's region taken from the event, so a re-executed
AssumeRole re-derives LastUsedDate from that same simulated clock and Region from
that same recorded request, writes the identical value, and the StateHashAfter
check at replay.go:332 agrees. What a projection adds is a dependency no plugin
has — IAMPlugin would need to hold an *EventStore and scan it on every GetRole,
which makes the answer to a read depend on the event log rather than on state. The
reasoning is in the code, not only here.

iamRoleLastUsedXML is modeled on iamPermissionsBoundaryXML and called from
iamSingleRoleXML only, because AWS scopes the member by naming its operations:
"This data type is returned as a response element in the GetRole and
GetAccountAuthorizationDetails operations." Substrate answers no
GetAccountAuthorizationDetails at all, so GetRole is the whole of the member's
reach; an implementation of it later renders a role through the same wrapper and
gains the member with it. ListRoles excludes it by name in the same sentence that
already excludes PermissionsBoundary and Tags, so iamRoleListXML and
iamRoleMembersXML do not call it. CreateRole and CreateServiceLinkedRole share the
single-role wrapper and render nothing, which is right — a role created a moment
ago has not been assumed.

Omitting the whole element for a never-assumed role is substrate's choice and is
recorded as such rather than claimed as AWS's. API_RoleLastUsed says only that
LastUsedDate "is null if the role has not been used within the IAM tracking
period", which is a statement about a tracked role falling out of the trailing 400
days; it says nothing about a role never assumed, nothing about Region in that
case, and nothing about whether the structure itself is present. Both members are
`Required: No`, so the omission is admissible, and it is what #816 asked for: it is
the only answer that lets a consumer distinguish "not yet assumed" from "assumed",
where a wrapper holding a zero date and an empty region would publish values AWS
never does.

The region is the request's (RequestContext.Region), per AWS's wording — "the name
of the AWS Region in which the role was last used" — and not the emulator's
configured one. The test proves it by assuming one role from three regions in turn.

Tests freeze the simulated clock at scale 0 rather than merely starting it at a
fixed instant: a TimeController at the default scale advances with wall time, and
the member is rendered to the second, so asserting the literal value under scale
1.0 would fail whenever the test straddled a second boundary. The ListRoles
assertion is against raw XML, because a decoded map cannot distinguish an absent
member from an empty one.

Compatibility: a state hash recorded after an AssumeRole event changes, so a
replay of a pre-#816 event log with ValidateState on reports a state_hash_after
difference on every AssumeRole. A role record written by an earlier version reads
back with no last use, which is the same thing a never-assumed role is.
The RoleLastUsed write's failure arm was untested, which codecov's patch
target caught: of the nine statements the change added to sts_plugin.go,
the store-failure return and the call site's propagation of it were never
executed, so the patch measured ~67% against a ~83% project target.

Worth a test on its own terms rather than to move a number. AssumeRole now
writes two records, and the question a reader will ask is what happens when
the second one fails — whether the caller gets a session whose use was
silently not recorded. It does not: the assume fails as a whole. The fault
store keys on the IAM record's key alone, so the session write under
`session:` in the STS namespace still succeeds and the test reaches the new
write and nothing before it; the fault is armed only after CreateRole, so
the role exists to be assumed. The assertion names the wrapped message
("store role last used") so that the arm reached is the intended one and not
some earlier failure that happens to answer 500 too.

The test fails against main for the same reason the rest of the file does:
without the write there is nothing to refuse, and AssumeRole answers 200.

recordRoleLastUsed is now 85.7% covered. The remaining arm is the
json.Marshal failure, which is unreachable for a valid IAMRole -- every
field marshals, so there is no input that reaches it.
@scttfrdmn
scttfrdmn force-pushed the feat/816-role-last-used branch from ea984c1 to ebe2fcd Compare September 13, 2026 03:46
@scttfrdmn
scttfrdmn merged commit 04b9140 into main Sep 13, 2026
17 checks passed
@scttfrdmn
scttfrdmn deleted the feat/816-role-last-used branch September 13, 2026 03:56
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

area: iam Issues relating to the iam component

Projects

None yet

Development

Successfully merging this pull request may close these issues.

IAM: model RoleLastUsed on GetRole

1 participant