Repository navigation
feat(identitybroker): record who acted, for whom, and what was decided - #2985
Conversation
The broker now records every event audit.md assigns to it: each session open (converted token, token AS-1 already converted, tokenless) and each refused open, every close path once (including a hard expiry a lookup finds), each agent registration and refused registration as a lineage event, each accepted or refused delegation report as a lineage event, and each ID-JAG and call decision. Every record has its own AuditID, the audit profile's Subjects keys with provenance marks, and AuditID references to the session open, the acting instance's registration, and the delegation it runs under. No record carries a credential value. Records go through one Recorder sink that can refuse a record. A successful open, registration, or delegation report takes effect only after its record is accepted, and otherwise fails UNAVAILABLE and changes nothing; refusals and closes take effect anyway, and a refused record is reported on a separate delivery-failure channel. The ID-JAG and decision keep their existing write order. mecak8s reports a team member's parent, and its delegation, as the root's main agent standing in for the RunTeam API request. Closes #2541 Co-Authored-By: Claude Opus 5.5 <[email protected]>
Co-Authored-By: Claude Opus 5.5 <[email protected]>
Name a delegation's run owner RunOwner and the session owner Owner, as in the other records, and the stand-in mark DelegatingStandIn. A refusal recorded after an accepted success that could not take effect names it in Supersedes. The delegation record carries the delegating agent's incarnation. WithDeliveryFailures is marked as a shortcut removed by #2848. Tests now cover a refused open whose record is refused, an open cancelled while waiting for its host session, registrations and delegations whose session closes while they are recorded, a Token held in any record, and the app's record summary line. Co-Authored-By: Claude Opus 5.5 <[email protected]>
ChrisJBurns
left a comment
There was a problem hiding this comment.
Review against #2541 and the agent identity design (including #2984's write-order table), and against the tickets that build on this. Each point is a question with the code to check, so it can be verified or rejected point by point; I may be wrong on any of them. Line references are at c816bb7.
1. Can a new session be used before its open record is accepted?
pairLocked adds a new session to t.byID and t.open (internal/identitybroker/sessions.go:280-281) during b.open, before b.record sends the open record (sessions.go:161). The open lock only makes other opens of the same host session wait.
- While the record is in flight, can
FindSession,RegisterAgent,ReportDelegation, orCloseSessionreach the session? The comment atsessions.go:309-313("A registration made while the open was recorded may [refer to it]") suggests yes. - If the open record is then refused, accepted records point at an
AuditIDthe sink never accepted. #2984 says "a session … without its record would leave those references unresolved, so it is not kept." Should the session stay pending (refused by lookups and registrations) until its record is accepted? - On the mismatched-answer path in
sessionopen.go, is the close record sent before the refused-open record it points to?
2. Who sends close records, and with what deadline?
Close records are queued under the table lock and sent in tableMutex.Unlock (sessions.go:69-80) by whichever goroutine releases the lock, using context.Background() (broker.go:130).
- Can that goroutine be an
AuthorizeCall, or a registration holding its own lock? If so, a slow sink, or a blocking one in #2848's lossless mode, stalls unrelated calls with no bound. - Records leave in unlock order, not event order, and
RecordHeaderhas no sequence field. Will #2566/#2848/#2808 need ordering assigned when the record is queued? - Would a bounded queue drained by its own goroutine fit better?
3. A refused open record after conversion is mapped as retryable
After a token conversion, a refused open record returns errNotRecorded (UNAVAILABLE), which internal/adapter/server/identity_broker.go:624 maps to ErrIdentityBrokerUnavailable. The close-after-conversion case just above it returns errBrokerSessionClosedAfterToken ("fail as for a refused token").
- Should a refused record after conversion take the same path? Otherwise the client retries with a spent token and gets
token_used. errNotRecordedhas no reason. Should it carry one (for examplenot_recorded), so #2559'sErrorInfocan express it?
4. Who retries a refused registration or delegation report?
#2984 says mecak8s retries a registration and reports a delegation again. Here, a failed registration stops the helper (identity_broker_helpers.go:25), and I couldn't find a retry for a failed ReportDelegation (the holder in internal/agentcredential/holder.go). Is a retry planned, or should #2984 say the helper fails? See the matching question on #2984.
5. Rollbacks after a refused record leave no follow-up
When the sink refuses an open, registration, or delegation success record, the code returns errNotRecorded and records nothing after it (sessions.go:161-169, and the matching paths in agents.go and runs.go). A sink that timed out after storing the record leaves a success for something that was rolled back. The decision path does write a follow-up error record (authorize.go, via refuse), and the close-during-record path uses Supersedes.
- Should every rollback after a refused record write a refusal through
recordAnywaywithSupersedesset to the attemptedAuditID? Supersedesisn't in the design yet; see #2984.
6. Re-reported delegations after a reopen
A close drops the per-session run and delegation ledger (sessions.go:305). When the holder reports delegations again into the reopened session, each gets a new mecatl_delegation success with a fresh AuditID and no link to the earlier one. Registrations carry PreviousRecord; DelegationRecord doesn't.
- Should delegation records keep the delegation ID →
AuditIDmapping outside the per-session ledger and carry aPreviousRecord, so #2844's lineage walk doesn't see one delegation recorded several times with no link?
7. Grant provenance for schedule grants
heldGrant.user and openRecord (sessionopen.go) feed ID-JAG and decision subjects as record:<open AuditID>, and OpenKind has converted, already_converted, and tokenless. #2569's scheduled runs open from a schedule grant, and #2843 requires that no scheduled-run record present the saved owner as a fresh sign-in.
- Would a typed provenance reference (open record or schedule-setup record) now avoid reshaping these types in #2569?
8. One record per event across replicas
The new per-incarnation (registering) and per-session (reporting) locks are what keep an identical repeat from producing a second success record. They are in-process.
- With replicas (#2805, #2558), can two replicas each record the same registration or delegation under different
AuditIDs? If so, should #2805's scope gain "one accepted record per registration and delegation across replicas"?
9. Smaller points
DelegatingRunRecorded: the flag is set from the first check inruns.go, butAuthorizeCallcan add the root run without thereportinglock before the second check. Can the record claim the report recorded a run it didn't?- Malformed requests: when validation fails,
OpenSession,RegisterAgent, andReportDelegationreturn before a record exists. Should a refused-as-invalid request still be recorded, as #2541 and step (3)/(4) "Evidence" say for refusals? workload_issis always setunavailable(records.go, the subjects builder), even for a verified workload. audit.md says to qualify workload subjects by issuer or trust domain. Intended, or a shortcut?- Registration lineage: only
agent_instance_refis markedreported:mecak8s;Parent,ParentHostSessionID,ParentStandIn,Definition, andHostSessionIDcarry no mark. audit.md "Lineage" says these are marked as reported by mecak8s. - Stand-in detection:
helperParentHosttreats any helper with no parent session as a stand-in (identity_broker_helpers.go:146). Should it also require the team-member session kind, so a future parentless helper kind isn't marked? - Diagnostics:
loggedRecorder(internal/app/identitybroker.go:750-767) writes each record's type,AuditID, outcome, code, and reason to diagnostics, and the harness test reads that line. AGENTS.md keeps audit and diagnostics separate, and #2566 removes diagnostic lines that only repeat a broker event. Could the test read the sink directly instead? - The
MemoryRecordershortcut names #2563 as a remover. Isn't storage and delivery of audit records #2566's? - Renewal re-registers, so each renewal now waits on the sink and writes a
mecatl_instance_registered, and a child'sParentRecordpoints at the latest renewal. Is that the intended lineage, or should #2562 record renewal as credential issuance? - API compatibility: the statement says clients see no new behaviour. Registrations of one incarnation and reports to one session now wait for each other, a cancelled wait returns
UNAVAILABLE, and an open can fail withsession_closedif a close lands during its record. Not breaking, I think, but worth listing. IDJAGRecord.Useris anOwnerwhile other records useUserandOwnerseparately; align now, or leave it for #2727?
- An open whose record is not accepted changes nothing and still remembers the converted source jti. It fails with record_not_accepted: as for token_used when it converted the request's token, which mecak8s answers with bearer_rejected, and UNAVAILABLE otherwise. - A refused open never leaves the broker session it created, whatever happens to its record. The close names the refusal's record. - Every event undone after its success record was sent records a refusal that supersedes that record: an open, a registration, a delegation report, and a withheld call decision. - Registrations and delegation reports whose record is not accepted fail with record_not_accepted; mecak8s does not retry them. - The user's token client is recorded as user_client_id and user_client_iss. - The stand-in marks on registrations and delegation reports move to #2557. Co-Authored-By: Claude Opus 5.5 <[email protected]>
- A new broker session enters the table only once its open record is accepted, so nothing reaches it while the record is in flight and no accepted record refers to an unaccepted open. A mismatched answer's close is queued after the refused-open record it names. - Close records go through a bounded queue drained by its own goroutine, each send with a deadline, so no call waits on the sink for them. A record past the bound is dropped and reported. - A delegation reported again into a reopened session refers to its earlier record (PreviousRecord). - Requests that fail validation are recorded as refusals with only the calling workload. - A verified workload is qualified by its authenticator's issuer, and registration and delegation lineage is marked as reported by mecak8s. - The harness reads the broker's record sink instead of the diagnostics line, and the MemoryRecorder shortcut names #2566 only. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks, these checked out. ee547bf follows #2984's revised write order (cf42713), and a89b2eb addresses the rest; the PR body is updated.
|
ChrisJBurns
left a comment
There was a problem hiding this comment.
Thanks for the fixes. Points 1, 3, 5, 6, and most of the smaller points check out at a89b2eb, and the focused race tests pass. A few things remain, two of them new with the fixes. As before, each is a question with lines to check, and I may be wrong on any of them. Line references are at a89b2eb.
1. Refusal records wait on the sink with no deadline, under per-key locks
recordAnyway sends with context.WithoutCancel(ctx) and no timeout (internal/identitybroker/records.go:563-565). refuseOpen is called while the host session's open lock is held (taken at sessions.go:139, released by the deferred unlock at :143). The registration and report refusals run under the registering and reporting locks (agents.go, runs.go).
- The usual way into
record_not_acceptedis the success record's context ending against a slow sink. The superseding refusal is then sent with no deadline at all. Can that hang the call, and every later open, registration, or report for the same key behind it, once #2566's HTTP sink is in place? - #2984 says a refusal is never held back. Should refusals go through the same queue as closes, or at least get a deadline like
queuedRecordTimeoutand be sent after unlocking? - Waited records use the caller's context with no broker-side deadline either. Is that intended?
2. Can a delete or sign-out close an open that is still being recorded?
A new session enters t.byID and t.open only once its record is accepted (sessions.go:172-182). FindSession reads only t.open (sessions.go:384). mecak8s closes by find-then-close, on delete or session end (internal/adapter/server/identity_broker.go:553-556) and in closeUnsavedPairing (:282).
- If a delete races an open, does the find miss the in-flight session, so the open then completes and holds a fresh refresh token for a host session that no longer exists, until hard expiry?
- The comment at
sessions.go:402-404("an open converting a token for the session meanwhile discards the new one") seems to no longer hold for new sessions. - Would a pending entry that closes can mark (and lookups can't use), or having the close path take the host session's open lock, cover it? #2568's sign-out everywhere would need the same.
3. Is the close queue bounded, and can drops be detected?
- Past 1024 waiting records, overflow goes into
q.full, which has no limit (recordqueue.go:55-57), and is only reported between sends, each of which can take up to 10 s. A sink that ignores its context blocksdrain, sofullgrows and its drops are never reported. Shouldpushreport and discard instead of storing? - A drop is reported only as a diagnostics warning (
internal/app/identitybroker.go:657-660). Nothing in the audit trail marks the gap for #2808/#2846/#2848's gap detection, and the PR body says sequence numbers are assigned where the sink receives records, which is after the drop. Should a record be numbered when it is emitted, before the queue? - There's no
Broker.Closethat drains the queue;wait()is only called from tests (export_test.go:105). Are close records still queued at shutdown lost without a report? End-to-end tests (#2817, #2457) also have no way to wait for them outside the package.
4. Stand-in marks went to a closed ticket
The marks moved to #2557, which closed on 2026-11-23 (via #2930) and doesn't mention them. An API-created team member now registers with the root as its parent and no mark (internal/adapter/server/identity_broker_helpers.go:46-49), so the trail states that as fact for #2844 and #2817. Should a new ticket track this, with a code shortcut naming it at that line?
5. Deferrals named only in the PR description
The description defers several things, but the target tickets haven't changed. Should each get a line, so the work isn't lost?
- #2569: grant provenance for schedule grants;
- #2805: one accepted record per registration and delegation across replicas (its scope still says only run records and delegation reports);
- #2562: renewal recorded as credential issuance rather than registration (#2848 also lists credential issuance events);
- #2727:
IDJAGRecordnaming; - #2566: whether mecak8s retries after
record_not_accepted; - #2563: the new in-memory reference state (
openRecord,user.openRecord,registrationRecord,runLedger.previous,heldClose); - #2568: the refresh-token discard site at
sessions.go:155, which its list of four sites doesn't include.
6. Smaller points
runLedger.previousis keyed by root host session and never pruned (runs.go:50-100). It also setsPreviousRecordon a changed repeat refused in the same session, while the field doc (records.go:423-427) says "in an earlier broker session". Prune on root close, and set it only across sessions?internal/agentcredential/holder.go:329-334: when the second report after a move fails, is the moved entry already stored, so the next lookup doesn't seeagainand never reports it? If so, that helper's gateway calls fail closed for the rest of its run. Store the moved entry only after the report succeeds, or say this case fails closed?record_not_acceptedmaps toUNAVAILABLEfromReason.Code()(errors.go:85-86) but the converted open returnsUNAUTHENTICATED, soerrors.Is(err, ReasonError(ReasonRecordNotAccepted, ""))misses that variant. Worth a note aterrors.go:68, and for #2559'sErrorInfomapping to match on reason?- The
errors.go:68-72comment says to retry the reason, while #2984's failure tables say registrations and reports aren't retried. See question 1 on #2984. - With mecatui's single refresh-and-retry (
cmd/mecatui/client/client.go:319-335), a sink outage during an open spends two tokens and reaches the user as Unauthenticated. Is that the intended experience, or should #2457 check it?
- Every send to the sink has a 10-second deadline, so a slow sink fails a waited record with record_not_accepted instead of holding the call. - Refusals go through the queue closes use, so no caller and no open, registration, or report lock waits on the sink for them. A refused open's close follows its refusal. - The queue reports and drops a record past its bound, and Broker.Close, called at shutdown, sends what is queued until its deadline and reports what it could not send. - A lookup of a host session whose open is creating a new broker session waits for that open, so a delete's find-then-close closes the session the open made. - PreviousRecord links only across broker sessions and is forgotten when mecak8s closes the root's session itself. - The holder puts a helper's old entry back when the report after its move fails, so the next lookup moves it and reports again. - record_not_accepted documents its outcome per event, and that the converted open's code differs from the reason's usual one. Co-Authored-By: Claude Opus 5.5 <[email protected]>
A team member created over the API registers with the root's main agent as its parent, and its delegation from the team run, with no mark that the main agent only stands in for the API request. Name #2986, which tracks the marks, in a code shortcut there. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks. 90f700c addresses these and aligns the code with #2984 at ce51086; 4ba4514 adds the #2986 shortcut. The PR body is updated.
|
ChrisJBurns
left a comment
There was a problem hiding this comment.
Thanks. Round 2 checks out at 4ba4514: refusals are queued, sends have a deadline, the queue is bounded, Broker.Close drains it, and the ticket notes and #2986 are in place. Focused race tests pass with -count=3. Nothing here blocks; question 1 is the one I'd look at before merge. Same format: questions with lines to check, and I may be wrong on any. Line references are at 4ba4514.
1. Can the delete path still miss an open in progress?
closeIdentityBrokerSession bounds its find with engineCloseTimeout, 10 s (internal/adapter/server/service.go:1158, used at identity_broker.go:550). The open that FindSession waits for (internal/identitybroker/sessions.go:400-416) can take up to the AS-1 request timeout plus recordTimeout.
- If the find gives up first, the close is skipped and only logged, so the open completes and keeps its refresh token until hard expiry. Is that the round-2 race again, just narrower?
FindSessionchecks for an in-flight new open once. Can another open create a new session between its wait ending and itst.mu.Lock()?- Would marking the host session deleted in the broker (so an open in progress closes its own session when it finishes) close it fully? Or a find timeout longer than the open's worst case, with a recheck?
- The API compatibility note says a concurrent request "already waited". Does that hold for delete, which never opened?
2. Denied calls still wait on the sink, under the AS-2 read lock
recordDecision sends synchronously with context.WithoutCancel (recorder.go:186-193). In AuthorizeCall, refuse at authorize.go:88 runs after acquireAS2 and before the deferred release().
- #2984 says a denied call's refusal is never waited for. Here a call can take up to 10 s past its own deadline, and
unbindand new calls queue behind a slow sink. Queue decision refusals too, or keep this with a shortcut naming #2727? - The PR body's "closes and refusals no longer wait for their records" isn't true for calls yet.
3. CloseSession forgets history even when the close changed nothing
sessions.go:452-456 calls forgetPreviousLocked(s.HostSessionID) unconditionally, including when s was already closed or isn't the host session's current broker session. closePreOpenedBrokerSession closes by broker session ID precisely so it doesn't touch the winner of a create race (identity_broker.go:260-263), but this erases the winner's history, so its next re-report has no PreviousRecord. Forget only when the close took effect and s was the host's current session?
Related: the history is still never pruned when a host session is deleted while it has no open broker session (after hard expiry, a lost grant, or a refused open), since the find returns not found and no CloseSession runs.
4. Smaller points
- A refused open's close always names the refusal's
AuditID(sessions.go:268-273). If the queue drops that refusal or the sink refuses it, the close points at a record that doesn't exist. Document that in theSessionRecordfield, or cover it under the #2848 shortcut? recordQueue.close(recordqueue.go:115-129): when the deadline passes with one record in flight and none queued, it reports "0 records not sent", and that record may still be sent afterClosereturns.- Shutdown order (
internal/app/build.go:3161-3168):Broker.Closeruns beforeib.release()stops AS-1, so requests arriving in between have their records dropped (reported, not silent). Release the servers first? - Holder (
internal/agentcredential/holder.go:222-224,:326,:339): between storing the moved entry and restoring the old one, a non-renewing lookup returns the new session's credential. It's transient and fails closed; worth a comment? - #2563's note lists close records waiting to be sent, but not queued refusals or
heldClose. identity_broker_unavailablegains a new cause (an audit sink refusing a record). Should the wire API statement say so, anduser-docs/reference/http-sse-api.md:33anduser-docs/features/security-and-execution/caller-identity.mdstop describing it only as "unreachable"? See question 7 on #2984.errors.go:79-81applies "move, renewal" retries to delegation re-reports, which #2984 limits to "after a reopen". See question 1 on #2984.
- Close a host session in the broker: CloseSessionRequest gains RootHostSessionID, which closes the open broker session and the new one an open in progress is creating, without waiting. That open then fails and stores nothing. mecak8s closes deleted sessions and ended scheduled runs this way, so a delete no longer misses a slow open. FindSession checks again for a new open after its wait. - Queue decision refusals like other refusals, so a denied call never waits on the sink or holds AS-2's binding while its record is sent. - Forget a root's delegation history only when a close took effect on its current broker session, or when its host session is closed. - Give record_not_accepted refusals the outcome error, and refusals a close caused denied. - Answer a converted open's repeated record_not_accepted, from the same caller for the same host session within a minute, with 503 identity_broker_unavailable. - Count and report the record in flight when the queue's close gives up; release AS-1 before draining at shutdown; read MemoryRecorder's slices under its lock. - Document the new cause of identity_broker_unavailable. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks. e3c9a5f addresses these and follows #2984 at 6ec9bda; the PR body is updated.
From #2984's round 3: a repeated |
ChrisJBurns
left a comment
There was a problem hiding this comment.
Thanks. Round 3 checks out at e3c9a5f: a delete closes by host session without waiting, FindSession re-checks, decision refusals are queued, history is forgotten only when a close takes effect, and shutdown order is fixed. Race tests pass with -count=3 and go vet is clean (task lint hit unrelated typecheck errors in cmd/mecatui/ui locally, so CI is the check there). Questions 1 and 2 are the ones I'd want answered before approval; the rest is minor. Same format: questions with lines to check, and I may be wrong on any. Line references are at e3c9a5f.
1. The 503 repeat rule for creates, and after the 503
openRecordRefusals keys on owner and host session (internal/adapter/server/identity_broker.go:658-697).
- A create without an explicit ID gets a new host session ID on every attempt (
preOpenIdentityBrokerSession,:243-252), and fork and clear open a new host session too. Does the repeat ever match for them, or does every create during a sink outage get 401 and spend a fresh token? - After the 503, the token is spent. If the client retries with it, the broker answers
token_used, andnote"forgets the previous refusal" for any other outcome, so the next refreshed attempt is a first failure again. Should atoken_usedfollowing a counted refusal keep the window? The PR body's "a conforming client retries without spending another token" seems not to hold yet. - The state is per replica; a retry reaching another replica gets 401. Worth a line in the docs?
See questions 1–3 on #2984 for the design side.
2. Can a deleted host session get a new broker session?
closeHostLocked (internal/identitybroker/sessions.go:478-486) closes t.open[host] and t.newOpens[host] but leaves no mark. An open queued on t.opening behind the one being closed then gets the lock, pairLocked creates a new session, converts, and stores a refresh token. An open from another replica that loaded the session before the delete can do the same. Either way the deleted host session gets a broker session nothing closes before hard expiry. Would a bounded, time-limited "host closed" marker that pairLocked checks cover it, or should a shortcut name the remaining window? The commit message's "a delete no longer misses a slow open" and the CloseSessionRequest doc may overstate it as is.
3. Close records from closeHostLocked for a session still opening
closeHostLocked queues a CloseRequested record naming the open's AuditID (sessions.go:479-481) before that open's record is sent.
- Close during the AS-1 exchange: the close is queued before the refusal it names, and
refuseOpenthen skips its own close because the session is already closed. Doesn't that contradictrefuseOpen's "queued after the refusal"? - Close between
open()returning andb.record: does the open still send its success record for a closed session, possibly after the close? - Open record refused by the sink: does the close then name a record the sink never accepted? The comment at
sessions.go:189-194says no accepted record refers to an open the sink did not accept; the close record queued bycloseHostLockedseems to be the exception.
Would holding the close in s.heldClose for a session in newOpens, and checking s.closed before sending the success record, fix all three?
4. Smaller points
- Denied-call refusals now share the 1,024-entry queue with closes (
recorder.go:192-197,recordqueue.go:57-66). An agent looping on denied calls while the sink is slow can push close records out; the drops are reported, but closes matter for revocation. Reserve room for closes, or note it under the #2848/#2563 shortcut? - A record in flight at close is reported as
errRecordInFlightAtClose(recordqueue.go:138-141), and the drainer'sb.recordreports it again if the sink then refuses it (records.go:533-536); if the sink accepts it, the first report was wrong. Worth a note in theDeliveryFailurecontract? - A tokenless open on another replica closed by a delete now fails with
session_closed, which maps toerrBrokerSessionClosedAfterTokenand thenErrInternal(identity_broker.go:183-190,:623-627), so the caller sees 500. Map it to not found or unavailable instead? user-docs/features/security-and-execution/caller-identity.md:220-230: "If the broker is unreachable, or its audit sink, the destination of its audit records, does not accept…" is hard to parse; split it, and add the limits from question 1?
- Key mecak8s's 503 rule for a repeated unrecorded converted open on the verified owner alone, so creates, forks, and clears, which open a new host session each time, reach it. Only a successful open ends it; a token_used from presenting the token the 503 spent keeps it. The state is per replica and best effort. - Mark a host session closed by host session, per workload, for five minutes. An open of a marked host session fails with session_closed before it converts or stores anything, so an open queued behind the one a delete ended, or one whose request loaded the session before the delete, gives it no new broker session. A replica that did not serve the close, a restart, or a later open is a shortcut under #2805 and #2563. - Hold the close of a new session an open is still creating until that open's refusal is queued, and have it name the refusal. Check for a close before sending an open's success record, so a closed session gets only a refusal. A close no longer precedes, or names, a record the sink was not given first. - Keep the last 256 of the record queue's 1,024 slots for closes, so refusals from denied calls cannot push them out. - State in the DeliveryFailure contract that a record in flight at Close may still be accepted, or be reported again. - Answer a tokenless open refused with session_closed, as after a delete, with 404 session_not_found instead of 500. - Rewrite the caller-identity doc's 503 paragraph and add the rule's limits: the spent token after a 503, per replica, best effort. The HTTP reference's 503 row says the token is spent in that case too. Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
Thanks. 7bab17a answers these and follows #2984 at 00ae95c; the PR body is updated.
Known and left as is: an open that presents a token for a deleted host session within the five minutes gets 401 |
ChrisJBurns
left a comment
There was a problem hiding this comment.
Approving. Round 4 checks out at 7bab17a, and the focused race tests pass with -count=3. The points below are minor and fine as follow-ups; I may be wrong on any of them. Line references are at 7bab17a.
refuseOpensends an open's refusal through the queue, which drops non-close records once 768 slots are full, while the held close that follows can still take a reserved slot and names that refusal (recordqueue.go:74,sessions.go:343,:357-360). Under a flood of denied calls, the sink can accept a close naming a record it never got, so the comment atsessions.go:352-355and the PR body's "no close names a record the sink was not given first" don't quite hold. Letting open refusals use the reserved slots, or reserving room for the refusal and its close together, would fix it.- An ID-JAG record that isn't accepted returns
errNotRecordedwithout a superseding refusal (authorize.go, around:175), while #2984'saudit.md:142asks for one when an event is undone. - The PR body says "schedules present no token, so never reach it". It's scheduled runs that present no token; schedule setup and renewal, which #2984 counts toward the rule, aren't in this PR (#2569).
user-docs/reference/http-sse-api.md:33says to refresh "when the cause is the audit sink refusing your repeated session opens", but the 503 carries the same code either way. "After a 503 on a request that presented a token, refresh the token before retrying" is something a client can act on.- The host-closed mark ignores incarnation. Only the scheduler creates with an explicit ID today, so it can't block a re-create in practice; worth keying on incarnation if that changes.
ChrisJBurns
left a comment
There was a problem hiding this comment.
See the inline comments.
| At: now, SessionID: s.ID, Workload: workload, Owner: owner, OwnerVerified: s.verifiedOwner != nil, | ||
| RecordHeader: RecordHeader{Type: TypeToolDecision, At: now}, | ||
| SessionID: s.ID, Workload: workload, Owner: owner, OwnerVerified: s.verifiedOwner != nil, | ||
| UserRecord: userRecord, User: user, |
There was a problem hiding this comment.
Important · security — Decision provenance remains attached to the old grant after a retry
decisionRecord snapshots UserRecord and User before the call selects its grant, and neither field is updated when authorizeAtGateway retries with a replacement grant. The supported replacement path—already exercised by “a newer grant is retried” in authorize_integration_test.go:533—therefore produces an ID-JAG record referencing the new open but a successful decision referencing the old open; if the replacement token has a different client identity, the decision also records the wrong verified client. This makes the newly added provenance inconsistent with the credentials actually us
Recommendation: Update the decision’s user provenance from the specific heldGrant selected for each exchange attempt, including retries, so the final decision and its ID-JAG reference the same grant; retain the initial session snapshot only for refusals before a grant is selected. --- ## No Issues
There was a problem hiding this comment.
Fixed in 14d7da2. A decision's user and user record now come from the grant each exchange uses, a retry's newer grant included, so the final decision and its ID-JAG name the same open. The session snapshot is used only for refusals before a grant is selected. The "a newer grant is retried" test now checks that both records name the reopen; it fails against the old code.
- Queue a refused open's refusal and its close as one group, whole or not at all, and let a group with a close use the queue's reserve. A flood of denied-call refusals can no longer drop the refusal while its close, which names it, is sent. - Follow an ID-JAG record the sink did not accept with an ID-JAG refusal that supersedes it (record_not_accepted, outcome error), as audit.md asks whenever the broker undoes an event. - Take a decision's user and user record from the grant each exchange attempt uses, a retry's newer grant included, so the decision and its ID-JAG name the same open. The session's user stays only for refusals before a grant is selected. - Key the host-closed mark on the closed incarnation as well: CloseSessionRequest gains RootHostIncarnation, required with RootHostSessionID, and mecak8s passes the deleted session's. A session deleted and created again under the same ID opens, while an open queued behind the delete is still refused. - Answer an open of a saved session that the broker refuses with session_closed, with or without a token, by what the store holds: 404 session_not_found when the session is gone or was created again, and the retryable 503 identity_broker_unavailable when it remains, as after a scheduled run ends. It is no longer 401 or 500. - Tell clients to refresh the token after any 503 on a request that presented one, and name the closed-while-opening cause, in the HTTP reference and the caller-identity page. Closes #2999 Co-Authored-By: Claude Opus 5.5 <[email protected]>
An open whose broker session closes after it converted the token is refused with session_closed, which mecak8s answers 503 while it still has the session and 404 once it is gone, as #2985 does. A create, fork, or clear, whose session is not saved yet, still fails as for a refused token. Refs #2998 Co-Authored-By: Claude Opus 5.5 <[email protected]>
|
14d7da2 answers your inline comments and the points from your approval (tracked in #2999, which this PR now closes). The comments on Host-closed mark and incarnation ( 404 only when the session is gone (
Tests cover a session deleted during the open, a kept session whose scheduled run ended, and an open that presented a token. The comment is corrected. One consequence: a broker session closed while the open converted the token now answers 503 rather than 401 when the session is still stored. #3000 updates the design to match. A create's open still answers
The design side is #3000. |
What this does
The identity broker now records who acted, for whom, and what was decided. Before, it kept only ID-JAG and call-decision records. Now every event
audit.mdassigns to the broker produces a record, kept in memory behind one sink (Recorder) that can refuse a record. #2566 writes these records in the AuditEvent profile and delivers them; this PR builds no delivery.Each record:
AuditID(rec_…), minted once, and amecatl_type;Subjects()keyed by the profile'sSubjectskeys, each markedverified,credential-verified,record:<AuditID>,reported:mecak8s, orunavailable;AuditID: the session open that verified the user, the acting instance's registration, the parent's registration, and the delegation a run acts under. When the broker undoes an event after sending its success record, it records a refusal whoseSupersedesnames that record (the profile'sMetadata.Extra["mecatl.supersedes"]), because a sink can store a record and still fail to confirm it;reported:mecak8s(LineageProvenanceon registration and delegation records), and qualifies a verified workload by the issuer its authenticator verified (workload_iss; no authenticator verifies one yet, so it isunavailabletoday);(iss, jti)or by record reference. A test runs every event and checks that no access token, refresh token, agent credential, ID-JAG, or gateway token value appears in any record or its subjects.Records each event produces
mecatl_session_openconverted; user (owner, AS-1iss/sub, and the token's client asuser_client_id/user_client_iss) markedverified, kept only after AS-1 accepts the token; sourcejti; hard expiry; any replaced refresh token by theAuditIDof the open that stored it plus that open's sourcejtimecatl_session_openalready_converted; user from the converting open's recordmecatl_session_opentokenless; ownerreported:mecak8s, user and clientunavailableunless an earlier open verified themmecatl_session_openmecatl_session_closemecatl_instance_registeredag_ID and SPIFFE ID (verified), incarnation (reported:mecak8s), definition, parent and parent host session, parent's registrationAuditID, new / moved / previous registrationmecatl_instance_registeredmecatl_delegationRunOwner), allreported:mecak8s; registration references; parent delegation'sAuditID; whether this report recorded the delegating run as a root run;PreviousRecord, theAuditIDof the same delegation's report in an earlier broker session of the root, as when mecak8s reports it again after a reopen (forgotten when mecak8s closes the host session, as on a delete, or closes its current broker session itself). An identical repeat makes no second recordmecatl_delegationALREADY_EXISTSfor a changed repeat. An invalid request is recorded with only its workloadmecatl_id_jag(iss, jti), user from the grant's open record, run, delegation and registration referencesmecatl_id_jagrecord_not_accepted, superseding the ID-JAG record the sink did not accept; the ID-JAG is not redeemedmecatl_tool_decisionWrite order and failure
Settled in design PR #2984 (
docs/audit-write-order), which should merge first:jtiit converted, so the spent token never reaches AS-1 again. It fails with reasonrecord_not_accepted: as fortoken_used(UNAUTHENTICATED, which mecak8s answers with 401bearer_rejectedso the client refreshes) when it converted the request's token, andUNAVAILABLEotherwise. If the session closes while the record is sent, the open fails with the closing reason. Either way a refused-open record follows, superseding the success.FindSessionof that host session waits for the open to end, and checks again in case another open started a new session meanwhile; a lookup of an existing session never waits.CloseSessionRequest.RootHostSessionIDcloses the host session's open broker session and the new one an open of it is creating, without waiting for that open. The open then fails withsession_closedand stores no refresh token. If the close came before the open's record was sent, the open records only a refusal; if it came while the record was sent, a refusal superseding the success. The new session's close record is held until that refusal is queued and names it, so no close names a record the sink was not given first. mecak8s closes a deleted session, or a scheduled run that ended, this way, so a delete no longer depends on its find outlasting the open. An existing session can still close while an open's record is sent; that open fails the same way.CloseSessionRequest.RootHostIncarnationnames it. An open of a marked incarnation fails withsession_closedbefore it converts or stores anything. An open of another incarnation, as when the host session is created again under the same ID, is unaffected. That covers an open queued behind the one the close ended, and a request that loaded the session before its delete. Five minutes is well past the longest an open holds its host session's lock (two AS-1 requests of at most 30 seconds and one 10-second record send). Shortcut: the mark is in memory and per replica, so an open on a replica that did not serve the delete, after a restart, or more than five minutes later still gets a broker session that nothing closes before its hard expiry; removed by [Phase 3] Run mecak8s with the identity broker on more than one replica #2805 and Durable broker state and recovery #2563.open_refused) names the refusal's record, which is queued before it. An open refused on an existing session leaves that session as it was.UNAVAILABLEwithrecord_not_accepted, nothing is registered, and a refusal superseding the success is recorded. A new helper's or team member's first registration is not retried: it does not run. The root's registration is retried when its run starts, and a re-registration after a reopen on the agent's next call. Registrations of one incarnation are serialized around check, record, and admission. Signing stays outside the lock.UNAVAILABLEwithrecord_not_accepted, nothing is stored, and a superseding refusal is recorded. A new helper's first report is not sent again: it does not run. A delegation reported again after a reopen is reported again on the helper's next call. When a helper moves, the holder reports its current delegation to the new session too; if that report fails, it puts the helper's old entry back, so the next lookup moves it and reports again. Reports to one broker session are serialized.record_not_acceptedinstead of holding the call.Broker.Close, called at mecak8s shutdown after AS-1 stops taking requests, sends what is queued until its deadline. It reports each record it could not send, and the one still being sent, and counts both in its error. That record's send finishes on its own, so the sink may still accept it, or refuse it and have it reported a second time; theDeliveryFailurecontract says so. A refused open's close names the refusal's record even when the sink refused it; that is part of the [Phase 3] Authorization server and gateway audit records, and reconciliation #2848 shortcut.audit.md's order. An unaccepted ID-JAG or success decision fails the callUNAVAILABLEwithrecord_not_accepted. An unaccepted ID-JAG record is followed by an ID-JAG refusal that supersedes it, and a withheld success decision by a decision refusal that supersedes it.Supersedes(Metadata.Extra["mecatl.supersedes"]) is set on a refusal that undoes an earlier record of the same event: after the record was not accepted, or after it was accepted and the session closed while it was recorded. That refusal's outcome iserrorforrecord_not_acceptedanddeniedwhen a close undid the event, decisions included. A converted open'srecord_not_acceptediserrortoo, though its code isUNAUTHENTICATED.WithDeliveryFailures(AuditIDand type, never content). mecak8s logs them as warnings.record_not_acceptedhas codeUNAUTHENTICATEDfor a converted open andUNAVAILABLEotherwise, so callers match on the reason, not onerrors.Iswith its usual code.mecak8s
record_not_acceptedwithUNAUTHENTICATED) is answered with 401bearer_rejected, as fortoken_used. When the same caller's previous open, of any host session, failed the same way within the last minute, it gets 503identity_broker_unavailableinstead, so a sink outage does not have the client spend fresh tokens. The rule keys on the verified owner alone, since a create, fork, or clear opens a new host session on every attempt (scheduled runs present no token, so they do not count; schedule setup and renewal will count toward it once Phase 2, Slice 3: Scheduled runs — A scheduled run calls gateway tools on its own grant, with no one present #2569 adds them). Only a successful open ends it: atoken_usedfrom presenting the token the 503 spent keeps it. It is per replica and best effort.session_closed, with or without a token, is answered by what the store holds: 404session_not_foundwhen the session is gone or was created again under its ID, and 503identity_broker_unavailable, which the client retries, when it is still stored, as after a scheduled run ends and the session is kept for result delivery, or when a concurrent close lands while the open records. It is never 401: a refusal for a closed host session converted nothing, and after a 503 on a request that presented a token the client refreshes it anyway. Before, a tokenless one got 500. Every otherrecord_not_acceptedmaps toidentity_broker_unavailableby its code.Broker.Closewith a 10-second deadline, so close and refusal records still queued are sent or reported, and an end-to-end test can read them afterBuilt.Close.app.Built.IdentityBrokerRecords()returns the in-memory records, so the harness test reads the sink rather than the diagnostics line (a shortcut that Audit records and delivery #2566 removes).AuditID, outcome, refusal; no subjects). This is a shortcut that Audit records and delivery #2566 removes. It is how the harness and operators see records while they live only in memory.Shortcuts
app.Built.IdentityBrokerRecordsexposes the in-memory records (Audit records and delivery #2566); a closed broker session's discarded refresh token is not revoked (Sign-out and revocation #2568).Left for other tickets
These are noted on #2569, #2805, #2562, #2727, #2566, #2563, and #2568.
AuditIDandOpenKind. A schedule grant will need a typed reference to its schedule-setup record, so no scheduled-run record presents the saved owner as a fresh sign-in.IDJAGRecord.Useris still the grant's company identity (Owner), apart from the other records'OwnerandUser; aligning it is left to the Bind each gateway token to its call #2727 rebase, which edits the same code.mecatl_instance_registered, and becomes a child'sParentRecord. Left as is; Identity broker credential renewal and key rotation #2562 decides whether renewal is recorded as credential issuance instead.AuthorizeCallstill records no refusal for a request that fails validation or names an unknown session; that lives in the call path Bind each gateway token to its call #2727 is changing.record_not_acceptedbeyond what this PR does.Merging with #2727
The #2727 branch also edits
authorize.goandrecorder.go. Here,RecordIDJAGandRecordDecisionbecome oneRecordmethod, andDecisionRecordandIDJAGRecordembedRecordHeader, so the second PR to land rebases.IDJAGRecord.Userkeeps its old name and type (the grant's company identity) to keep that rebase small; aligning it with the other records (OwnerandUser) is left for then.API compatibility
Assessment: no wire change, no break. The gRPC and HTTP APIs keep their messages and codes.
identity_broker_unavailable(503) gains a cause, an audit sink that does not accept a record the request needs, and its documentation inuser-docs/reference/http-sse-api.mdanduser-docs/features/security-and-execution/caller-identity.mdnow says so, including that after a 503 on a request that presented a token, the client refreshes the token before retrying. Clients already retry it. Everything else is in-process Go: the broker'sService/Corecontract (Workload.Issuer, set only by a verifying authenticator;CloseSessionRequest.RootHostSessionIDandRootHostIncarnation;Broker.Close), theRecorderinterface (now oneRecordmethod; implementations are in this repo only), new record types, and a new broker reason,record_not_accepted.Behaviour a client can observe, none of it breaking:
UNAVAILABLE, which mecak8s reports asidentity_broker_unavailable, a retryable error clients already handle.record_not_accepted) reaches clients asidentity_broker_unavailable, or 401bearer_rejectedfor a converted open, so the client refreshes its token as aftertoken_used. A repeat of that converted-open failure by the same caller within a minute, for any session, is answered 503identity_broker_unavailable. The 503 has spent the token too, so a conforming client refreshes it before retrying, as for any 503 after a token was presented; presenting the spent token again getsbearer_rejected(token_used) and the rule still holds. The rule is per replica, so a retry another replica serves can get 401 again.session_closedif a close lands while its record is sent, and an open of a host session incarnation closed in the last five minutes, on the same replica, fails the same way. mecak8s used to answer a converting open'ssession_closedwith 401bearer_rejectedand a tokenless one with 500. It now re-checks the store: 404session_not_foundwhen the session was deleted, otherwise 503identity_broker_unavailable, a retryable error clients already handle. A host session created again under the same ID is not affected by the mark.No stored data changes: broker state is in memory. No major or feature change, no approval needed.
Testing
internal/identitybroker/records_test.go: each kind of open, every refused-open reason with the session it created closed (including an open cancelled while waiting for its host session), provenance after a tokenless open, every close path recorded once (including a hard expiry found by a lookup), registrations (main, helpers, re-admitted, moved, refused), delegation reports (accepted, nested, another root run, identical repeat, every refusal), the ID-JAG and decision references, a refused record per event, an undone open, registration, and delegation recorded as a refusal superseding the unaccepted success, a convertedjtistill remembered after an unrecorded open, the profile's Subjects keys, no credential value in any record, and the user from a real AS-1 token.token_usedrefusal seen leaving one in a Kind run.RegisterAgent,ReportDelegation, andCloseSessionwhile its open record is in flight. AFindSessionwaits for that open, and a find-then-close racing the open closes the session it made and discards its refresh token. A refusal returns, and the next registration of the same incarnation proceeds, while the sink is stalled on the refusal's record. Every send carries a deadline of at most 10 seconds.Broker.Closesends what is queued and reports what it cannot send, and app shutdown sends queued close records. A re-reported delegation'sPreviousRecordis only set across sessions and is forgotten on a requested close. The holder undoes a move whose second report fails. A mismatched answer's close is neither queued nor sent before the refusal it names. A close returns while the sink is stalled on its record. The queue keeps order, gives each send a deadline, and drops and reports a record past its bound. A re-reported delegation links to its earlier record. Invalid requests are recorded with only the workload. The workload issuer is used only when verified, and lineage is markedreported:mecak8s.TestIdentityBrokerOpenRefusalMappingcovers an unrecorded converted open answered as a refused token, with no broker session left.TestIdentityBrokerRepeatedUnrecordedOpenIsUnavailablecovers a create, on a new host session, answered 503 after a prompt's refusal; atoken_usedwith the spent token keeping the rule; and a success ending it.TestOpenRecordRefusalsRepeatPerCallercovers the one-minute window per caller.TestIdentityBrokerOpenOfAClosedHostSessioncovers a session deleted while its request opened it (404), a kept session whose scheduled run ended (503), and an open presenting a token (503, not 401).TestIdentityBrokerRecreatedSessionOpensAfterADeletedeletes a session and creates it again under the same ID within the window.TestIdentityBrokerDeleteClosesAnOpenInProgressdeletes a session, with a 50 ms broker timeout, while another replica's open of it is stalled in its exchange; the open then fails and no broker session is left.cmd/mecak8sTestIdentityBrokerRecordsWhoActedruns mecak8s with the real AS-1 and gateway and reads the broker's record sink. A main-agent gateway call, then a subagent's, produce an open, two registrations, a delegation, and an ID-JAG and decision for each call. The sink refuses nothing.Tokenheld in a record; duplicate records; missing close; swallowed or missing follow-up refusals; dropped references), and 11 more for the revised write order (a refused open's session kept when its refusal is recorded; a converted unrecorded open failingUNAVAILABLE; each rollback withoutSupersedes; an unrecorded registration not recorded as refused; a reasonless error; the mecak8s mapping; the key rename; a convertedjtiforgotten), and 13 for the review fixes (a new session reachable before its record, or never added; a mismatched answer's close queued early, or never sent; a queue that waits, is unbounded, or sends without a deadline; a delegation's previous record lost; an invalid open not recorded; the workload issuer ignored, or taken from an unverified workload; delegation lineage unmarked), and 11 for the second review (refusals sent synchronously; a waited record without a deadline; a lookup not waiting for, or not told of, a new open; a queue keeping overflow; Close not reporting what it could not send, or queueing after Close; a previous record within the same session, or never forgotten; a refused open's close before its refusal; the holder keeping a move whose second report failed). For the third review, the delete test fails against the old find-then-close, and the refusal test fails when decision refusals are sent synchronously. All were caught. The repeated check inFindSessionafter its wait has no dedicated test./code-reviewand a four-axis panel (spec, standards, tests, security, architecture, reuse, duplication) found no blockers. Their important findings are fixed here: the owner naming in the record family, the follow-up refusal records, and four test gaps. A design-fit check found no open decisions. This revision follows docs(agent-identity): settle the broker's write order for every audit event #2984's answer to its design review: the open's failure codes, no retry of an unrecorded registration or report, no session left by a refused open,Supersedeson every rollback, the user's client keys, and the stand-in marks moved to Mark team members created over the API as having a stand-in parent #2986. It also follows docs(agent-identity): settle the broker's write order for every audit event #2984 at 6ec9bda: retries only after a reopen, refusal outcomes, and the 503 for a repeated unrecorded open.session_closedopen by the store, and a recreated session opens after a delete.TestIdentityBrokerCloseDuringConversionIsRetryableand the mapping table's close-during-exchange case now expect 503 rather than 401. Mutants caught: a refusal and its close queued separately, a group checked one record at a time, no ID-JAG refusal, a mark that ignores the incarnation (broker and mecak8s tests), a delete that names no incarnation, the decision keeping the session's user after a retry, and the old 404/401 mapping ofsession_closed.token_usedending the 503 rule. Not dedicated-tested: the check of a closed session just before the success record is sent, a window no test can reach without a hook.record_not_acceptedandsession_closedrefusals; the queue counts a record in flight at close; conformance for closing by host session and its invalid requests.task lintandtask docsare clean.go test -racepasses oninternal/identitybroker/...(three runs),internal/agentcredential,internal/adapter/server,internal/app, andcmd/mecak8s.Closes #2541
Closes #2999
🤖 Generated with Claude Code