Documentation
¶
Overview ¶
Package entra implements the Microsoft Entra (Azure AD) variant of the on-behalf-of (OBO) token exchange.
It performs the Entra OBO flow — the jwt-bearer grant with requested_token_use=on_behalf_of against the v2.0 token endpoint — and maps the provider's error responses onto a small typed taxonomy (see errors.go). Exchanger implements both exchange.Exchanger and exchange.TokenExchanger; wrap it in the sibling cache package to add session-partitioned token caching:
tokenURL, err := entra.TokenURL("<tenant>", "") // "" = public Entra authority
if err != nil { ... }
exchanger, err := entra.NewFromTokenURL(tokenURL, "<app-id>", "<secret>", nil)
if err != nil { ... }
var oboExchanger exchange.Exchanger = cache.New(exchanger)
The package links only the standard library and the stdlib-only pkg/auth/obo/exchange contract. It deliberately does NOT depend on the oauthproto helpers, which transitively pull in a large dependency graph (fosite, ristretto, grpc-gateway) that the proxyrunner does not otherwise need, and it stays free of client-go and controller-runtime (see the dependency guard test in pkg/auth/obo).
Index ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrInteractionRequired indicates Entra refused the silent exchange and // demands interactive user action — a conditional-access / MFA / claims // challenge (for example AADSTS50076 or AADSTS50079). v1 fails fast on this // case rather than attempting an interactive passthrough; the originating // *ExchangeError carries the raw claims challenge for a future enhancement. ErrInteractionRequired = errors.New("entra obo: interaction required (conditional access / claims challenge)") // ErrInvalidGrant indicates the subject (user) token was rejected — expired, // malformed, or not consented for this resource. It is permanent for that // token: re-running the exchange with the same assertion will fail again. ErrInvalidGrant = errors.New("entra obo: subject token rejected") // ErrInvalidClient indicates the confidential client failed to authenticate // (wrong client_id / client_secret, or the secret has expired). It is a // permanent configuration error until the operator fixes the credentials. ErrInvalidClient = errors.New("entra obo: client authentication failed") // ErrTransient indicates a retryable failure — a 5xx, 429 or 408 from the // token endpoint, an OAuth "temporarily_unavailable" error, or a // transport-level error reaching it. Callers may retry with backoff. ErrTransient = errors.New("entra obo: transient token endpoint failure") )
Sentinel errors for the OBO exchange failure classes. Callers compare with errors.Is; the concrete *ExchangeError returned by the Exchanger unwraps to the sentinel matching its Kind. They never carry token or secret material.
This layer deliberately does no logging (it would risk leaking secrets and the consumer has the request context anyway). The audit record for a fail-fast conditional-access / claims challenge is the runtime middleware's and the vMCP strategy's responsibility: on errors.Is(err, ErrInteractionRequired) they emit the audit event using the safe-to-log fields the *ExchangeError already carries — Kind, OAuthError, Description, Claims, HTTPStatus — none of which contain credential material.
Functions ¶
func TokenURL ¶
TokenURL builds and validates the Entra v2.0 on-behalf-of token endpoint for a tenant. The URL it returns is one NewFromTokenURL will accept. The operator's OBO validation calls this to derive the runtime contract's tokenUrl from the CRD's tenantId (and optional authority) rather than re-spelling Entra's authority/tenant/path structure — keeping that structure defined in one place.
authority defaults to the public Microsoft Entra host when empty; a non-empty authority must be an https URL (http only for loopback) with a host and no query or fragment. tenantID must be a directory GUID or a verified domain name. Errors are plain errors that never contain a credential.
func ValidateTokenURL ¶
ValidateTokenURL applies the checks NewFromTokenURL makes on a token URL: present, absolute, https (http only for a loopback host), with no query or fragment. Callers that build the Exchanger lazily use it to reject a bad URL when the configuration is validated rather than on the first exchange.
Types ¶
type ErrorKind ¶
type ErrorKind int
ErrorKind classifies an OBO exchange failure so callers can decide between fail-fast (interaction required), permanent-error (bad grant / client), and retry (transient) without string-matching provider diagnostics.
const ( // KindUnknown is an unclassified failure: a non-success response that did // not match any recognised OAuth error code or status class. It is treated // as permanent (it does not unwrap to ErrTransient) so callers do not retry // indefinitely on an unrecognised, likely permanent, error. KindUnknown ErrorKind = iota // KindInteractionRequired is a conditional-access / MFA / claims challenge. KindInteractionRequired // KindInvalidGrant is a rejected subject token. KindInvalidGrant // KindInvalidClient is a confidential-client authentication failure. KindInvalidClient // KindTransient is a retryable server-side or transport failure. KindTransient )
type ExchangeError ¶
type ExchangeError struct {
// Kind is the classified failure class.
Kind ErrorKind
// OAuthError is the RFC 6749 "error" code from the response body (for
// example "invalid_grant"). Empty when the failure had no parseable body
// (transport error, 5xx with a non-JSON body).
OAuthError string
// Description is the provider's "error_description" diagnostic. For Entra
// this is the human-readable "AADSTSnnnnn: ..." message. It contains no
// credential material and is safe to log.
Description string
// Claims is the raw claims challenge from an interaction-required response
// (the "claims" field Entra returns for conditional access). It is empty for
// every other Kind. It is a request for additional claims, not a credential.
Claims string
// HTTPStatus is the token endpoint's HTTP status code, or 0 when the request
// never produced a response (transport-level failure).
HTTPStatus int
}
ExchangeError is the typed error returned when an Entra OBO exchange fails. It classifies the failure (Kind) and unwraps to the matching sentinel so callers can use either errors.As (to read Kind / Claims / OAuthError) or errors.Is (against the sentinels above).
It deliberately carries only non-sensitive fields: the RFC 6749 error code, the provider's diagnostic description, the HTTP status, and — for an interaction-required challenge — the raw claims request. It never contains the user's assertion, the client secret, or any issued access token, so it is safe to log and to surface in API responses.
func (*ExchangeError) Error ¶
func (e *ExchangeError) Error() string
Error implements error. It composes only the non-sensitive fields; in particular it never includes the subject token, client secret, or issued access token.
func (*ExchangeError) Unwrap ¶
func (e *ExchangeError) Unwrap() error
Unwrap maps the Kind onto its sentinel so errors.Is works against the exported sentinels. KindUnknown intentionally unwraps to nil — an unknown failure matches none of the sentinels and is therefore treated as permanent.
type Exchanger ¶
type Exchanger struct {
// contains filtered or unexported fields
}
Exchanger performs the Microsoft Entra on-behalf-of token exchange. It implements both exchange.Exchanger (token string only) and exchange.TokenExchanger (token plus expiry, consumed by the caching layer).
For the Entra provider the audience argument of Exchange / ExchangeToken is the OAuth scope to request — typically "<resource>/.default" or an explicit delegated scope such as "api://<app-id>/Files.Read". It is sent verbatim as the request's scope parameter.
func NewFromTokenURL ¶
func NewFromTokenURL(tokenURL, clientID, clientSecret string, httpClient *http.Client) (*Exchanger, error)
NewFromTokenURL returns an Exchanger that posts the OBO exchange to a fully-formed tenant token endpoint. Callers that hold a tenant + authority pair derive the endpoint with TokenURL first; the proxy-runtime middleware receives tokenURL verbatim from the obo.MiddlewareParameters contract and must not re-derive Entra's authority/tenant URL structure. It fails loudly on missing required fields or a malformed URL rather than deferring the failure to the first exchange.
tokenURL must be an absolute https URL (http permitted only for loopback hosts, so tests can point at an httptest server), with a host and no query string or fragment. clientID and clientSecret are required (v1 supports client_secret authentication only). A nil httpClient gets a default client with a bounded timeout; an injected client is used for its transport and timeout. Either way redirects are refused (see newHTTPClient). Configuration errors are returned as plain errors, not as *ExchangeError (which classifies exchange-time failures only).
SECURITY: tokenURL is a trust boundary. The exchange POSTs the client secret and the end-user assertion in the request body to tokenURL, so the caller must supply only a trusted Entra token endpoint. This is safe because tokenURL comes from operator-controlled configuration (the obo.MiddlewareParameters contract), never from end-user input, and the unconditional redirect guard (see newHTTPClient) stops a 3xx from replaying that body to another host. This constructor intentionally does NOT allowlist hosts or enforce a path shape: TokenURL already trusts an operator-supplied authority for arbitrary hosts (sovereign clouds), and a hard allowlist would reject legitimate sovereign / B2C / CIAM endpoints (which use different hosts and token paths) while giving only false assurance.
func (*Exchanger) Exchange ¶
Exchange implements exchange.Exchanger: it returns just the backend-scoped access token, discarding the expiry the caching layer would use.
func (*Exchanger) ExchangeToken ¶
func (e *Exchanger) ExchangeToken(ctx context.Context, userToken, audience string) (exchange.Token, error)
ExchangeToken implements exchange.TokenExchanger: it performs the Entra OBO exchange and returns the backend-scoped token together with its expiry.
Failures fall into three error shapes:
- Argument validation (empty userToken or audience) returns a plain error, not an *ExchangeError — no exchange was attempted, so there is nothing to classify.
- A cancelled or timed-out context returns the wrapped context error (matches with errors.Is(err, context.Canceled / context.DeadlineExceeded)).
- An HTTP-level failure returns a typed *ExchangeError; use errors.As to read Kind / Claims, or errors.Is against the package sentinels.
No returned error ever contains the subject token, client secret, or the issued access token.