Documentation
¶
Overview ¶
Package mcpfacade composes AppTheory's Go runtime MCP OAuth facade.
The package registers the route families defined by runtime/mcproutes.ContractVersion. It serves RFC 9728 protected-resource metadata and RFC 8414 authorization-server discovery while leaving authorization and token behavior in application-owned handlers.
MCP transport routes (POST, GET, and DELETE on every MCP pattern) are registered with an authenticated posture by default: requests without a verified principal are rejected with HTTP 401 and the MCP handler never runs. Set FacadeConfig.TransportPosture to select another posture: runtime-bearer pairs with FacadeConfig.RequireBearerToken to validate an RFC 9728 bearer token in a route-level guard that runs before application middleware, and none-public is the explicit public posture.
Mounting on a closed-by-default SecureApp ¶
RegisterMCPFacade installs the facade on the legacy App surface. RegisterMCPFacadeSecure installs the same route inventory, with the same request-time behavior, on a closed-by-default SecureApp. Use the SecureApp registrar for an application that already runs its non-MCP route families on a SecureApp: mounting the facade on the legacy surface instead would drop the application's SecurePrincipalResolver, tier, and PolicyHook for every route that shares the app.
SecureApp requires every route to declare exactly one auth posture at registration, so the SecureApp registrar declares the posture each facade route has always had. The table below is the authority for each family; it is the same table on both surfaces, restated in SecureApp's vocabulary.
Route family SecureApp posture Authority MCP transport, posture iam or jwt Authenticated() the app's SecurePrincipalResolver (the gateway has already validated the caller) MCP transport, posture runtime-bearer Public() the facade's route-level RFC 9728 bearer guard, which runs before application middleware and fails closed MCP transport, posture none-public Public() none, by explicit facade contract protected-resource metadata Public() none: RFC 9728 metadata is public by design authorization-server discovery Public() none: RFC 8414 metadata is public by design /authorize and /token Public() the client-facing protocol surface itself: PKCE and the single-use code /register (RFC 7591) Public() the DCR handler, which admits public clients only upstream callback Public() the callback handler, which pins state and iss before consuming anything root authorization server Public() none: RFC 8414 metadata is public by design
"Public" here is a declaration, never an omission: a route this package does not register is not reachable at all, and the application's own resolver, tier, and PolicyHook keep governing every route the facade does not own. The PolicyHook (tier P2) runs before the posture gate on both surfaces, so a consumer that denies a request in its hook denies it on facade routes too; that is the consumer's declared authority, not a framework loophole.
Index ¶
- Constants
- type Capabilities
- type FacadeConfig
- type FrontDoorSecretReader
- type FrontDoorVerification
- type HandlerFactory
- type OriginReachability
- type RefreshSweepConfig
- type RefreshSweepOutcome
- type RefreshSweepResult
- type RefreshSweeper
- type RootDiscoveryConfig
- type Route
- type RouteInventory
- type RouteRefreshEvent
- type RouteRefreshEventClass
- type RouteRefreshEventHook
- type RouteRefreshPolicy
- type TransportPosture
- type URLMode
Constants ¶
const ( // RouteRefreshOutcomeAccessTokenOnly is retained for telemetry compatibility. // The beyond-grace access-token-only serve was removed; a beyond-grace // presentation is served by rotating the family's live head and reports // RouteRefreshOutcomeRotatedFromHead instead. RouteRefreshOutcomeAccessTokenOnly = "access_token_only" // RouteRefreshOutcomeRevokedFamily is a reuse presentation answered by // revoking the whole family through the store's transactional tombstone. RouteRefreshOutcomeRevokedFamily = "revoked_family" // RouteRefreshOutcomeRevokedWalk is retained for telemetry compatibility. A // family-less lineage is now adopted by the bounded successor walk (see // RouteRefreshReasonLegacyLineageAdopted), so no live path reports this // outcome. RouteRefreshOutcomeRevokedWalk = "revoked_walk" // RouteRefreshOutcomeRateLimited is retained for telemetry compatibility. The // per-family reuse budget no longer gates a token serve. RouteRefreshOutcomeRateLimited = "rate_limited" // RouteRefreshOutcomeBindingRejected is retained for telemetry compatibility. // A live-head refresh still validates its binding; the binding failure is a // validation rejection, and a beyond-grace presentation is served rather than // refused, so no live path reports this reuse outcome. RouteRefreshOutcomeBindingRejected = "binding_rejected" // RouteRefreshOutcomeRotatedFromHead is the reuse outcome of a stale // predecessor presentation served by rotating the family's live head. It is // additive: the client receives fresh credentials and the family is not // revoked. RouteRefreshOutcomeRotatedFromHead = "rotated_from_head" )
Reuse outcomes. They are the `Outcome` of a RouteRefreshEventReuse, and they are deliberately distinct from the client-facing response, which is the same uniform invalid_grant for every terminal outcome.
const ( RouteRefreshReasonHandleMalformed = "handle_malformed" RouteRefreshReasonClientRejected = "client_rejected" RouteRefreshReasonRecordAbsent = "record_absent" RouteRefreshReasonRecordExpired = "record_expired" RouteRefreshReasonRecordRevoked = "record_revoked" RouteRefreshReasonClientMismatch = "client_mismatch" RouteRefreshReasonResourceMismatch = "resource_mismatch" RouteRefreshReasonBindingRejected = "binding_rejected" RouteRefreshReasonLockContention = "lock_contention" RouteRefreshReasonStoreFailure = "store_failure" RouteRefreshReasonRewriteFailure = "rewrite_failure" RouteRefreshReasonFamilyRevokeFailed = "family_revoke_failed" // RouteRefreshReasonAlreadyServed is retained for telemetry compatibility. A // beyond-grace presentation reports RouteRefreshReasonStalePredecessor and is // served, so no live path emits this reason. RouteRefreshReasonAlreadyServed = "already_served" RouteRefreshReasonUpstreamRejected = "upstream_rejected" RouteRefreshReasonSuccessorBody = "successor_body" // RouteRefreshReasonAccessTokenOnly is retained for telemetry compatibility. RouteRefreshReasonAccessTokenOnly = "access_token_only" // RouteRefreshReasonRotatedReuse is retained for telemetry compatibility. It // was the reason of a beyond-grace reuse presentation that revoked the // family; the served path reports RouteRefreshReasonStalePredecessor with the // rotated_from_head outcome and never revokes on reuse. RouteRefreshReasonRotatedReuse = "rotated_reuse" // RouteRefreshReasonLegacyLineage is a family-less (pre-policy) record // presented for ordinary rotation: migration or reauthorization is required. RouteRefreshReasonLegacyLineage = "legacy_lineage_unsupported" // required family state is missing or corrupt. RouteRefreshReasonFamilyStateUnavailable = "family_state_unavailable" // RouteRefreshReasonStalePredecessor is a presentation of a rotated-away // handle beyond its grace window. Ordinary client behavior — a restart with // a stale stored copy, a second process on one login, a lost response — // produces exactly this presentation, so it is served and never treated as // theft. RouteRefreshReasonStalePredecessor = "stale_predecessor" // RouteRefreshReasonFamilyHeadAbsent is a family whose live head aged out, // leaving no member that can rotate. The handle is unusable. RouteRefreshReasonFamilyHeadAbsent = "family_head_absent" // RouteRefreshReasonLegacyLineageAdopted is a family-less (pre-policy) record // migrated in code onto a fresh generation-1 family. It is additive: the // client keeps its session and no manual data operation is needed. RouteRefreshReasonLegacyLineageAdopted = "legacy_lineage_adopted" // RouteRefreshReasonLineageVerified is a presentation resolved by the // post-timeout lineage check: the family's live head had already moved on past // the presented record, so the head was rotated for the client and the stale // material was never presented again. It is ordinary recovery, never theft. RouteRefreshReasonLineageVerified = "lineage_verified" // RouteRefreshReasonRecoveryPending is an upstream contract-terminal verdict // that is still ambiguous because a rotation attempt of the same record is // unconfirmed inside the ambiguity horizon: a lost response, a timeout, or an // informed serve-off state can all produce that verdict. The family is kept and // the client is told to retry. RouteRefreshReasonRecoveryPending = "recovery_pending" )
Failure reasons. They are the `Reason` of a validation-rejected or state failure event.
const ( RouteRefreshExpirySignalAbsent = "absent" RouteRefreshExpirySignalExpired = "expired" )
Expiry signals. The store distinguishes an aged-out handle from one that never existed; the client-facing body does not.
const ( // MinRouteRefreshHandleTTL is the shortest accepted handle lifetime. A // shorter local policy defeats the lazy-refresh client the mechanism exists // for, and is far below every upstream access-token lifetime the facade is // known to front. MinRouteRefreshHandleTTL = time.Minute // MaxRouteRefreshHandleTTL is the longest accepted handle lifetime: thirty // days, equal to the verified upstream refresh-family inactivity default. // A ceiling above it would violate the design's min-of rule (route handle // lifetime ≤ upstream refresh-token lifetime). MaxRouteRefreshHandleTTL = 30 * 24 * time.Hour // DefaultRefreshGraceWindow is the lost-response replay window a policy that // does not state one selects. It is the pinned maximum, widened from the // original thirty seconds, so a lazy client that retries a dropped rotation // response inside two minutes recovers without a second upstream call. DefaultRefreshGraceWindow = 120 * time.Second // MaxRefreshGraceWindow is the hard bound on the lossless replay carve-out. MaxRefreshGraceWindow = 120 * time.Second // MinRefreshReuseRateCeiling is the smallest accepted value of the retained // ReuseRateCeiling field. The field no longer gates a token serve; the floor // and ceiling keep every existing configuration valid and are pinned by the // policy tests. MinRefreshReuseRateCeiling = 9 // MaxRefreshReuseRateCeiling caps the retained ReuseRateCeiling field so an // existing configuration stays within the accepted range. MaxRefreshReuseRateCeiling = 120 // DefaultRefreshBudget is the upstream refresh-call budget a policy that does // not state one selects. It is the M2.1 hardened upstream HTTP deadline // (oauth's default fetch bound, shared by the discovery, token, and JWKS // fetches), so an unchanged configuration keeps exactly the deadline the // adapter already used. DefaultRefreshBudget = 10 * time.Second // MinRefreshBudget is the shortest accepted upstream refresh budget. Below it // a healthy upstream could not answer, so the facade would report transient // failures it caused itself. MinRefreshBudget = time.Second // MaxRefreshBudget is the longest accepted upstream refresh budget: the // reference broker lock TTL (oauthstore.DefaultRouteRefreshLockTTL, 15 s) less // the commit margin. The ceiling is calibrated to that reference TTL; a store // with a shorter one is not rejected at registration. If such a store's lock // expires mid-rotation, the second caller runs another upstream refresh and // RotateFamily's owner/expiry/version re-check defers its rotation to the // winner, so the outcome is an extra upstream call and a deferred loser, never // a second mint. MaxRefreshBudget = oauthstore.DefaultRouteRefreshLockTTL - refreshBudgetLockMargin )
const DefaultFrontDoorSecretTTL = 5 * time.Minute
DefaultFrontDoorSecretTTL is how long a front-door secret read from Parameter Store is reused in one execution environment when FacadeConfig leaves FrontDoorSecretTTL unset.
const MaxFrontDoorSecretTTL = time.Hour
MaxFrontDoorSecretTTL is the largest accepted FrontDoorSecretTTL. A longer cache would let a rotated-out value stay accepted for longer than the documented rotation window.
Variables ¶
This section is empty.
Functions ¶
This section is empty.
Types ¶
type Capabilities ¶
type Capabilities struct {
ResponseTypes []string
GrantTypes []string
TokenEndpointAuthMethods []string
CodeChallengeMethods []string
}
Capabilities controls the RFC 8414 capability lists advertised by the facade. Nil fields use DefaultCapabilities; non-nil fields replace a default.
func DefaultCapabilities ¶
func DefaultCapabilities() Capabilities
DefaultCapabilities returns the golden-path OAuth capabilities: code responses, authorization-code and refresh-token grants, public clients, and S256 PKCE.
type FacadeConfig ¶
type FacadeConfig struct {
// IssuerURL is the absolute HTTPS authorization-server issuer advertised by
// both metadata document families when IssuerMode is family.
IssuerURL string
// JWKSURI is the absolute HTTPS key-set URL advertised by both metadata
// document families. In route issuer mode it remains the upstream JWKS,
// because the upstream signs the access tokens the route hands to clients.
JWKSURI string
// RegistrationEndpointURL optionally overrides the RFC 8414 registration
// endpoint. When empty, issuer + /register is advertised (family mode).
RegistrationEndpointURL string
// IssuerMode selects per-route issuer/resource derivation. An empty value
// means IssuerModeFamily: one FacadeConfig.IssuerURL for the whole facade.
// IssuerModeRoute makes each route its own authorization server: the route
// URL is the issuer, the resource, and the advertised authorization server.
IssuerMode mcproutes.IssuerMode
URLMode URLMode
PublicBaseURL string
// UpstreamCallbackPath optionally overrides the stage-global upstream
// callback path. When empty, mcproutes.DefaultCallbackPath is used.
UpstreamCallbackPath string
// AllowedHostnames is required in request-host mode. Configuration entries
// normalize case, trailing dots, and default ports scheme-agnostically;
// request authorities normalize case and trailing dots too, but strip only
// the request scheme's own default port.
// The normalized request authority must exact-match an entry or metadata
// fails with HTTP 400.
AllowedHostnames []string
// Scopes must contain a non-empty scope set for every contract endpoint
// kind. Scope policy remains application-owned.
Scopes map[mcproutes.EndpointKind][]string
// Capabilities selectively overrides DefaultCapabilities.
Capabilities Capabilities
// MCPHandler serves every POST, GET, and DELETE MCP endpoint pattern.
MCPHandler apptheory.Handler
// AuthorizeHandler and TokenHandler are an all-or-none pair. AppTheory only
// mounts the derived paths; all authorization behavior remains app-owned.
AuthorizeHandler HandlerFactory
TokenHandler HandlerFactory
// RegisterHandler mounts the derived RFC 7591 dynamic-client registration
// path per kind. AppTheory only mounts the derived path; registration
// behavior remains app-owned. Absent mounts no register route.
RegisterHandler HandlerFactory
// CallbackHandler mounts the single stage-global upstream OAuth callback
// path. AppTheory only mounts the route; the callback mechanics remain
// app-owned. Absent mounts no callback route.
CallbackHandler apptheory.Handler
// RootAuthorizationServer optionally installs one static GET at the
// algebra-derived root authorization-server discovery path.
RootAuthorizationServer *RootDiscoveryConfig
// TransportPosture selects how the MCP transport routes (POST, GET, and
// DELETE on every MCP pattern) are authorized. An empty value means
// TransportPostureIAM.
//
// TransportPostureRuntimeBearer validates an RFC 9728 bearer token in the
// runtime and requires RequireBearerToken; registration fails closed without
// it. TransportPostureNonePublic registers the transport routes without
// authentication and is never a default. The posture must agree with the CDK
// construct's synthesized posture marker.
//
// The posture is evaluated by the portable tier pipeline and by SecureApp.
// TierP0 is the frozen legacy pipeline and does not evaluate route-level
// postures, so an application that explicitly selects TierP0 must supply
// RequireBearerToken or own transport authentication itself.
TransportPosture TransportPosture
// RequireBearerToken validates an RFC 9728 bearer token on every MCP
// transport route. Credential-free or invalid requests are rejected with
// HTTP 401 and the RFC 9728 WWW-Authenticate challenge that points at the
// protected-resource metadata. This holds for every tier, including TierP0.
// It is valid only with TransportPostureRuntimeBearer and is rejected under
// every other posture.
RequireBearerToken *oauth.RequireBearerTokenOptions
// OriginReachability records the direct-origin posture the CDK construct
// declared, so one application-owned constant can feed both surfaces. An
// empty value leaves the posture unrecorded; disabled and locked are
// edge-enforced and add no runtime check. Fronted requires
// FrontDoorVerification and refuses every derived route whose front-door
// header is absent or wrong.
OriginReachability OriginReachability
// FrontDoorVerification is the app-owned front-door header this runtime
// verifies on every derived route (transport and OAuth facade paths) under
// OriginReachability fronted. Registration fails closed when fronted is
// declared without it, and it is rejected under every other posture: an
// undeclared or unenforced front door would be a silent no-op.
FrontDoorVerification *FrontDoorVerification
// FrontDoorSecretReader reads FrontDoorVerification.SecretParameterName. A
// nil reader selects AWS Systems Manager Parameter Store and is created
// lazily on the first request in the execution environment. It is only
// consulted by the parameter form; the literal form never reads a parameter.
FrontDoorSecretReader FrontDoorSecretReader
// FrontDoorSecretTTL bounds how long a parameter value read from
// FrontDoorSecretReader is reused before it is read again, so a rotation
// takes effect without a redeploy. Zero selects DefaultFrontDoorSecretTTL;
// the accepted range is greater than zero and at most MaxFrontDoorSecretTTL.
// The cache also refreshes on a verification mismatch, so the first request
// carrying a rotated value is admitted. It applies to the parameter form
// only.
FrontDoorSecretTTL time.Duration
// Provider anchors the framework-owned front channel (DESIGN §8). When it is
// set, AppTheory owns /authorize, the stage-global upstream callback, and the
// /token authorization_code grant, and the rest of the front-channel field
// set below is required. A nil Provider leaves the front channel unowned: an
// application either supplies its own AuthorizeHandler/TokenHandler pair and
// CallbackHandler, or registers no OAuth surface at all. Setting any other
// front-channel field without Provider is a registration error.
Provider oauth.Provider
// Stores supplies the five facade store SPIs the front channel persists
// through (DESIGN §7): transaction, authorization code, client,
// route-refresh broker, and rate limit. All five are required when Provider
// is set. Each store owns its own TTL (DESIGN §7 TTL column), so no TTL is
// configured here.
//
// The framework's in-memory reference stores are non-durable and do not
// encrypt: they exist for deterministic tests and local development only. A
// durable store implementation MUST encrypt the Encrypted* record fields at
// rest (for example with persistence-layer encryption), because the facade
// hands the store upstream material, including the upstream-minted access
// token, exactly as the provider returned it and relies on the store to
// protect it (DESIGN §7).
Stores oauthstore.Stores
// UpstreamClientID is the facade's own OAuth client registration at the
// upstream provider (DESIGN §8.1): the upstream authorize request carries it
// and the server-side upstream code exchange presents it. It is also the
// expected azp/client_id of an upstream access token the facade validates
// (DESIGN §5.2, §6), so a token minted for another client is refused.
UpstreamClientID string
// UpstreamIssuer is the expected upstream issuer: the RFC 9207 iss value the
// upstream callback pins before consuming the transaction or exchanging the
// code (DESIGN §8.2) and the issuer the provider's Discovery call must verify
// before any published endpoint is trusted (DESIGN §5.2, §6). It must be an
// absolute HTTPS URL with no query or fragment, normalized like IssuerURL,
// and it is distinct from the client-facing issuer.
UpstreamIssuer string
// LifecycleScopes are scope values the facade adds to every upstream
// authorize request but never requires from the MCP client, for example the
// offline_access lifecycle scope that lets the upstream issue refresh
// material (FRAMEWORK_VS_POLICY row 7). Nil adds none. Values are validated
// like Scopes: trimmed, non-empty, and well-formed Unicode.
LifecycleScopes []string
// ProviderHints supplies the opaque provider hints for one authorize request
// (DESIGN §6): it receives the request context and returns the hint map, for
// example the account_id hint. A hint carries no authority — the provider
// derives authentication account context from its own validated binding, not
// from the hint (DESIGN §6). A nil function contributes no hints; an error is
// a provider-call failure in the gateway class, so it maps to the 502
// upstream_error error page and never redirects (DESIGN §8.2).
ProviderHints func(ctx *apptheory.Context) (map[string]string, error)
// RouteRefreshPolicy is the encoded static policy of the brokered route
// refresh handle. It is REQUIRED whenever Provider is set: a missing or zero
// handle TTL, grace window, or reuse rate ceiling is a registration error,
// never a silent fallback. Setting it without Provider is a registration
// error like every other front-channel field.
//
// HandleTTL is applied by the broker store; a store that reports its local
// lifetime through oauthstore.RouteRefreshBrokerHandleTTLReporter must agree
// with it. GraceWindow drives the facade's own serve classification;
// ReuseRateCeiling is retained for configuration compatibility and no refresh
// path reads it.
RouteRefreshPolicy RouteRefreshPolicy
// RouteRefreshEvents optionally receives schema-redacted route refresh
// broker telemetry. Events carry route identifiers, status transitions, and
// hashes only: never an authorization code, access token, upstream refresh
// token, route refresh handle, ID token, cookie, or provider session id. The
// hook runs synchronously on the request path and a panic is recovered.
RouteRefreshEvents RouteRefreshEventHook
// RefusalHook optionally receives one structured, redacted event for every
// 400, 401, 403, 404, and 405 the facade renders on its own routes (authorize,
// callback, token, register, and the metadata documents), so a refusal a real
// client hit is answerable from telemetry instead of being a bare status. The
// MCP transport routes report through mcp.WithRefusalHook on the MCP handler,
// so one refusal is never reported twice. Events carry the status, a reason
// slug or the client-facing error code, the method, and the path; never a
// credential, a code, a handle, or a query string. A nil hook emits nothing.
RefusalHook refusal.Hook
}
FacadeConfig configures the complete route-algebra MCP OAuth facade.
type FrontDoorSecretReader ¶ added in v7.4.0
FrontDoorSecretReader reads the current value of a front-door secret parameter.
The default is AWS Systems Manager Parameter Store. Supply a reader on FacadeConfig to serve the same well-known name from another source — the local runner's credential-free parameter store, for example — and to keep an application's unit tests free of AWS calls.
type FrontDoorVerification ¶ added in v7.3.0
type FrontDoorVerification struct {
// HeaderName is the origin request header the front door injects. 1 to 64
// characters of [A-Za-z0-9-], and never a request header that rewrites the
// origin contract.
HeaderName string
// SecretValue is the literal header value. 32 to 128 characters of
// [A-Za-z0-9._~-]. It is compared in constant time on every request.
SecretValue string
// SecretParameterName is the well-known SSM parameter that holds the header
// value, mutually exclusive with SecretValue. The parameter must be type
// String: CloudFront's origin custom headers support the plaintext
// CloudFormation "ssm" dynamic reference only. The runtime reads it with
// decryption enabled, so a SecureString would also read, but it could not
// feed the distribution header.
SecretParameterName string
}
FrontDoorVerification declares the app-owned front-door header this runtime verifies on every derived route under OriginReachabilityFronted.
The front door (for example an application-owned CloudFront distribution whose origin is the execute-api hostname) injects HeaderName: <secret> on every origin request. Supply the secret as exactly one of two forms:
- SecretValue is the v7.3 literal. Three copies of that value must come from one application-owned constant — the CDK construct prop (digest only), the distribution's origin custom-header configuration, and this config.
- SecretParameterName names a well-known, stage-qualified Parameter Store parameter. The value is read lazily in the request path (never by a goroutine or background timer), cached for FrontDoorSecretTTL, and re-read on a verification mismatch so a rotation takes effect without a redeploy. The CDK construct's frontDoorOriginHeader renders the matching CloudFormation dynamic reference for the distribution.
type HandlerFactory ¶
type HandlerFactory func(mcproutes.EndpointKind) apptheory.Handler
HandlerFactory returns an application-owned handler for one endpoint kind. Factories run during facade registration, never during request handling.
type OriginReachability ¶ added in v7.3.0
type OriginReachability string
OriginReachability is the declared direct-origin posture of the front door that fronts this facade.
The value mirrors the CDK construct's AppTheoryMcpOriginReachability decision, so one application-owned constant can feed both the construct prop and this config. Only OriginReachabilityFronted changes runtime behavior: disabled and locked are enforced at the edge, where the construct proves them, and are recorded here so the runtime can refuse a contradictory front-door declaration instead of silently ignoring it.
const ( // OriginReachabilityDisabled is the edge-enforced disabled execute-api // endpoint posture. It carries no runtime check. OriginReachabilityDisabled OriginReachability = "disabled" // OriginReachabilityLocked is the edge-enforced mutual-TLS posture. It // carries no runtime check. OriginReachabilityLocked OriginReachability = "locked" // OriginReachabilityFronted requires FrontDoorVerification: every derived // route refuses a request whose declared front-door header is absent or // wrong. OriginReachabilityFronted OriginReachability = "fronted" )
type RefreshSweepConfig ¶ added in v7.3.0
type RefreshSweepConfig struct {
// Provider makes the upstream refresh call. Required.
Provider oauth.Provider
// Stores supplies the broker store the rotation transacts through. It must
// carry the transactional family capability. Required.
Stores oauthstore.Stores
// Policy is the encoded route refresh policy: the grace window, the upstream
// refresh budget, and the handle lifetime. Required.
Policy RouteRefreshPolicy
// Events optionally receives the same schema-redacted route refresh telemetry
// the request path emits. A sweep rotation reports lock_acquired, refreshed,
// and state_failure; it never reports a reuse or revocation class.
Events RouteRefreshEventHook
// Now is the sweeper's clock for the stored deadlines it writes and for the
// event instants. Nil means wall time.
Now func() time.Time
}
RefreshSweepConfig configures a RefreshSweeper. The provider, the broker store, and the route refresh policy are exactly the ones the facade was registered with; the sweeper refuses an incomplete set rather than degrading.
type RefreshSweepOutcome ¶ added in v7.3.0
type RefreshSweepOutcome string
RefreshSweepOutcome is the closed result vocabulary of one SweepFamily call.
const ( // RefreshSweepRotated means the sweep won the lock and committed a rotation. RefreshSweepRotated RefreshSweepOutcome = "rotated" // RefreshSweepDeferred means another writer held the family, the version moved, // the upstream failed transiently, or the store could not answer. Nothing was // minted and the family is unchanged; retry on the next tick. RefreshSweepDeferred RefreshSweepOutcome = "deferred" // RefreshSweepTerminalVerdict means the upstream answered with the one // contract-terminal class (invalid_grant). The sweep released the lock and left // the family intact: the next request-path presentation verifies lineage and // renders the verdict, so no sweep-driven revocation exists. RefreshSweepTerminalVerdict RefreshSweepOutcome = "terminal_verdict" // RefreshSweepRevokedFamily means the family is already revoked; there is // nothing to rotate and nothing to do. RefreshSweepRevokedFamily RefreshSweepOutcome = "revoked_family" // RefreshSweepNoLiveHead means the family has no member whose upstream material // is current (every member is revoked, rotated away, or below the family root). RefreshSweepNoLiveHead RefreshSweepOutcome = "no_live_head" )
type RefreshSweepResult ¶ added in v7.3.0
type RefreshSweepResult struct {
Outcome RefreshSweepOutcome
FamilyHash string
PresentedHandleHash string
SuccessorHandleHash string
ChainGeneration int
// DeferredReason is the additive cause of a deferred outcome, or empty.
DeferredReason string
// UpstreamClass is the provider class the sweep observed, when one applied.
UpstreamClass string
}
RefreshSweepResult reports one SweepFamily call. It carries hashes and a generation only: never a handle, an access token, or upstream material.
type RefreshSweeper ¶ added in v7.3.0
type RefreshSweeper struct {
// contains filtered or unexported fields
}
RefreshSweeper rotates the live head of one refresh family out of band, so a scheduled trigger (a worker function, a cron entry, a batch invocation) can keep credentials fresh without reimplementing the facade's rotation. It is the exported sweep entrypoint of the rotation-recovery contract's facade rule (theorycloud_refresh_rotation_recovery.v0.1 R7): the same store SPI, the same lock, the same rotation transaction, and the same encoded policy the request path uses.
The caller decides which families are due. The sweeper does not guess: a scheduler that owns the access-token expiry knows it better than the broker record, which stores the upstream refresh material and the handle's lifetime, not the access token's.
Concurrency contract ¶
A sweep-driven rotation is an ordinary rotation competitor, never a second authority over the family:
- Exclusive lock. The sweep takes the same per-record lock the request path takes (AcquireLock with the version it read) before any upstream call. A held lock, a lock the sweep cannot take, or a version that moved since the head was read resolves to RefreshSweepDeferred: no upstream call, no state change, no family effect. The caller retries on its next tick.
- Exactly one winner. The rotation commits through the same RotateFamily transaction, which re-checks the lock owner, the expected version, the family and generation bindings, and successor uniqueness. A loser (the request path rotated first, the lock expired, the family was revoked) gets a typed transient result and never mints a successor: nothing is minted unless every write landed.
- The loser keeps working. A request-path presentation racing a committed sweep rotation finds its handle grace-marked and is served the stored successor body, or — past the grace window — has the family's new live head rotated for it. A sweep racing a committed request-path rotation defers and reads the new head on its next tick. Neither order is family-affecting.
- The sweep never revokes. Continuity maintenance is not a revocation trigger (contract R5). A contract-terminal upstream verdict observed by the sweep releases the lock and returns RefreshSweepTerminalVerdict, leaving the family intact: revocation and its receipt stay on the request path, where the client-facing verdict is rendered and lineage is verified.
- It is bounded. The upstream call carries the same encoded RefreshBudget as the request path, which stays below the broker lock TTL, so a sweep can never outlive the lock it holds.
func NewRefreshSweeper ¶ added in v7.3.0
func NewRefreshSweeper(config RefreshSweepConfig) (*RefreshSweeper, error)
NewRefreshSweeper validates a sweep configuration and returns the sweeper.
func (*RefreshSweeper) SweepFamily ¶ added in v7.3.0
func (s *RefreshSweeper) SweepFamily(ctx context.Context, familyHash string) (RefreshSweepResult, error)
SweepFamily rotates the live head of one refresh family. It never revokes and never returns an error for a transient race: a rotation it cannot win is a RefreshSweepDeferred result, which the documented concurrency contract treats as "retry on the next tick". A returned error is a programming or wiring fault (a missing family hash, an unreadable entropy source), never a family event.
type RootDiscoveryConfig ¶
type RootDiscoveryConfig struct {
IssuerURL string
AuthorizationEndpointURL string
TokenEndpointURL string
RegistrationEndpointURL string
JWKSURI string
Scopes []string
}
RootDiscoveryConfig configures the optional, unscoped authorization-server discovery document. Unlike routed discovery, every endpoint is fixed at registration time and belongs to the upstream authorization server.
type Route ¶
type Route struct {
Kind mcproutes.EndpointKind
MCPPattern string
MCPMethods []string
ProtectedResourcePattern string
DiscoveryCanonicalPattern string
DiscoverySuffixPattern string
AuthorizePattern string
TokenPattern string
RegisterPattern string
// AuthorizationRoutesAttached reports whether transport authorization is
// attached to this route family (false under the none-public posture). It
// mirrors the CDK construct's authorizationRoutesAttached inventory field,
// which is pinned by the shared facade-route-inventory fixture.
AuthorizationRoutesAttached bool
}
Route describes one endpoint-kind route family installed by the helper.
type RouteInventory ¶
type RouteInventory struct {
ContractVersion string
Routes []Route
RootAuthorizationServerPattern string
RootAuthorizationServerAttached bool
// CallbackPattern is the stage-global upstream callback path.
CallbackPattern string
// IssuerMode is the resolved per-route issuer derivation mode.
IssuerMode mcproutes.IssuerMode
}
RouteInventory is a defensive snapshot of the installed facade surface.
func RegisterMCPFacade ¶
func RegisterMCPFacade(app *apptheory.App, config FacadeConfig) (*RouteInventory, error)
RegisterMCPFacade installs the complete MCP OAuth facade described by mcproutes.ContractVersion and returns its route inventory. The helper owns composition only: authorize and token routes are absent unless the application supplies both handler factories.
The whole plan is proven installable before the app receives its first facade route, so a configuration the facade rejects, an invalid entry, or a duplicate inside the plan adds no route at all. A collision with a route the application already registered on this plain App is detected by the app's own duplicate check while the plan is mounted: the plain App surface publishes no route table, so the facade cannot pre-check that collision the way RegisterMCPFacadeSecure can on a SecureApp. See UPGRADING.md for the precise guarantee on each surface.
func RegisterMCPFacadeSecure ¶
func RegisterMCPFacadeSecure(secure *apptheory.SecureApp, config FacadeConfig) (*RouteInventory, error)
RegisterMCPFacadeSecure installs the complete MCP OAuth facade on a closed-by-default SecureApp and returns its route inventory.
It is the SecureApp counterpart to RegisterMCPFacade and produces the same route inventory and the same request-time behavior. The difference is how each route's authority is declared: on the plain App surface the facade expresses transport security with route options, while here every route must declare an explicit auth posture, so the facade declares the posture each of its routes has always had (see the authority table in the package docs and in docs/features/mcp-facade-helper.md).
The SecureApp stays closed by default: this helper adds only the facade's own routes, each with a declared posture, and it adds none of them when the plan is rejected. The whole plan is proven installable before the app receives its first facade route — every entry, and every collision with a route the app already declares — so a returned error means zero facade routes were added. A route the application never declares remains undeliverable, and the application's own SecurePrincipalResolver, tier, and PolicyHook keep governing every non-facade route on the same app.
type RouteRefreshEvent ¶
type RouteRefreshEvent struct {
Class RouteRefreshEventClass
// Reason is the failure or trigger reason vocabulary above.
Reason string
// Outcome is the reuse outcome vocabulary above.
Outcome string
// ErrorCode is the client-facing OAuth error code the request received, when
// one was rendered.
ErrorCode string
// At is the framework clock instant the event describes.
At time.Time
Issuer string
Stage string
CanonicalResource string
ClientNamespace string
EndpointKind string
PartnerID string
AgentID string
ClientIDHash string
SubjectIDHash string
HandleHash string
FamilyHash string
SuccessorHandleHash string
UpstreamRefreshTokenHash string
PreviousUpstreamRefreshTokenHash string
ScopeFingerprint string
StatusFrom string
StatusTo string
// ChainGeneration is the presented record's family generation, 0 for a
// record that predates the policy.
ChainGeneration int
// ChainDepth is retained for telemetry compatibility. The removed depth-1
// serve no longer sets it, and a beyond-grace stale predecessor is reported
// with its generation but without a depth classification.
ChainDepth int
// ExpirySignal is absent or expired for a record-state rejection.
ExpirySignal string
// UpstreamClass is the provider error class for upstream attribution.
UpstreamClass string
// RevokedRecords is how many records a family or walk revocation handled.
RevokedRecords int
}
RouteRefreshEvent is one schema-redacted route refresh broker telemetry event. Every identifier is a hash or a route-derived value; the event never carries an authorization code, an access token, an upstream refresh token, a route refresh handle, an ID token, a cookie, or provider session material.
type RouteRefreshEventClass ¶
type RouteRefreshEventClass string
RouteRefreshEventClass is the closed class vocabulary of the route refresh broker telemetry the framework emits. The set follows the families the TMS SPEC names (SPEC.md:346-352): broker issuance, local validation rejections, refresh lock acquisition, coalesced service from a stored grace response, successful refresh, reuse classification, upstream rejection attribution, and broker state failures.
const ( // RouteRefreshEventIssued is emitted when the code exchange opens a broker // record and mints the chain root handle. RouteRefreshEventIssued RouteRefreshEventClass = "issued" // RouteRefreshEventValidationRejected is emitted when a refresh presentation // is refused by a local check. The client-facing body stays the uniform // invalid_grant for record-state failures. RouteRefreshEventValidationRejected RouteRefreshEventClass = "validation_rejected" // RouteRefreshEventLockAcquired is emitted when the facade takes the route // refresh lock before a rotation. RouteRefreshEventLockAcquired RouteRefreshEventClass = "lock_acquired" // RouteRefreshEventGraceServed is emitted when a rotated-away handle inside // its grace window replays the stored successor body. RouteRefreshEventGraceServed RouteRefreshEventClass = "grace_served" // RouteRefreshEventRefreshed is emitted after a rotation is persisted and // the successor handle is handed to the client. RouteRefreshEventRefreshed RouteRefreshEventClass = "refreshed" // RouteRefreshEventReuse is emitted on EVERY out-of-grace presentation of a // rotated-away handle, whatever the classification and outcome. RouteRefreshEventReuse RouteRefreshEventClass = "reuse" // RouteRefreshEventUpstreamReauthRequired is emitted when the upstream // rejects the recorded refresh material terminally. RouteRefreshEventUpstreamReauthRequired RouteRefreshEventClass = "upstream_reauth_required" // RouteRefreshEventStateFailure is emitted when a store, lock, rewrite, or // revocation operation fails, so the retryable class is attributable. RouteRefreshEventStateFailure RouteRefreshEventClass = "state_failure" )
type RouteRefreshEventHook ¶
type RouteRefreshEventHook func(ctx context.Context, event RouteRefreshEvent)
RouteRefreshEventHook receives one route refresh broker event. It runs synchronously on the request path, after the state transition it describes has been decided. A hook must not block or retain the event for later mutation; a panic is recovered so telemetry can never fail a refresh.
type RouteRefreshPolicy ¶
type RouteRefreshPolicy struct {
HandleTTL time.Duration
GraceWindow time.Duration
ReuseRateCeiling int
RefreshBudget time.Duration
}
RouteRefreshPolicy is the encoded static policy of the brokered route refresh handle (DESIGN §8.4). It is a FacadeConfig struct field, never an environment variable, and it is required whenever the framework-owned front channel is configured: a missing or zero value is a registration error, not a silent fallback.
The policy has three knobs:
- HandleTTL is the local lifetime of a route refresh handle. It must lie in [MinRouteRefreshHandleTTL, MaxRouteRefreshHandleTTL]. The store applies it; a broker store that reports its own lifetime through oauthstore.RouteRefreshBrokerHandleTTLReporter must agree with it, so a deployment cannot declare a long ceiling while its store keeps a short one.
- GraceWindow is the lost-response replay window measured from the winning rotation. Zero selects DefaultRefreshGraceWindow. Inside the window the rotated (previous) handle replays the stored successor body, including its handle material, because that is the lost-response recovery path; the replayed body reports only the access token's remaining lifetime, so a replayed credential is always accepted for as long as the response says. At and beyond the window the presentation is served by rotating the family's live head and handing back fresh credentials: the evidence from every real client that broke is exactly this presentation (a stale stored copy presented minutes to hours after a successful rotation), so it is ordinary client behavior and never a reason to revoke the family. The window is bounded by MaxRefreshGraceWindow, and it is exclusive at its end.
- ReuseRateCeiling is retained for configuration compatibility. It previously bounded the removed beyond-grace access-token-only serve; no refresh path uses it now, because a stale predecessor presentation is served by rotating the head and the re-armed grace window bounds retries. The field and its validation stay so an existing configuration keeps registering unchanged, and the F20 limiter semantics are untouched.
- RefreshBudget is the encoded time budget of one upstream refresh call. Zero selects DefaultRefreshBudget. The facade applies it as the deadline of the provider call, so an adapter that ignores the deadline still cannot outlive it, and it is bounded above by the broker lock TTL it has to stay inside (MaxRefreshBudget). It is a configuration field, never an environment variable.
type TransportPosture ¶
type TransportPosture string
TransportPosture selects how the MCP transport routes are authorized.
const ( // TransportPostureIAM keeps the authenticated transport posture (the default). TransportPostureIAM TransportPosture = "iam" // TransportPostureJWT assumes a gateway JWT authorizer already rejected the request. TransportPostureJWT TransportPosture = "jwt" // TransportPostureRuntimeBearer validates an RFC 9728 bearer token in the runtime. TransportPostureRuntimeBearer TransportPosture = "runtime-bearer" // TransportPostureNonePublic registers the transport routes without authentication. TransportPostureNonePublic TransportPosture = "none-public" )
type URLMode ¶
type URLMode string
URLMode selects the source of absolute URLs in facade metadata documents.
const ( // URLModePublicBaseURL uses FacadeConfig.PublicBaseURL fixed at registration // time. Use it when a front door or CDN owns the public origin. URLModePublicBaseURL URLMode = "public_base_url" // URLModeRequestHost derives the origin from each normalized request. Use it // for direct API Gateway custom-domain and test deployments. URLModeRequestHost URLMode = "request_host" )