Skip to content

feat(mcp): session-scoped vMCP broker with per-tool external OAuth authorization - #1072

Merged
jhrozek merged 115 commits into
mainfrom
recon/session-mcp-auth-stack
Sep 8, 2026
Merged

jhrozek merged 115 commits into
mainfrom
recon/session-mcp-auth-stack

Conversation

@jhrozek

@jhrozek jhrozek commented Sep 4, 2026

Copy link
Copy Markdown
Contributor

Summary

Adds a session-scoped MCP broker capable of authenticating individual
protected upstream MCP servers via per-tool OAuth, replacing the
global-only MCP profile path with a mode-aware canonical authority
resolver (global vs broker).

  • WHY: mecak8s/mecatui deployments need to expose OAuth-protected MCP
    servers (e.g. a GitHub-broker) per session/caller, with credentials
    bound to the session rather than the process, and without requiring
    every session's first prompt to block on an eager OAuth round trip.
  • WHAT changed (high level, across the 67 commits in this branch):
    • internal/mcpbroker: new session-scoped Runtime/logical-session
      model — per-backend OAuth transactions, callback state, replay
      ledger, and workspace-services enrollment (the pre-prompt bundle
      that authenticates every configured protected backend together).
    • engine/session: new durable primitives — PendingAuthorization,
      AuthorizationResolution, PendingWorkspaceEnrollment,
      ExternalBinding, and the StateAuthorizing lifecycle state, all
      integrated into the existing reopen/interrupt/recover/abandon
      run-entry discipline.
    • engine/agent: PreparedRun/PrepareAuthorizationContinuation/
      PrepareAfterAuthorization let a host atomically install a pending
      tool call's effective results and resume the parked turn once an
      external authorization resolves (granted/denied/cancelled/expired/
      interrupted), including bounded compensation on failed persistence
      or a race with client cancellation.
    • internal/adapter/server: new GetMcpAuthorizationPresentation /
      RecheckMcpAuthorization / CancelMcpAuthorization RPCs (gRPC +
      HTTP/SSE) and ConnectWorkspaceServices / RetryWorkspaceEnrollment
      / CancelWorkspaceEnrollment for the enrollment bundle, session
      lease/mutation-capability wiring for every new mutation path (ADR
      0294), and session-affinity classification for the new RPCs.
    • cmd/mecak8s: wires the broker vertical into composition and the
      HTTP mux (broker OAuth authorize/token/callback routes), requires
      verified callers (bearer/OIDC/mTLS) for the broker control surface,
      and defaults configured MCP to broker authority (opt-in to global
      via the legacy --mcp-server flag).
    • cmd/mecatui: workspace-services enrollment surfaced as an
      on-demand /tools-connect / /tools-cancel command instead of a
      blocking modal, plus live status/authorization-URL observation.
    • Helm chart, docs (docs/adr/0245–0247, docs/acceptance/*,
      user-docs/features/mcp-oauth-and-credentials.md), and the
      session-correlation/affinity ADR (0294) updated to match.

Type of change

  • Bug fix
  • New feature
  • Refactoring (no behavior change)
  • Dependency update
  • Documentation
  • Other (describe):

Test plan

Required baseline

  • Linting (task lint) — clean across the root module, engine/,
    authn/oidc, and every provider/* submodule
  • Offline test suite (task test equivalent: go test ./... in
    both the root and engine/ modules) — green except four
    pre-existing failures verified to reproduce identically on
    unmodified origin/main (a macOS temp-dir symlink issue in
    cmd/mecatequi's TestRunNonEmptyDiffWhenAgentWritesFile, a
    role-telemetry regression already present on main, and two
    skill-learning tests that require live network access this
    sandbox blocks)
  • Offline demo (go run ./cmd/mecademo)

Conditional checks

  • Markdown changed: documentation generation and checks
  • User docs or user-facing behavior changed: user-docs site build
  • Guarded engine API surface affected: compatibility check
    (task api:check) — engine/api/*.txt regenerated and
    engine/CHANGELOG.md updated per change (session placement,
    environment/workspace unification, external binding typing,
    prepared-run authorization continuations)
  • Intentional guarded engine API change: baselines regenerated
  • Manual testing (describe below)

Does this introduce a user-facing change?

Yes. Operators can now configure mcp.mode: broker (mecak8s defaults
to broker when no legacy --mcp-server servers are configured) to run
protected upstream MCP servers behind per-tool OAuth. mecatui gains
/tools-connect and /tools-cancel commands to authorize the
session's configured protected MCP backends on demand rather than
blocking the first prompt.

Special notes for reviewers

This branch was rebased through 67 commits on top of a moved
origin/main; conflict resolution mostly involved carrying forward the
session.EnvironmentRef/server-owned-placement refactor (ADR 0291) and
the ADR-0294 session-lease/mutation-capability wiring that landed on
main concurrently with this branch's own development. A few real
bugs surfaced and were fixed during that process (documented in the
commit messages): a CloseSession/Drain deadlock from a
lease-acquisition ordering conflict, a stale-session-object identity
bug in startRunContent after an authorization interrupt/repair, and
a couple of missing runState.settled channel initializations that
panicked on close.

@jhrozek
jhrozek force-pushed the recon/session-mcp-auth-stack branch from 4292eff to ca492c4 Compare September 4, 2026 06:55
@jhrozek

jhrozek commented Sep 4, 2026

Copy link
Copy Markdown
Contributor Author

Re-triggering CI checks that didn't fire automatically on the last force-push.

@jhrozek jhrozek closed this Sep 4, 2026
@jhrozek jhrozek reopened this Sep 4, 2026
@jhrozek
jhrozek force-pushed the recon/session-mcp-auth-stack branch from ca492c4 to 6b36483 Compare September 4, 2026 07:22
@jhrozek
jhrozek force-pushed the recon/session-mcp-auth-stack branch from 3070e4f to 90b5810 Compare September 4, 2026 09:13

@JAORMX JAORMX left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Thorough panel review: requesting changes for the blocking security, lifecycle, and deployment issues below. The common theme is that the durable session/lease layer is being combined with broker state that remains process-local, while the current public and Kubernetes surfaces do not consistently preserve that boundary.

return nil
}

func (h HandlerBundle) routes(callbackPath string) ([]handlerRoute, error) {

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

**Security: this route is mounted outside the Harness API authenticator, but toolhive_process.go can leave incoming authentication unset when every configured broker upstream uses auth:none. That makes this vMCP endpoint an anonymous tool-execution surface: a network client can initialize/list/call managed tools without a Mecatl identity, session ownership, permission posture, or approval path.

Please either do not publish this handler unless protected broker targets require it, or require authenticated, session-bound caller authorization for every request. Add a non-loopback integration test proving anonymous initialize/list/call is rejected.

Refs: CWE-306 / OWASP API2:2023.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in d2ba04b (I-3): publication of the vMCP endpoint is now gated on the same condition that builds the incoming-auth middleware, plus a structural backstop in HandlerBundle.routes() that refuses to mount VMCP without the complete protected-handler bundle. Proven over a real network listener: an all-auth:none process publishes no vMCP route, and a mixed-config process rejects anonymous initialize/tools-list/tools-call with real 401s (handlers_test.go, toolhive_process_test.go).

# First-class remote Streamable HTTP MCP connections. Authentication is an
# explicit union: none, staticBearer, or oauth. Secret values are always read
# from same-namespace Kubernetes Secrets; they are never Helm values.
# explicit union: none, staticBearer, or oauth. OAuth selects the session MCP

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Broker deployment blocker: enabling this broker callback does not constrain the chart's two-replica default, although broker bindings, OAuth callback correlation, grants, and replay state are process-local. A plain Service can send the callback, presentation, or recheck for a session created on pod A to pod B; a session Lease prevents B from mutating the session, but does not route it back to A.

Until broker state is durable/shared and affinity is deployed, please fail chart validation for OAuth broker mode unless replicaCount: 1 (or otherwise make this configuration impossible).

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e8d64ab (I-4/I-5/P2-12): the Helm schema now makes replicaCount: 1 structurally required whenever OAuth broker mode is enabled (values.schema.json conditional required/const block), so this configuration is impossible rather than merely discouraged.

@@ -28,7 +29,7 @@ spec:
{{- if and (not .Values.mockProvider) (not .Values.security.allowUnsafeRealProvider) .Values.security.tlsTerminatedUpstream }}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This new profile checksum causes a rollout for broker configuration, but the Deployment retains an overlapping rolling-update strategy. Even with one desired replica, a profile/image update produces a second Ready process with a different in-memory broker incarnation; traffic for active sessions can reach it before the old pod drains, and broker grants/callback state are lost when the old process exits.

The interim single-process broker posture needs a non-overlapping rollout/drain strategy (or explicit maintenance/recreate contract), not only replicaCount: 1.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in e8d64ab (I-4/I-5/P2-12): the Deployment now sets strategy.type: Recreate whenever OAuth broker mode is enabled, with an inline comment explaining why (a surge RollingUpdate would run a second broker incarnation alongside the old one before drain, which the single-process, in-memory broker state cannot tolerate).

return st, nil
}

// NewClient builds a standalone redis.UniversalClient using the SAME

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

The normal Redis session store uses the watched/reloadable client generation, but this broker-specific client reads credentials/CA material once. After an ACL or CA rotation, the normal store may reload and /readyz remains green while broker authorization storage has stale credentials/trust and OAuth operations fail.

Please share the rotation-managed client/accessor with broker storage (or provide equivalent reload and readiness coverage), and narrow the hot-reload documentation until that is true.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Addressed in bc5a38c (I-6) via the documented alternative: confirmed toolhive-core's tcredis.Config exposes no credentials-provider/reload hook, so sharing the rotation-managed client isn't available as written. Narrowed docs/usage/mecak8s.md, the user-docs deployment guide, and NewClient's own doc comment to state plainly that the broker's dedicated Redis connection reads credentials once and needs a pod restart after rotation, rather than leaving the misleading hot-reload claim in place.

}
return WorkspaceEnrollmentProjection{Ref: presentation.Ref, Status: brokercontract.WorkspaceEnrollmentPending, URL: presentation.URL}, nil
}

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This clears PendingWorkspaceEnrollment only for connected. For expired, denied, failed, or cancelled enrollment, the aggregate remains pending while the broker may delete the terminal transaction. The user is then blocked from prompting and cannot reliably observe, cancel, or retry the exact enrollment.

Please atomically settle/abort the matching aggregate for every terminal outcome, so retry can create a replacement enrollment and prompts are no longer gated. Add lifecycle coverage for each terminal state followed by prompt/reconnect/retry/cancel.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 5783562 (I-7): every terminal enrollment status (connected/expired/denied/failed/cancelled) now atomically settles or aborts the matching session aggregate via settleTerminalWorkspaceEnrollment/recordObservedWorkspaceEnrollment, not only connected. Added lifecycle coverage for each terminal state followed by prompt/reconnect/retry/cancel.

@@ -3161,19 +3355,22 @@ func (s *Service) DeleteSession(ctx context.Context, id session.SessionID) error
if err != nil || absent {
return err
}
if !s.mutationLeaseHeld(id) {
return fmt.Errorf("%w: %q", ErrSessionLeasedElsewhere, id)
unlockBroker := s.brokerMu.lock(id)

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Deleting broker state before the durable session creates an unrecoverable partial-deletion state: if durable deletion subsequently fails, the snapshot remains but its broker binding no longer exists. A retry/reopen cannot reconstruct it. The same ordering appears in retention deletion paths.

Please make this a durable, idempotently resumable workflow (for example, a persisted cleanup marker/outbox/saga), or preserve broker state until durable deletion commits. Add fault-injection tests for failures at each step.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Fixed in 0e5e8d1 (I-8): reordered DeleteSession, DeleteSessionForRetentionCandidate, and DeleteSessionForRetention to delete the durable record first and treat broker cleanup as best-effort (logged, not returned) afterward. An already-completed durable delete still attempts broker cleanup on its early-return path so a handle is never orphaned. A broker-cleanup failure is now a bounded process-local leak instead of an unrecoverable partial-deletion window.

@JAORMX JAORMX left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up: net-new findings

This review excludes my earlier comments (including unrelated goldens) and covers only newly confirmed issues.

P1

  1. Enrollment cancellation can resurrect authority — internal/adapter/mcpbroker/workspace_enrollment.go:198-217,232-275; internal/adapter/mcpbroker/auth.go:676-705.
    A discovery operation can publish a stale grant snapshot after another attachment cancels enrollment, recreating grants that protected execution accepts. Version/claim the transaction before discovery; verify the exact grant remains current before publishing/installing it; add a blocked-discovery race test.

  2. OAuth requests omit the RFC 8707 resource indicator — internal/adapter/mcpbroker/auth.go:391-398,594-595; internal/adapter/mcpbroker/workspace_enrollment.go:296-306.
    MCP Authorization Spec 2025-06-18 requires the canonical MCP server URI in authorization and token requests: https://modelcontextprotocol.io/specification/2025-06-18/basic/authorization#resource-indicators. Carry the canonical resource to AuthCodeURL and Exchange, then test both outgoing requests.

  3. Event-sourced restore loses broker identity — engine/adapter/eventsource/eventsource.go:82-126,174-199.
    SessionMeta does not persist ExternalBinding, so fold cannot exactly reattach a broker-backed session. Persist/restore it, update the API baseline and changelog, and add fold-to-broker coverage.

  4. Broker wrappers erase tool behavior interfaces — internal/mcpbroker/broker.go:165-169.
    Wrapping only tool.Tool / tool.AuthorizationRequester drops DispatchSerial, Disclosable, and PlanOnly; dispatch/projection semantics can change. Preserve optional interface combinations and test them.

  5. Cancelled authorization handoff leaves EventLog unresolved — internal/adapter/server/mcp_authorization.go:397-425,459-467,516-520; engine/adapter/eventsource/eventsource.go:166-168.
    The snapshot is settled but a non-started prepared run emits no tool-result/resolution events, so a later fold sees pending authorization. Append a terminal resolution/results for every settled pre-start failure; test through EventLog and Fold.

  6. A transient initial load failure disables authorization expiry — internal/adapter/server/mcp_authorization.go:546-549; internal/adapter/server/service.go:6768-6772.
    The one-time expiry scheduling load can fail without a timer or retry, leaving authorizing past TTL. Schedule from known state or use bounded retry/diagnostics; add a fail-once store test.

  7. Authorization settlement failure aborts shutdown cleanup — internal/adapter/server/service.go:2771-2773,2903; internal/adapter/server/mcp_authorization.go:762-775.
    A false return skips cancellation, resource closure, and lease release; the composition close is once-only. Always continue mandatory cleanup after a bounded/reported settlement failure; test failing and blocking stores.

P2

  1. Attachment.Close races operation admission — internal/adapter/mcpbroker/auth.go:265-334,432-467.
    A request can pass its close check, block on secret resolution, and create an OAuth transaction after close returns. Linearize admission/close with a shared operation guard and cancellation context.

  2. Token refresh ignores cancellation under a session mutex — internal/adapter/mcpbroker/auth.go:622-654; internal/adapter/mcpbroker/runtime.go:324-340.
    It uses context.Background() and exchanges while holding logical.mu, preventing cancellation and blocking deletion. Snapshot under lock, refresh outside it using the operation context, then conditionally install the result.

  3. Shutdown closes dependencies before active broker calls drain — internal/adapter/mcpbroker/auth.go:755-775; internal/adapter/mcpbroker/toolhive_process.go:365-391,451-485.
    Runtime close returns with active operations, then process close may stop resources beneath those operations. Stop admission, cancel/join operations before closing dependencies, with a bounded shutdown policy.

  4. Token endpoint query handling is inconsistent with config and RFC 6749 §3.2 — internal/adapter/mcp/oauth_http.go:53-56; internal/adapter/mcpbroker/auth.go:41-66.
    Config accepts query components, runtime rejects RawQuery, though token endpoint queries are permitted. Preserve trusted configured queries or reject them consistently at configuration validation and document it.

  5. Helm mixed-auth validation depends on list order — deploy/helm/mecak8s/templates/_helpers.tpl:106-124; deploy/helm/mecak8s/templates/deployment.yaml:145-157.
    [oauth, staticBearer] fails but [staticBearer, oauth] renders an app-invalid combination. Count modes over the complete list before validation and test both orders.

  6. Broker resource inventory rows are outside the Markdown table — docs/adr/0027-cloud-native.md:930-932.
    Rows 68–70 render as pipe-delimited paragraphs, not List 1 inventory rows. Move them before the table close or add a headed continuation table.

Targeted go test ./internal/adapter/mcpbroker passed. The race build was blocked by isolated-checkout disk quota while compiling ToolHive, not a test failure.

@jhrozek
jhrozek force-pushed the recon/session-mcp-auth-stack branch from 90b5810 to 2adf71a Compare September 6, 2026 18:28

@JAORMX JAORMX left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I think REVIEW_LEDGER.md was checked in by accident

jhrozek added a commit that referenced this pull request Sep 7, 2026
REVIEW-LEDGER.md was an internal audit/status doc for this branch's
review, checked in by accident — flagged in PR #1072 review. Its
content is superseded by the actual fix commits and the PR's own
review-thread history.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@jhrozek
jhrozek force-pushed the recon/session-mcp-auth-stack branch from 2adf71a to 49d991f Compare September 7, 2026 05:36
Comment thread .matlatlignore Resolved
jhrozek added a commit that referenced this pull request Sep 7, 2026
REVIEW-LEDGER.md was an internal audit/status doc for this branch's
review, checked in by accident — flagged in PR #1072 review. Its
content is superseded by the actual fix commits and the PR's own
review-thread history.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@jhrozek
jhrozek force-pushed the recon/session-mcp-auth-stack branch from c8cae36 to 78ba8ba Compare September 7, 2026 08:26
jhrozek added a commit that referenced this pull request Sep 7, 2026
REVIEW-LEDGER.md was an internal audit/status doc for this branch's
review, checked in by accident — flagged in PR #1072 review. Its
content is superseded by the actual fix commits and the PR's own
review-thread history.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@jhrozek
jhrozek force-pushed the recon/session-mcp-auth-stack branch from 78ba8ba to c2e8a9e Compare September 7, 2026 08:45

@JAORMX JAORMX left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up review (current c2e8a9e25)

I rechecked the earlier findings rather than reviewing the same areas twice. The prior vMCP authentication, single-incarnation Helm posture, enrollment terminal handling, deletion ordering, OAuth resource indicators, and broker-operation shutdown fixes are present and covered by targeted tests.

Blocker

  1. Authorization crash window leaves an EventLog that cannot be folded — engine/agent/loop.go:1787-1806, engine/adapter/eventsource/eventsource.go:503-514.

    The authorizing snapshot is saved before EvAuthorizationRequired is emitted to the relay/EventLog. A process failure in that interval leaves no authorization.required record. Restart recovery then persists tool results and authorization.resolved, but Fold rejects a terminal resolution with no matching required lifecycle event. This breaks the event-sourced reconstruction contract precisely on the crash-recovery path. Please either make recovery reconcile this narrow missing-required sequence or ensure the durable lifecycle record is committed consistently; add a save-before-emit crash-window fold test.

Important

  1. Terminal authorization settlement can persist running without an owning runtime — engine/session/authorization.go:162-178, internal/adapter/server/mcp_authorization.go:397-419, :845-862.

    AbortAuthorization and InterruptAuthorization set StateRunning. Both the no-continuation fallback and shutdown settlement persist that state without starting a run or emitting EvResult. The next prompt treats it as a crash orphan and listings remain misleading until repair. Reserve running for a successfully registered continuation; make no-continuation terminal settlement transition and persist a terminal state/event.

  2. New session-bound gRPC controls omit affinity-hint validation — internal/adapter/server/grpc.go:1409-1512, internal/adapter/server/session_affinity_grpc_test.go:63-87.

    ConnectWorkspaceServices, RetryWorkspaceEnrollment, CancelWorkspaceEnrollment, GetMcpAuthorizationPresentation, RecheckMcpAuthorization, and CancelMcpAuthorization are classified as session-bound but never call the existing gRPC affinity validator. Duplicate or mismatched X-Mecatl-Session-ID metadata thus reaches service work rather than failing at ingress, contrary to the ADR-0294 acceptance matrix. Validate the hint before service work (before first Recv for bidi streams) and add exact/mismatch/duplicate behavioral coverage.

I did not include the reuse-only suggestion to consolidate refresh helpers: given the separate grant semantics and this PR's risk profile, keeping that structure is a reasonable trade-off.

jhrozek added a commit that referenced this pull request Sep 7, 2026
…lifecycle

Addresses JAORMX's 2026-09-07 follow-up review on PR #1072.

Blocker: the authorizing snapshot is durably saved before
EvAuthorizationRequired reaches the EventLog (an async, relay-owned
append). A process crash in that narrow window leaves a durably-awaiting
session with no matching required record; the later resolved event then
makes eventsource.Fold reject the whole session. Added
ensureAuthorizationRequiredLogged, which reads the log once for the
authorization ID and backfills a required event (built from the durable
pending state) only when genuinely missing — never blindly, since a
duplicate required is its own Fold rejection. Wired into both
resolveAuthorizationLocked and settleAuthorizationLocked, ahead of every
call site that appends the resolved event.

Important: AbortAuthorization/InterruptAuthorization unconditionally
leave the session StateRunning, correct when a real Engine.Run is about
to start. The no-continuation fallback and shutdown settlement start no
run, so the durable snapshot was stranded StateRunning forever with no
owning process — the next prompt misread it as a crash orphan. Both
paths now call sess.Abandon() (settling to idle with accurate close-out
wording) and best-effort re-save after the resolution is durably logged,
matching the existing repairAuthorizationRegistration convention.
Updated three tests that had pinned the stranded StateRunning as the
correct outcome.

Important: six session-bound gRPC controls (ConnectWorkspaceServices,
RetryWorkspaceEnrollment, CancelWorkspaceEnrollment,
GetMcpAuthorizationPresentation, RecheckMcpAuthorization,
CancelMcpAuthorization) were classified as session-bound by ADR-0294's
acceptance matrix but never actually validated the X-Mecatl-Session-ID
affinity hint, so a mismatched or duplicate header reached service work
instead of failing at ingress. Added validateGRPCSessionAffinity calls;
the two bidi streams get the same two-phase pattern Converse already
uses (validate metadata shape before the first Recv, then validate the
real session id after). Extended the existing affinity matrix test with
all six.

Also registers ensureAuthorizationRequiredLogged in the ADR-0294
session-mutation inventory (a new Save/appendEvent-adjacent method must
be classified or the governance test fails the build).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@jhrozek

jhrozek commented Sep 7, 2026

Copy link
Copy Markdown
Contributor Author

Fixed all three findings from the 2026-09-07 follow-up review in 2a7fcedb0:

  1. Blocker (crash-window EventLog gap): added ensureAuthorizationRequiredLogged/authorizationRequiredLogged — reads the log once for the authorization ID and backfills the missing required event (from the durable pending state) only when genuinely absent, wired into both resolveAuthorizationLocked and settleAuthorizationLocked ahead of every resolved-event append site. New test TestMCPAuthorizationResolutionBackfillsMissingRequired reproduces the exact crash window, proves eventsource.Fold recovers, and proves no duplicate on a second call.

  2. Important (stranded StateRunning): both the no-continuation fallback and shutdown settlement now call sess.Abandon() + best-effort re-save once the resolution is durably logged, settling the snapshot to idle instead of leaving it stranded StateRunning forever. Updated the three tests that had pinned the stranded state as correct.

  3. Important (gRPC affinity): added validateGRPCSessionAffinity to all six flagged RPCs — the two bidi streams (RecheckMcpAuthorization/CancelMcpAuthorization) get the same two-phase pattern Converse already uses (validate metadata shape before the first Recv, then validate the real session id after). Extended the existing affinity matrix test with all six.

Also caught and fixed a regression an independent review pass surfaced: the new ensureAuthorizationRequiredLogged wasn't registered in ADR-0294's session-mutation-inventory governance test, which would have failed CI.

go test ./internal/adapter/server/... and go vet both clean.

@JAORMX JAORMX left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Follow-up review (2a7fcedb0)

I reviewed only the two commits after c2e8a9e25 and rechecked the three previous findings. The gRPC affinity coverage now reaches all six controls. The two authorization-lifecycle fixes are not yet complete.

Blockers

  1. Recovery still has a new crash window before the backfill. internal/adapter/server/mcp_authorization.go:400-409, 521-544.

    resolveAuthorizationLocked calls AbortAuthorization, records results, and saves the session—which removes the only durable PendingAuthorization—before ensureAuthorizationRequiredLogged. A crash (or failed backfill append) after that save loses the source needed to reconstruct authorization.required; terminal result/resolution persistence can then make eventsource.Fold reject the log. Reconcile and durably append the required lifecycle event before consuming the pending snapshot, and make a failed reconciliation prevent terminal lifecycle append/reporting. Add crash/fault-injection coverage for this ordering.

  2. The restored-authorization interruption path bypasses both lifecycle repairs. internal/adapter/server/mcp_authorization.go:816-829.

    interruptRestoredAuthorizationLocked appends authorization.resolved without ensureAuthorizationRequiredLogged, then returns the intermediate StateRunning snapshot with no continuation owner. Thus the same save-before-required crash path remains non-foldable after restart, and the session is again left to be misclassified as a crash orphan. Backfill/check the required event before the terminal append and settle the no-continuation snapshot to idle; add a regression test for the missing-required restored path.

@JAORMX JAORMX left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Incremental review (052fefd73)

I reviewed only the commit after c2e8a9e25, plus the author’s responses to the three outstanding lifecycle/affinity findings. The required-event reconciliation is correctly moved before pending consumption in the terminal and restored-interruption paths, and the gRPC-affinity fix was already covered in the preceding follow-up commit. However, two concrete lifecycle gaps remain:

Blockers

  1. Granted authorization still has the original EventLog crash window. internal/adapter/server/mcp_authorization.go:305.

    continueGrantedAuthorizationLocked calls ClaimAuthorization() and persists the cleared PendingAuthorization without first calling ensureAuthorizationRequiredLogged. If the original authorization.required relay append was lost in the save-before-emit window, a crash after this granted-path save permanently removes the only data needed to backfill it. The later granted resolution then remains non-foldable. Reconcile/fail before ClaimAuthorization, as the terminal paths now do, and cover the granted path.

  2. Restored-interruption error paths can still persist an unowned running session. internal/adapter/server/mcp_authorization.go:851-854,954-975; internal/adapter/server/service.go:4414-4447.

    The helper saves StateRunning before appending terminal lifecycle events. If that append fails, it returns before startRunContent has installed its deferred repair guard; similarly, the no-continuation/shutdown flows only abandon after a successful append. There is then no run owner and no pending authorization to retry, leaving the exact stranded-running condition from the earlier finding. Independently settle/repair the snapshot on every post-save failure (and surface a failed repair), with fault-injection coverage for both the restored path and terminal append failure.

Remote PR checks currently report no check runs for this head. I did not run local CI, per review scope.

jhrozek added a commit that referenced this pull request Sep 7, 2026
REVIEW-LEDGER.md was an internal audit/status doc for this branch's
review, checked in by accident — flagged in PR #1072 review. Its
content is superseded by the actual fix commits and the PR's own
review-thread history.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
jhrozek added a commit that referenced this pull request Sep 7, 2026
…lifecycle

Addresses JAORMX's 2026-09-07 follow-up review on PR #1072.

Blocker: the authorizing snapshot is durably saved before
EvAuthorizationRequired reaches the EventLog (an async, relay-owned
append). A process crash in that narrow window leaves a durably-awaiting
session with no matching required record; the later resolved event then
makes eventsource.Fold reject the whole session. Added
ensureAuthorizationRequiredLogged, which reads the log once for the
authorization ID and backfills a required event (built from the durable
pending state) only when genuinely missing — never blindly, since a
duplicate required is its own Fold rejection. Wired into both
resolveAuthorizationLocked and settleAuthorizationLocked, ahead of every
call site that appends the resolved event.

Important: AbortAuthorization/InterruptAuthorization unconditionally
leave the session StateRunning, correct when a real Engine.Run is about
to start. The no-continuation fallback and shutdown settlement start no
run, so the durable snapshot was stranded StateRunning forever with no
owning process — the next prompt misread it as a crash orphan. Both
paths now call sess.Abandon() (settling to idle with accurate close-out
wording) and best-effort re-save after the resolution is durably logged,
matching the existing repairAuthorizationRegistration convention.
Updated three tests that had pinned the stranded StateRunning as the
correct outcome.

Important: six session-bound gRPC controls (ConnectWorkspaceServices,
RetryWorkspaceEnrollment, CancelWorkspaceEnrollment,
GetMcpAuthorizationPresentation, RecheckMcpAuthorization,
CancelMcpAuthorization) were classified as session-bound by ADR-0294's
acceptance matrix but never actually validated the X-Mecatl-Session-ID
affinity hint, so a mismatched or duplicate header reached service work
instead of failing at ingress. Added validateGRPCSessionAffinity calls;
the two bidi streams get the same two-phase pattern Converse already
uses (validate metadata shape before the first Recv, then validate the
real session id after). Extended the existing affinity matrix test with
all six.

Also registers ensureAuthorizationRequiredLogged in the ADR-0294
session-mutation inventory (a new Save/appendEvent-adjacent method must
be classified or the governance test fails the build).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@jhrozek
jhrozek force-pushed the recon/session-mcp-auth-stack branch from 052fefd to 0529dab Compare September 7, 2026 11:29
jhrozek added a commit that referenced this pull request Sep 7, 2026
REVIEW-LEDGER.md was an internal audit/status doc for this branch's
review, checked in by accident — flagged in PR #1072 review. Its
content is superseded by the actual fix commits and the PR's own
review-thread history.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
jhrozek added a commit that referenced this pull request Sep 7, 2026
…lifecycle

Addresses JAORMX's 2026-09-07 follow-up review on PR #1072.

Blocker: the authorizing snapshot is durably saved before
EvAuthorizationRequired reaches the EventLog (an async, relay-owned
append). A process crash in that narrow window leaves a durably-awaiting
session with no matching required record; the later resolved event then
makes eventsource.Fold reject the whole session. Added
ensureAuthorizationRequiredLogged, which reads the log once for the
authorization ID and backfills a required event (built from the durable
pending state) only when genuinely missing — never blindly, since a
duplicate required is its own Fold rejection. Wired into both
resolveAuthorizationLocked and settleAuthorizationLocked, ahead of every
call site that appends the resolved event.

Important: AbortAuthorization/InterruptAuthorization unconditionally
leave the session StateRunning, correct when a real Engine.Run is about
to start. The no-continuation fallback and shutdown settlement start no
run, so the durable snapshot was stranded StateRunning forever with no
owning process — the next prompt misread it as a crash orphan. Both
paths now call sess.Abandon() (settling to idle with accurate close-out
wording) and best-effort re-save after the resolution is durably logged,
matching the existing repairAuthorizationRegistration convention.
Updated three tests that had pinned the stranded StateRunning as the
correct outcome.

Important: six session-bound gRPC controls (ConnectWorkspaceServices,
RetryWorkspaceEnrollment, CancelWorkspaceEnrollment,
GetMcpAuthorizationPresentation, RecheckMcpAuthorization,
CancelMcpAuthorization) were classified as session-bound by ADR-0294's
acceptance matrix but never actually validated the X-Mecatl-Session-ID
affinity hint, so a mismatched or duplicate header reached service work
instead of failing at ingress. Added validateGRPCSessionAffinity calls;
the two bidi streams get the same two-phase pattern Converse already
uses (validate metadata shape before the first Recv, then validate the
real session id after). Extended the existing affinity matrix test with
all six.

Also registers ensureAuthorizationRequiredLogged in the ADR-0294
session-mutation inventory (a new Save/appendEvent-adjacent method must
be classified or the governance test fails the build).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
jhrozek and others added 21 commits September 8, 2026 10:29
…I-5/P2-12)

Broker session, grant, and authorization-transaction state is
process-local, so a multi-replica deployment or a surge rollout can
route a request to a pod that has no idea about it. Three fixes:

- I-4: schema now requires replicaCount: 1 whenever
  mcp.broker.callbackURL is set, including the chart's own default of
  2 — the actual scenario an operator hits by enabling broker mode
  without also touching replicaCount.
- I-5: the Deployment renders strategy.type: Recreate instead of
  RollingUpdate in that same mode, so a config/image change fully
  retires the old broker incarnation before starting the new one — a
  real downtime window, the correct tradeoff until broker state is
  shared. Reused the existing $mcpOAuth template local for both
  detection points rather than duplicating it.
- P2-12: the staticBearer/OAuth mixed-auth rejection counted and
  checked in the same range pass, so [oauth, staticBearer] correctly
  failed but [staticBearer, oauth] rendered the same invalid
  combination. Count both modes over the complete server list first,
  then validate once after the loop.

Updated the two stale "chart intentionally leaves replica behavior
unchanged" doc callouts (docs/usage/mecak8s.md and the user-docs
deployment guide) that I-4/I-5 make untrue, added replicaCount: 1 to
both worked broker examples, and fixed the shared renderOAuthMCPValues
test fixture (every existing broker-OAuth test rendered at the old
default replicaCount: 2) before it could go red under the new schema
rule.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
… ADR

Rows 68-70 (MCP broker resources) followed 13 lines of prose with no
blank line or restated header, so Markdown renderers treated them as
disconnected paragraphs instead of a continuation of the List 1 table.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…alize concurrent refreshes

The embedded ToolHive authorization server's client was registered public
(no secret), reachable on the same public listener as everything else with
no gate from mecatl's own session/caller-auth. An attacker who learned the
process-wide client_id could self-drive /authorize, capture a code off the
raw redirect, and call /oauth/token directly to mint a valid broker JWT —
bypassing mecatl's session ownership, permission gate, and audit trail
entirely. Register it confidential (client_secret_basic, ToolHive's own
registration helper, hashed secret) instead; PKCE stays as defense in depth.

Also closes a concurrent-refresh race: two goroutines racing a refresh of
the same grant could have the loser's invalid_grant error revoke the token
the winner just installed, because in-place token mutation defeated the
existing pointer-identity reverify. A per-grant refreshMu now fully
serializes refresh attempts, with a check-lock-recheck so a second caller
returns the already-refreshed token instead of repeating the round trip.

RFC 8707's resource indicator, previously sent only on the initial exchange,
is now also carried on refresh (a resourceRefreshTransport injects it into
the refresh request body, since oauth2.Config.TokenSource has no hook for
extra params on that path).

See ADR 0299 for the confidential-client decision.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…t commits, bound shutdown drain to one deadline

FreezeAuthenticatedCatalogue published the discovered catalogue before the
logical enrollment transaction had committed. A sibling attachment cancelling
its own enrollment in that window left the published catalogue permanently
wedged against the now-cancelled ref, failing every later enrollment attempt
through that Attachment. freezeAuthenticatedCatalogue now takes a publish
bool; the enrollment path stages the result privately and only installs it
after re-verifying the transaction/credential are still current under lock.

Also: Runtime.Close's mark-closed and session-snapshot steps were two
separate critical sections, so a session could attach in the gap and never
get waited on during drain while Process.Close tore down the resources
underneath it. closeAndSnapshot now does both atomically under one lock, and
closeAndDrain waits on one shared deadline for the whole session set instead
of the full per-session timeout summed across all of them.

Two Medium findings from the same review, both in the enrollment path:
- A discovery call interrupted by the caller's own context cancellation (not
  a genuine backend rejection) no longer clears the granted credential —
  ctx.Err() is checked separately from FreezeAuthenticatedCatalogue's error,
  so a transient timeout doesn't force the user to redo browser consent.
- A terminal observation now leaves a retryable tombstone instead of deleting
  the transaction outright, so a host save failure after observing a
  terminal result doesn't wedge the durable pre-prompt gate: retrying finds
  the same terminal result instead of ErrAuthorizationNotFound.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…us on the wire

toProtoWorkspaceEnrollment mapped both "denied" and "expired" down to
"failed" before sending the enrollment status to the client — discarding the
distinction the broker layer had just started producing (access_denied vs. a
genuine failure) and the client already had separate messaging wired for
("connection was declined" vs. "connection failed"). Pass the real status
through unchanged.

Adds a server-level test proving the save-failure recovery from the
previous commit: a forced store failure on the first terminal observation
leaves the durable pending enrollment untouched, and a retry completes the
save and clears it correctly.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
MCPStaticToolProfile's doc comment still described the original "admitted
without discovery, authorized lazily on first call" design, but the current
implementation stages every declared tool behind the same workspace-
enrollment gate as an undeclared backend — confirmed live, a declared
backend's tools are invisible until /tools-connect completes. Correct the
comment to describe what the code actually does today.

(This is expected to be revised again once the lazy on-demand connection fix
lands — see .scratch/handovers/lazy-ondemand-toolhive-connection-HANDOVER.md.)

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…is-backed auth storage

Adds ADR 0299's scenario/acceptance coverage to the multi-upstream OAuth
acceptance plan, narrows the AC2.1 real-ToolHive claim to be honest about
what the fixture actually proves (ToolHive v0.45 doesn't correlate an
internally-received upstream access_denied back to mecatl's outer callback;
that path is covered by focused adapter tests instead, not the E2E fixture).

Adds cloud-native inventory rows for ToolHive's own Redis-backed auth
storage (List 1 row 71 / List 2 row 46) — durable inner upstream token
records are a genuinely different resource from mecatl's process-local
outer callback/enrollment correlation, and the previous inventory rows
described everything as in-memory-only without accounting for it.

Updates architecture.md, IMPLEMENTATION-NOTES.md, and the user-facing
mcp-oauth-and-credentials.md to describe both of the above.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…ing task lint

Unrelated to the broker OAuth work in the preceding commits — task lint was
already failing on this branch before any of it: two gocyclo complexity
warnings on functions whose branches each guard a distinct precondition
(nolint with justification, matching this repo's existing convention),
terminalWorkspaceEnrollmentNotice's always-empty notice return kept as a
symmetric slot for a future terminal status, and one genuinely dead
Attachment.stateError (unused since before this session, no callers even at
HEAD) removed outright.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…ed against ToolHive on first call

A protected backend with a static tools: declaration was completely invisible
until an explicit /tools-connect completed the full bundle enrollment,
contradicting the feature's own name and original intent: compileStaticProtectedRoutes
already computed the right routes, but its result was discarded, and the
initial catalogue was built from anonymous backends only.

All authorization still goes through ToolHive — nothing bypasses it. Declared
routes are now installed into the initial catalogue (visible immediately, no
live discovery needed since their schema is already known) and marked with
both `oauth` (ToolHive's embedded-server issuer) and `broker` (execute via
the outer broker credential once granted). The first call to one of them
starts a normal per-tool authorization pause, but the resulting transaction
represents ToolHive's complete ordered protected-backend bundle
(bundleBackends), not a per-backend grant — ToolHive has no way to authorize
a single upstream independently, so a bundle transaction is the only accurate
representation of what its consent screen covers. A granted bundle credential
now satisfies every other declared tool's call with no repeat consent
(existingAuthorizationLocked checks logical.brokerCredential for bundle
routes), and execution correctly routes through the broker-credential path
(Execute now checks `broker` before `oauth`).

Fixes a real hazard this would otherwise cause: simply adding the declared
routes to the initial catalogue collides with the same routes re-staged
during authenticated discovery, failing every enrollment freeze. catalogueInputs
and stageAuthenticatedRoutes' de-dup seed now both filter to oauth-free
routes, so the frozen catalogue still supersedes the pre-connection stand-ins
cleanly with no duplicate/stale entries.

Ceiling, by design and documented in ADR 0300: a lazy authorization unlocks
only the declared surface. A backend's undeclared tools, and any backend
with no declaration at all, remain reachable only through explicit
pre-prompt /tools-connect (full authenticated discovery requires the
zero-message engine-rebuild that a mid-run tool call cannot perform).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Documents the previous commit's design: ADR 0298 correctly made ToolHive own
the entire upstream OAuth chain, but its pre-prompt-only static-tool staging
was an unintended side effect, not a deliberate part of that decision. ADR
0300 narrowly supersedes only that one admission-timing choice — every
ADR 0298 prohibition (no per-backend mecatl OAuth, no upstream token copying,
no selector on the shared callback) still holds.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
REVIEW-LEDGER.md was an internal audit/status doc for this branch's
review, checked in by accident — flagged in PR #1072 review. Its
content is superseded by the actual fix commits and the PR's own
review-thread history.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
Follow-up to ff7df82, which renamed the file but missed the content
edits: fixes the in-body title/links in ADR 0304 itself, the "See
also" links in ADR 0302/0303, the acceptance doc's ADR references,
IMPLEMENTATION-NOTES's P10 citation, cloud-native.md's List 1 row 46,
the README index (also reordered 0302/0303/0304 into numeric order),
and the stale REVIEW-LEDGER.md entry in .matlatlignore.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…lifecycle

Addresses JAORMX's 2026-09-07 follow-up review on PR #1072.

Blocker: the authorizing snapshot is durably saved before
EvAuthorizationRequired reaches the EventLog (an async, relay-owned
append). A process crash in that narrow window leaves a durably-awaiting
session with no matching required record; the later resolved event then
makes eventsource.Fold reject the whole session. Added
ensureAuthorizationRequiredLogged, which reads the log once for the
authorization ID and backfills a required event (built from the durable
pending state) only when genuinely missing — never blindly, since a
duplicate required is its own Fold rejection. Wired into both
resolveAuthorizationLocked and settleAuthorizationLocked, ahead of every
call site that appends the resolved event.

Important: AbortAuthorization/InterruptAuthorization unconditionally
leave the session StateRunning, correct when a real Engine.Run is about
to start. The no-continuation fallback and shutdown settlement start no
run, so the durable snapshot was stranded StateRunning forever with no
owning process — the next prompt misread it as a crash orphan. Both
paths now call sess.Abandon() (settling to idle with accurate close-out
wording) and best-effort re-save after the resolution is durably logged,
matching the existing repairAuthorizationRegistration convention.
Updated three tests that had pinned the stranded StateRunning as the
correct outcome.

Important: six session-bound gRPC controls (ConnectWorkspaceServices,
RetryWorkspaceEnrollment, CancelWorkspaceEnrollment,
GetMcpAuthorizationPresentation, RecheckMcpAuthorization,
CancelMcpAuthorization) were classified as session-bound by ADR-0294's
acceptance matrix but never actually validated the X-Mecatl-Session-ID
affinity hint, so a mismatched or duplicate header reached service work
instead of failing at ingress. Added validateGRPCSessionAffinity calls;
the two bidi streams get the same two-phase pattern Converse already
uses (validate metadata shape before the first Recv, then validate the
real session id after). Extended the existing affinity matrix test with
all six.

Also registers ensureAuthorizationRequiredLogged in the ADR-0294
session-mutation inventory (a new Save/appendEvent-adjacent method must
be classified or the governance test fails the build).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
… pending

Follow-up to 2a7fced. JAORMX's 2026-09-07 10:24 re-review found the
reconciliation fix was ordered too late and missed a third call site.

ensureAuthorizationRequiredLogged ran AFTER AbortAuthorization/
InterruptAuthorization had already cleared the session's only durable
PendingAuthorization and that cleared state was already saved — so a
crash or a failed backfill append after that save point lost the exact
source data needed to reconstruct the required event, relocating the
original unfoldable-log bug rather than closing it. Moved the call to
run FIRST, before any mutation, in resolveAuthorizationLocked and
settleAuthorizationLocked, and changed it to return an error instead of
warning-and-continuing: a failed reconciliation now aborts the whole
resolution with pending fully intact, so the caller can just retry
instead of losing the recovery point.

Also missed interruptRestoredAuthorizationLocked (StartRunContent's
restored-authorization repair path), a third site with the identical
resolve-then-append shape. Reconciled the same way, and closed its own
stranding risk: it durably saves StateRunning on the promise that a
real Engine.Run is about to take ownership, but every return between
that save and the actual BeginRun+engine.Run handoff left the same
snapshot stranded with no owning run. A deferred repairRunningSession
now settles it back to idle unless the handoff actually completes.

Updated TestStartRunRepairsUnavailableRestoredAuthorizationBeforeFailingReattach
(now correctly idle instead of pinning the stranded-running bug) and
added TestMCPAuthorizationReconciliationFailureLeavesPendingIntact,
proving a reconciliation failure aborts with the session completely
untouched.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…post-save failure

Follow-up to 052fefd. JAORMX's 2026-09-07 11:23 incremental review found
two more gaps in the same family:

A fourth call site, continueGrantedAuthorizationLocked, was missed
entirely — it consumes pending via ClaimAuthorization with no
reconciliation at all, so a crash after its own save could permanently
lose the source data needed to backfill a missing required event, same
as the three already-fixed terminal paths. Reconciled it first, before
ClaimAuthorization, identically to the others.

The deeper structural gap: every "settle to idle on no continuation" repair
only fired after a SUCCESSFUL terminal-lifecycle append. A FAILED append
returned early and skipped settlement entirely, stranding the exact
unowned StateRunning snapshot the repair exists to prevent — just on the
failure path instead of the success path. Replaced the narrow
success-only repairs in resolveAuthorizationLocked and
settleAuthorizationLocked with unconditional defers registered right
after the state-mutating save, so every return between there and a
genuine continuation handoff settles the snapshot, whether the append in
between succeeded or failed. interruptRestoredAuthorizationLocked had
the same gap from the other direction: a failed append returned an error
before StartRunContent's own deferred repair guard (from the previous
fix) was ever registered, so it now settles itself internally before
propagating the error.

Added tests for all three: the granted path backfilling a missing
required event, shutdown settlement idling despite an append failure,
and the restored-interruption repair idling despite its own append
failure.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
authorizationEvent's status parameter shadowed the status package
import — pre-existing branch debt CI's Analysis job just started
catching. Renamed to authStatus; no behavior change.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…d grant compensation

Follow-up to 5115404/93c6f4e66. JAORMX's next incremental review found
two more edge cases in the same family, both now independently verified.

appendAuthorizationResolution used to return immediately on the first
per-event append error. port.EventLog.Append's contract makes such an
error ambiguous (the event may already be durably committed) and
forbids retrying it — but the old code also abandoned every event AFTER
the failing one, so a failure on the primary call's own result (the
first event in the sequence) meant authorization.resolved never got
appended at all: a permanently non-eventsource.Fold-reconstructable
log, since Fold requires the primary call answered before accepting
resolved. Changed the function to track the first error and continue
attempting every remaining event regardless — bounded, honest damage
control for an irreducible ambiguity: if the one flagged write did
commit (the only case any caller-side fix can help with), the rest of
the sequence still lands and the log stays foldable. Rewrote
TestMCPAuthorizationTerminalFallbackAppendFailureIsExplicit to seed a
full turn history and inject the failure on the primary call's own
result specifically (the hard sub-case), then assert eventsource.Fold
still succeeds.

Granted-path compensation had its own stranding risk: after
ClaimAuthorization's save durably lands StateRunning, if the
continuation's prepare/register/cancel-handoff fails,
restoreAuthorizationClaim compensates by putting pending back and
saving StateAuthorizing — but if THAT save also fails, the earlier
StateRunning snapshot was left stranded with no owning run and no
pending authorization to retry. Added
restoreAuthorizationClaimOrSettle, which falls back to reloading the
session fresh from the store and settling it via the existing
repairRunningSession helper when the compensating save itself fails;
wired into all four call sites that previously called
restoreAuthorizationClaim directly. New test
TestMCPAuthorizationGrantedCompensationSaveFailureSettlesInsteadOfStranding
proves a claim-save-succeeds-then-compensation-save-fails sequence
settles to idle instead of stranding.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
… never joined

appendAuthorizationResolution continued past an ambiguous per-event Append
failure to avoid stranding later events, but still appended
EvAuthorizationResolved even when the PRIMARY call's own EvToolResult was the
one that failed. If that failure meant the result genuinely never committed,
Fold's resolveAuthorization hard-rejects the log (ErrReconstruct) instead of
the intended soft "still open" outcome (ErrPrivateStateRequired) the design
already has for genuine ambiguity. Skip the resolved append whenever the
primary result's own append fails, folding both the post-write-ambiguous and
genuinely-uncommitted cases into the same safe behavior, since a caller of
port.EventLog.Append cannot tell them apart.

Also extends the ToolHive import boundary allowlist with the two RFC 9728
protected-resource-discovery files (#1055) that legitimately import
oauthproto from a separate, unrelated ToolHive integration than this
branch's own MCP broker leaves.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
The new authorization.required/authorization.resolved case pushed
EventToMsg's cyclomatic complexity to 21, past golangci-lint's gocyclo
threshold. Move it into the existing advisoryEventToMsg split-dispatcher
alongside the other CI-caught issue: two stale docs/architecture.md and
docs/design/IMPLEMENTATION-NOTES.md links still pointed at the
pre-renumbering 0309-confidential-toolhive-broker-client.md path instead
of the final 0312 (matlatl docs gate caught the broken links).

Co-Authored-By: Claude Sonnet 5 <[email protected]>
…ust the primary

appendAuthorizationResolution's primaryAppended gate (from the prior review
round) only checked the PRIMARY call's own result append before deciding
whether to append EvAuthorizationResolved. But eventsource.Fold's foldability
depends on every ordered result being durably recorded, not just the primary's:
a failed deferred-sibling append can leave a dangling tool_call that
SeedHistory hard-rejects, producing the exact same permanent non-foldability
this gate was built to prevent — just triggered from the other half of the
result sequence.

Widen the gate to require every result append to have returned nil
(allAppended) before appending the terminal event, folding the deferred case
into the same conservative "leave it open" behavior as the primary case. Add
pre-write (failCalls) and post-write (postWriteFailCalls) coverage for a
failed deferred result, mirroring the existing primary-result tests, per
JAORMX's review at ce8b52a.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@jhrozek
jhrozek force-pushed the recon/session-mcp-auth-stack branch from ce8b52a to 0aa4201 Compare September 8, 2026 08:31
@jhrozek

jhrozek commented Sep 8, 2026

Copy link
Copy Markdown
Contributor Author

Fixed in a0c1210a5 (now on 0aa420154 post-rebase).

appendAuthorizationResolution's gate is widened from primaryAppended to allAppended: EvAuthorizationResolved is now appended only if every result append (primary and every deferred sibling) returned nil. If any of them ambiguously failed — pre-write or post-write — the function stops before the terminal event, same as it already did for the primary-only case, leaving the lifecycle in the intended soft "still open" state (ErrPrivateStateRequired) instead of risking ErrReconstruct.

Added TestMCPAuthorizationDeferredResultAppendFailureStaysFoldable (pre-write, via failCalls) and TestMCPAuthorizationDeferredResultAmbiguousPostWriteFailureStaysFoldable (post-write, via postWriteFailCalls) mirroring the existing primary-result tests, both asserting eventsource.Fold returns ErrPrivateStateRequired rather than a hard reconstruct failure.

@JAORMX JAORMX left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved after the incremental authorization-lifecycle fixes at 0aa420154. The prior blockers are addressed; no further blocking findings from this review.

Main's RPC transport-catalog parity gate (PR #1190) doesn't know about
the 7 new HarnessService methods this branch adds. Add the 6 real RPCs
to the TypeScript catalog and bump the two pinned counts; classify
StartInteractiveRunContent as a non-RPC alternate entry point.

Co-Authored-By: Claude Sonnet 5 <[email protected]>
@jhrozek
jhrozek merged commit d6b4eb8 into main Sep 8, 2026
26 checks passed
@jhrozek
jhrozek deleted the recon/session-mcp-auth-stack branch September 8, 2026 10:08
@jhrozek jhrozek linked an issue Sep 8, 2026 that may be closed by this pull request
13 tasks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

The harness acts for a user against an external system

2 participants