authware

package module
v2.3.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 44 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

go-authware

HTTP authentication, outbound credentials, secrets and anti-replay signing for Go services. Standard library plus go-jsonfast, nothing else.

Go Version Lint Test Security Fuzz Go Reference

Packages

Import path Purpose
github.com/ubyte-source/go-authware/v2 Inbound authentication: the Gate (none, bearer, API key, OAuth/JWT, mTLS), OAuth metadata and authorization server facade, hardening middleware, log redaction
github.com/ubyte-source/go-authware/v2/cred Outbound credentials: OAuth2 client credentials and refresh token, Azure MSI, GCP metadata, AWS SigV4, client mTLS, token cache, signing transport
github.com/ubyte-source/go-authware/v2/secret secret.Value, which never prints its content, providers (Static, Env, File) and a per-tenant MapResolver
github.com/ubyte-source/go-authware/v2/replay HMAC-SHA256 request signing with nonce replay protection (NewSigner, NewVerifier, NewMemoryStore)

Import only what you need. cred and replay hold their keys in secret.Value; replay.Signer plugs into cred.NewTransport.

Install

go get github.com/ubyte-source/go-authware/v2

API conventions

The module path is github.com/ubyte-source/go-authware/v2. These constructors validate their input and return an error: authware.New, authware.ConfigFromEnv, cred.NewClientCredentials, cred.NewRefreshToken, cred.NewAzureMSI, cred.NewGCPMetadata, cred.NewSigV4, cred.Basic, cred.NewCachedSource, cred.LoadClientTLS, secret.File, replay.NewSigner, replay.NewVerifier and replay.NewMemoryStore; authware, cred and replay each name their configuration error ErrInvalidConfig. authware.NewRedactor, cred.AsSigner and cred.NewTransport take a dependency that must not be nil and do not check it. Settings travel in typed configs (authware.Config, cred.ClientCredentialsConfig, cred.ClientTLSConfig and so on) or in options typed per constructor. Secrets are secret.Value, never plain strings.

Server-side authentication

A Gate enforces exactly one mode. The mode is always explicit, and New reports every configuration problem at once, each error wrapping ErrInvalidConfig.

gate, err := authware.New(&authware.Config{
    Mode: authware.ModeOAuth,
    OAuth: authware.OAuthConfig{
        Issuer:         "https://login.example.com/tenant",
        Audience:       "api://orders",
        RequiredScopes: []string{"orders.read"},
    },
})
if err != nil {
    log.Fatal(err)
}

mux := http.NewServeMux()
mux.Handle("/mcp", gate.Middleware(mcpHandler))
gate.Mount(mux, "/mcp") // protected resource metadata for /mcp
Mode Settings Credential
ModeNone none Admits every request
ModeBearer Bearer.Token (at least 32 bytes, no control byte, space or tab) Authorization: Bearer <token>
ModeAPIKey APIKey.Key (at least 32 bytes, no space or tab at either end, no control byte but an inner tab), APIKey.Header (default X-Api-Key) The header, or Authorization: ApiKey <key> when the header is absent and the key has no space or tab
ModeOAuth OAuth.Issuer, OAuth.Audience, plus JWKSURL or HMACSecret or neither (discovery) Authorization: Bearer <JWT>
ModeMTLS MTLS.AllowedSubjects and/or MTLS.AllowedSPKIPins Client certificate

Static credentials are compared as SHA-256 digests in constant time, and the Authorization scheme must be an ASCII token before it is compared case-insensitively. A repeated Authorization or API key header is rejected. The sections of the other modes must stay empty; Realm (default restricted) names the protection space in challenges.

Identity

Gate.Middleware stores the authenticated *Identity in the request context; Gate.Authenticate returns it directly.

id, ok := authware.IdentityFromContext(r.Context())
fmt.Println(ok, id.Subject(), id.Mode(), id.Scopes(), id.HasScope("orders.read"))
team, ok := id.ClaimString("team")
fmt.Println(team, ok)

PeerCertificate returns the client certificate in ModeMTLS; Claim, ClaimString, ClaimInt64, ClaimFloat64, ClaimBool and Claims read the token claims in ModeOAuth. An Identity is immutable. Claims are kept as an owned copy of the JWT payload and decoded on demand. The subject is a header value, with no control byte but an inner tab and no space or tab at either end, and the scopes are scope tokens. A token names its subject in the first non-empty of sub, client_id and azp; static modes report static-bearer or static-apikey, and mTLS the matched common or distinguished name; a pin reports the DN that a verified chain proves and a header carries, else sha256/ and the base64 pin. Only ModeNone leaves the subject empty.

Failures

Gate.Authenticate errors match one sentinel with errors.Is, and the middleware answers with a fixed body naming only the status:

Sentinel Status WWW-Authenticate (Bearer)
ErrMissingCredentials 401 realm only
ErrInvalidCredentials 401 error="invalid_token"
ErrTokenExpired 401 error="invalid_token"
ErrInsufficientScope 403 error="insufficient_scope", scope
ErrKeysUnavailable 503 none; Retry-After: 30

In ModeOAuth every 401 and scope 403 challenge also carries resource_metadata, pointing at the protected resource metadata of the requested path. API key challenges are ApiKey realm="...". ModeMTLS and ModeNone have no challenge scheme, so they answer 403 without WWW-Authenticate where a 401 would need one. Parameter values are quoted-string escaped.

A refused request is answered, never logged, and Gate.Authenticate returns its cause. Config.ErrorLog, when set, receives at warn level the causes no answer carries: every failed fetch of the keys or the issuer metadata, also while stale ones are served, and every facade request the upstream fails.

Authorization

Require admits requests whose identity passes every Capability. Without an identity it answers 401 (403 in ModeMTLS and ModeNone); a failed scope capability answers 403, naming the scopes in the Bearer challenge in ModeBearer and ModeOAuth, and any other failed capability a plain 403.

admin := gate.Middleware(gate.Require(
    authware.HasMode(authware.ModeOAuth),
    authware.HasAllScopes("admin"),
    authware.HasClaim("tenant", "acme"),
)(adminHandler))

Built-in capabilities: HasAnyScope, HasAllScopes, HasClaim (a JSON string, integer, number or boolean equal to a string, int64, float64 or bool, read as ClaimString, ClaimInt64, ClaimFloat64 or ClaimBool read it), HasMode, HasSubject; NewCapability(fn) wraps any predicate.

OAuth: JWT access tokens

Keys come from JWKSURL, from the jwks_uri discovered from Issuer, or from HMACSecret (at least 32 bytes, exclusive with JWKSURL). A token is accepted only when all of these hold:

  • At most 16 KiB, checked before any decoding; exactly three strict base64url segments.
  • Header and payload are UTF-8 JSON objects without duplicate members or lone surrogate escapes, nested at most 32 levels.
  • alg is one of RS256/384/512, PS256/384/512 (salt length equal to the hash), ES256/384/512 (fixed-length R||S, curve pinned), EdDSA (Ed25519), or, in HMAC mode only, HS256/384/512 under a secret at least as long as the hash (32, 48 or 64 bytes). JWKS mode refuses HS*, HMAC mode refuses the rest.
  • typ is absent, JWT, application/jwt, at+jwt or application/at+jwt, in any ASCII case; RequireAccessTokenType accepts only the at+jwt forms. crit in any form rejects the token; jku, x5u, jwk and x5c are never used.
  • iss equals Issuer byte for byte; aud, a string or an array of strings, is required and contains Audience.
  • exp is required and the token is expired once now is past exp + ClockSkew (default 30s); nbf and iat may not lie beyond now plus the skew. Time claims are JSON numbers from 0 to 2^53.
  • sub, client_id or azp holds a non-empty string: the first that does names the subject and is a header value, with no control byte but an inner tab and no space or tab at either end.
  • ID tokens are refused by their marks: at_hash, c_hash, or nonce without any of scope, scp or roles. An ID token without a mark carries the ID of its client as aud and neither scope nor scp, so an Audience other than that ID, a RequiredScopes entry or RequireAccessTokenType refuses it.
  • Every field of scope (space-separated), or else of scp (such a string or an array of them), is a scope token: visible ASCII but " and \. Every RequiredScopes entry is among them; otherwise 403 insufficient_scope.

Keys. A JWKS keeps its usable keys and skips the others: unknown kty or curve, RSA outside 2048 to 8192 bits or with an even exponent or one outside 3 to 2^31-1, EC coordinates off the curve or not full length, use other than sig, key_ops without verify, or a JWK alg that does not fit the key. A set without a usable key is an error. A token kid selects among the keys with that kid; without kid exactly one compatible key must exist. A JWK alg, when present, must equal the token alg.

Cache. Keys live for KeysCacheTTL (default 5m). The issuer metadata is cached the same way and shared by the keys and the facade, so a key refresh discovers again only once the metadata is older than KeysCacheTTL. Concurrent refreshes share one fetch, bounded by FetchTimeout (default 10s) and detached from the caller's cancellation. A token whose key is missing forces one refresh, at most every 30s, which the tokens missing a key wait for while it runs; such a token gets 503 with Retry-After when that refresh fails and while a failed fetch backs off. While fetching fails, the last good set is served until 24h after it was fetched, so a KeysCacheTTL of 24h or more serves nothing stale, and no new fetch starts for 30s after a failure; with no usable set the request gets 503 with Retry-After.

Discovery. Without JWKSURL, the gate fetches {issuer}/.well-known/openid-configuration, then {origin}/.well-known/oauth-authorization-server{path}. The document issuer must equal Issuer exactly, and jwks_uri, authorization_endpoint and token_endpoint must share the scheme, host and port of the issuer. An identity provider that publishes its keys on another origin, such as Google (https://www.googleapis.com/oauth2/v3/certs), needs JWKSURL.

Every outbound URL (issuer, JWKS, discovered endpoints) must be https, or http to localhost, 127.0.0.0/8 or ::1, and must not carry userinfo (ErrInsecureURL); CheckOutboundURL applies the same policy to a URL of your own. Outbound requests go through a copy of Config.HTTPClient that never follows redirects and whose timeout is at most FetchTimeout; key and discovery fetches treat any non-2xx status as a failure, of which they read at most 4 KiB, accept a document of at most 1 MiB (JWKS) or 256 KiB (metadata) and refuse one that is not a UTF-8 JSON object without duplicate members or lone surrogate escapes, nested at most 32 levels.

OAuth: protected resource metadata

Gate.Mount(mux, endpoints...) registers, in ModeOAuth only, GET /.well-known/oauth-protected-resource plus that path followed by each endpoint and its sub-paths; the bare path describes the first endpoint.

  • resource: Resource.Identifier, else origin plus the escaped request path after /.well-known/oauth-protected-resource, or for that bare path the first endpoint unless it is /.
  • authorization_servers: the origin when the facade is enabled (an explicit Resource.AuthorizationServers is then a configuration error), else Resource.AuthorizationServers, which defaults to Issuer when it is a secure URL; omitted when empty.
  • scopes_supported: RequiredScopes; bearer_methods_supported: ["header"]; resource_name and resource_documentation when set.

The origin is PublicURL when set (it must be scheme://host[:port] in lower case, without the default port of the scheme). Otherwise it is https for TLS connections, or the first X-Forwarded-Proto element (http or https) when TrustForwardedProto is set, else http, joined with the request Host. Documents derived from the request are sent with Cache-Control: private, max-age=300 and Vary: Host, X-Forwarded-Proto; with PublicURL they are public, max-age=300.

OAuth: authorization server facade

Setting OAuth.Facade.ClientID turns the gate into an authorization server for public clients, such as MCP clients that expect dynamic registration, relaying to the issuer as one pre-registered upstream client. Mount then also serves:

Route Behavior
GET /.well-known/oauth-authorization-server Metadata with issuer = origin, the three endpoints below, response_types_supported [code], grant_types_supported [authorization_code, refresh_token], code_challenge_methods_supported [S256], token_endpoint_auth_methods_supported [none], scopes_supported = RequiredScopes plus offline_access; cached like the resource metadata
GET /authorize Requires response_type=code, code_challenge_method=S256 with a 43-character challenge, and an https or loopback http redirect_uri without fragment, and refuses request and request_uri; anything else gets a 400 JSON error and never a redirect. Valid requests get a 302 to the upstream authorization endpoint, whose own query parameters win
POST /register UTF-8 JSON object of at most 64 KiB without duplicate members or lone surrogate escapes, nested at most 32 levels, with a non-empty redirect_uris array of https or loopback http URLs; answers 201 with the pinned client_id, token_endpoint_auth_method: none, both grant types, response_types: [code] and the redirect_uris
POST /token application/x-www-form-urlencoded body of at most 64 KiB without repeated parameters; only authorization_code (with a 43 to 128 character code_verifier) and refresh_token, and a redirect_uri, when sent, that /authorize accepts. A 2xx or 4xx upstream answer of at most 1 MiB, other than a 204 with a body, is relayed with its status, body, Content-Type and WWW-Authenticate

Parameters are rewritten in the upstream client's terms: repeated parameters are refused and only an allowlist is relayed, so audience, claims, client credentials and any other name never reach the issuer. /authorize relays response_type, redirect_uri, state, code_challenge, code_challenge_method, nonce, prompt and login_hint; /token relays grant_type, code, redirect_uri, code_verifier and refresh_token. Both add the pinned client_id, and the upstream client authenticates in the form body with ClientSecret (none for a public client). scope is qualified with ScopePrefix: bare scopes, colon names such as memory:read included, get the prefix; openid, offline_access, profile, email and scopes already under the prefix pass unchanged; URI scopes (:// or urn:) outside the prefix and any token that is not an OAuth scope-token (visible ASCII but " and \) are refused with invalid_scope. /authorize always asks for openid offline_access plus the requested scopes, or RequiredScopes when none are requested, so New refuses a facade whose RequiredScopes holds a URI scope outside ScopePrefix. The issuer answers openid with an ID token whose aud is ClientID, so New also refuses a facade whose ClientID is the Audience unless RequiredScopes or RequireAccessTokenType is set. /token qualifies scope only when present. resource is UpstreamResource, or absent when that is empty. New refuses a ScopePrefix that is not a scope token and an UpstreamResource that is not an absolute URI without a fragment.

The upstream endpoints come from the issuer metadata the keys use, refreshed after KeysCacheTTL and served for up to 24h while discovery fails; after a failed discovery with nothing to serve, or an upstream answer neither 2xx nor 4xx, a 204 with a body or oversized, the facade answers 503 temporarily_unavailable with Retry-After: 30, and a failed discovery is not retried for 30s. Every facade response other than the metadata is Cache-Control: no-store, and relayed token responses also carry Pragma: no-cache. Keep PKCE enforced at the upstream provider too: clients can obtain codes from the upstream authorization endpoint directly.

gate, err := authware.New(&authware.Config{
    Mode: authware.ModeOAuth,
    OAuth: authware.OAuthConfig{
        Issuer:    "https://login.microsoftonline.com/contoso/v2.0",
        Audience:  "api://orders",
        PublicURL: "https://mcp.example.com",
        Facade: authware.FacadeConfig{
            ClientID:     "orders-mcp",
            ClientSecret: clientSecret,
            ScopePrefix:  "api://orders",
        },
    },
})
if err != nil {
    log.Fatal(err)
}
mux := http.NewServeMux()
mux.Handle("/mcp", gate.Middleware(mcpHandler))
gate.Mount(mux, "/mcp") // metadata, /authorize, /register, /token
Server mTLS
gate, err := authware.New(&authware.Config{
    Mode: authware.ModeMTLS,
    MTLS: authware.MTLSConfig{
        AllowedSubjects: []string{"client.example", "CN=admin,O=corp"},
        AllowedSPKIPins: [][]byte{spkiSHA256},
    },
})

A subject entry containing = is a distinguished name and any other entry a common name, each written as pkix.Name.String renders it, escapes included, except that a value of a dotted type is # and the hex of its DER on every Go version: svc\;blue admits the common name svc;blue, and New refuses an entry that is never rendered, such as CN=a, O=b, cn=a,o=b or O=b,CN=a for CN=a,O=b, and one that admits no header value, such as svc\ , whose common name ends in a space. A subject that repeats its common name or serial number, of which pkix.Name keeps only the last, matches no entry. Subjects match only when the TLS layer verified the chain (ClientAuth: tls.RequireAndVerifyClientCert), since anyone can self-sign a subject. SPKI pins (SHA-256 of the SubjectPublicKeyInfo, 32 bytes each) bind the key itself and also admit unverified chains. A pin reports the DN of its certificate when a verified chain proves it, the subject repeating neither its common name nor its serial number, and the DN is a header value; else sha256/ followed by the base64 pin, never an unproven DN. A missing or refused certificate gets 403 without a challenge. The certificate is available as Identity.PeerCertificate().

nginx auth_request

Gate.CheckHandler() serves the nginx auth_request protocol: 200 with X-Auth-Subject, X-Auth-Method and, for an identity with scopes, X-Auth-Scopes, space-separated, or the challenge (403 in a mode without one, 503 with Retry-After while the keys are unavailable). Responses are Cache-Control: no-store. The subject, a header value, and the scopes, scope tokens, are sent as the identity holds them: a header line carries both unchanged. In ModeOAuth the challenge names the metadata of the path in X-Original-URI, or without that header the bare metadata path, which Mount serves for its first endpoint.

mux.Handle("/auth/check", gate.CheckHandler())
location = /auth/check {
    internal;
    proxy_pass http://gate;
    proxy_pass_request_body off;
    proxy_set_header Content-Length "";
    proxy_set_header X-Original-URI $request_uri;
}
Hardening middleware
headers := authware.SecurityHeaders(&authware.SecurityHeadersConfig{
    HSTSMaxAge:            31536000,
    HSTSIncludeSubDomains: true,
    ContentTypeNosniff:    true,
    FrameOptions:          "DENY",
    ReferrerPolicy:        "no-referrer",
})
handler := headers(apiHandler)

SecurityHeaders computes its headers once. Request body limits and the cross-origin check come from the standard library: http.MaxBytesHandler and http.CrossOriginProtection.

Log redaction
logger := slog.New(authware.NewRedactor(slog.NewTextHandler(os.Stdout, noTime)))
logger.Info("request", slog.String("authorization", "Bearer secret"), slog.String("path", "/api"))
// Output: level=INFO msg=request authorization=*** path=/api

RedactHeader(h, keys...) masks the same names in an http.Header in place and returns it.

NewRedactor masks attributes whose key matches, case-insensitively, at any depth. LogValuer values are resolved first; an http.Header, *http.Header or map[string][]string is logged as a masked copy, and an *http.Request or *http.Response as a group of its method or status, masked URL and masked header. A url.URL, *url.URL or *url.Userinfo logs its password as URL.Redacted writes it, and a URL query or fragment or url.Values logs as *** the value of every parameter named in the keys or carrying a credential: access_token, refresh_token, id_token, code, code_verifier, client_secret, client_assertion, password and api_key, in any case. In a logged header, the URLs of Location, Content-Location and Referer are masked the same way, and a value that is not a URL logs as ***. Without keys, NewRedactor and RedactHeader use SensitiveHeaders(): Authorization, Proxy-Authorization, Cookie, Set-Cookie, X-Api-Key and X-Auth-Token. A custom APIKey.Header is not in that list; pass it to NewRedactor and RedactHeader.

Environment configuration

ConfigFromEnv(prefix string) (*Config, error) reads the variables below, each name preceded by prefix ("" reads them as listed, "MCP_INBOUND_" reads MCP_INBOUND_AUTH_MODE and so on), and reports every malformed one, by name and never by value, in one error wrapping ErrInvalidConfig. Lists are comma-separated, except subjects, which are separated by semicolons because distinguished names hold commas. A backslash keeps the byte after it, and itself, in the element, as the escapes of a rendered subject need; an empty element or one ending in a lone backslash is refused. Pins are base64 SHA-256 digests and durations use time.ParseDuration. .env.example documents each one.

AUTH_MODE  AUTH_REALM  AUTH_BEARER_TOKEN  AUTH_APIKEY  AUTH_APIKEY_HEADER
AUTH_OAUTH_ISSUER  AUTH_OAUTH_AUDIENCE  AUTH_OAUTH_JWKS_URL  AUTH_OAUTH_HMAC_SECRET
AUTH_OAUTH_REQUIRED_SCOPES  AUTH_OAUTH_REQUIRE_AT_JWT  AUTH_OAUTH_CLOCK_SKEW
AUTH_OAUTH_KEYS_CACHE_TTL  AUTH_OAUTH_FETCH_TIMEOUT  AUTH_OAUTH_PUBLIC_URL
AUTH_OAUTH_TRUST_FORWARDED_PROTO  AUTH_OAUTH_RESOURCE  AUTH_OAUTH_RESOURCE_NAME
AUTH_OAUTH_RESOURCE_DOCUMENTATION  AUTH_OAUTH_AUTHORIZATION_SERVERS
AUTH_OAUTH_FACADE_CLIENT_ID  AUTH_OAUTH_FACADE_CLIENT_SECRET
AUTH_OAUTH_FACADE_SCOPE_PREFIX  AUTH_OAUTH_FACADE_UPSTREAM_RESOURCE
AUTH_MTLS_ALLOWED_SUBJECTS  AUTH_MTLS_SPKI_PINS
cfg, err := authware.ConfigFromEnv("EXAMPLE_")
if err != nil {
    log.Fatal(err)
}
gate, err := authware.New(cfg)

Config.Validate reports, without building a Gate, every problem New would refuse the configuration for, so a service can join them with its own configuration errors at boot. EnvNames(prefix) lists the variables ConfigFromEnv(prefix) reads, so a service can tell a misspelled name under its own prefix from these and warn about it.

Outbound credentials: cred

import "github.com/ubyte-source/go-authware/v2/cred"
Symbol Role
Token, Token.Apply, Token.Sign, Token.Validate Outbound credential written to a request header (Authorization: Bearer by default, the value alone when Bare is set); a *Token is a Signer of itself; Validate refuses a nil token, a header or scheme that is not a token, a scheme on a Bare token and a value that is empty or not a clean header value
Basic(user, password) (*Token, error) HTTP Basic credentials as a Token; user must be a clean header value without a colon
TokenSource, TokenSourceFunc Produces tokens; safe for concurrent use
Signer, SignerFunc, AsSigner Signs a request in place; AsSigner adapts a TokenSource
NewTransport(base, signer) Signs a clone of every request, with a copy of a *Token signer taken when the transport is built; it sends no request that follows a redirect, and the client that follows one gets ErrRedirect
NewCachedSource(src, opts...) (*CachedSource, error) Memoizes tokens until WithSkew (default 30s, at most half the lifetime) before expiry, sharing its own copy of each with the header value rendered once; a token already expired when it arrives counts as a failed refresh; WithTimeout bounds each refresh and WithErrorLog receives every failed one
NewClientCredentials(&ClientCredentialsConfig{...}) OAuth2 client_credentials grant: the token endpoint ClientConfig plus Audience
NewRefreshToken(&ClientConfig{...}, store) OAuth2 refresh_token grant; rotated tokens saved through a RefreshTokenStore (NewMemoryRefreshStore)
NewAzureMSI Azure managed identity
NewGCPMetadata GCE metadata access tokens, or ID tokens for an audience, below BaseURL
NewSigV4(&SigV4Config{...}) AWS Signature Version 4 Signer
LoadClientTLS(&ClientTLSConfig{...}) Client TLS config for mutual TLS; a positive Interval reloads the key pair, and ErrorLog receives every failed reload

Every config above has a Validate method that reports, joined, what its constructor would refuse, a nil store or source aside.

src, err := cred.NewClientCredentials(&cred.ClientCredentialsConfig{
    ClientConfig: cred.ClientConfig{
        TokenURL:     idp.URL + "/oauth2/token",
        ClientID:     "orders-sync",
        ClientSecret: clientSecret,
        Scopes:       []string{"orders.read"},
    },
})
if err != nil {
    log.Fatal(err)
}
cached, err := cred.NewCachedSource(src)
if err != nil {
    log.Fatal(err)
}
client := &http.Client{Transport: cred.NewTransport(nil, cred.AsSigner(cached))}

An Azure service principal is a client credentials grant on its tenant's v2.0 endpoint, loginHost being https://login.microsoftonline.com, with the secret in the form and the scope <resource>/.default:

src, err := cred.NewClientCredentials(&cred.ClientCredentialsConfig{
    ClientConfig: cred.ClientConfig{
        HTTPClient:   client,
        TokenURL:     loginHost + "/" + url.PathEscape(tenantID) + "/oauth2/v2.0/token",
        ClientID:     "orders-sync",
        ClientSecret: clientSecret,
        Scopes:       []string{resource + "/.default"},
        AuthStyle:    cred.AuthStyleParams,
    },
})
  • The New* constructors validate their configuration once and report every problem at once: bad settings, scopes that are not scope tokens or repeat one and negative timeouts included, wrap ErrInvalidConfig; an insecure token or metadata URL also wraps ErrInsecureTokenURL. NewSigV4 requires the access key, region and service to be header tokens and a session token to be a clean header value, and refuses UnsignedPayload unless Service is one of S3's signing names (s3, s3-object-lambda, s3-outposts, s3express); NewGCPMetadata requires scope tokens without a comma and refuses Scopes together with Audience. NewCachedSource and NewRefreshToken refuse a nil source or store with an error wrapping ErrInvalidConfig.
  • Token endpoints must be https, or http to a loopback host, and are reached through a copy of HTTPClient that refuses redirects. Cloud metadata endpoints may also be plain http on a link-local address or metadata.google.internal. The Timeout of each source config bounds every exchange (default 10s).
  • Every error that stops AsSigner or NewTransport from attaching a credential wraps ErrCredential, and the request that follows a redirect, which NewTransport refuses to send, fails with ErrRedirect. An error answer of a token endpoint or a metadata service is an *OAuth2Error whatever its size, read from its first 4 KiB; Transient() reports 5xx, 429, temporarily_unavailable and slow_down. Success answers over 1 MiB or malformed, and network tokens that are not clean header credentials, wrap ErrInvalidTokenResponse.
  • Concurrent CachedSource refreshes share one call, detached from the caller's cancellation and bounded by WithTimeout (default 10s, also for zero). A failed refresh goes to the WithErrorLog logger at warn level, and no other refresh starts for 30s: meanwhile a cached token that has not expired is still served, and without one Token fails at once with an error wrapping that failure.
  • With AsSigner over a CachedSource, a 401 answer invalidates the token it carried, at most once every 30s, so an upstream that rejects every token costs one token fetch per pause. A request whose body can be replayed is then retried once when the source yields another token, after the 401 body is drained (at most 4 KiB) so the connection is reused; otherwise the 401 is returned.
  • NewRefreshToken never runs two exchanges at once, and a rotated refresh token is saved before the access token is returned. When Save fails, the exchange returns no token and an error wrapping ErrRotationNotSaved and the store error; the rotated token stays in memory and the next exchange saves it again before presenting it. While Load returns the zero Value, each exchange fails with ErrNoRefreshToken and reads the store again.

AWS SigV4, verified against the AWS test suite vectors. The signature covers the hash of a body of at most 1 MiB unless UnsignedPayload is set, which only an S3 Service accepts. Before it changes the request, Sign refuses one without a host with ErrMissingHost, and one whose host net/http would not send as it is with ErrInvalidHost: a host with a byte outside ASCII, which net/http converts to punycode, or with another byte its Host header check refuses. A body it hashes that fails to read or close fails with an error wrapping ErrInvalidBody; the refusal of a body over 1 MiB wraps ErrBodyTooLarge too.

signer, err := cred.NewSigV4(&cred.SigV4Config{
    AccessKey: accessKeyID,
    SecretKey: secretKey,
    Region:    "us-east-1",
    Service:   "execute-api",
})
if err != nil {
    log.Fatal(err)
}
client := &http.Client{Transport: cred.NewTransport(nil, signer)}

Secrets: secret

import "github.com/ubyte-source/go-authware/v2/secret"

A non-zero secret.Value renders as *** through fmt, log/slog, JSON and text encoders when used directly or in an exported field, and the zero Value as nothing; fmt prints its type for %T, and a pointer address, never the secret, for %p, for %w and inside an unexported field. Reveal() is the only way to read it and Equal compares in constant time (Values are not comparable with ==).

p := secret.Static(map[string]string{"db_password": "p4ss"})
v, err := p.Secret(ctx, "db_password")
  • secret.Static(map): an in-memory copy.
  • secret.Env(prefix): key K reads strings.ToUpper(prefix + K).
  • secret.File(path): a flat JSON object of string members in a regular file, read once. It fails with an error wrapping ErrInvalidFile on a path that is not a regular file, a file that cannot be opened, read or closed (whose error it wraps too), over 1 MiB, truncated, with trailing data or with a duplicate key.
  • secret.MapResolver(m, fallback): one provider per tenant.

A missing key, or one whose value is empty, wraps ErrNotFound. Every provider and resolver is safe for concurrent use, and Resolver.For never returns nil. Vault or cloud secret managers are not bundled: implement secret.Provider in your own binary.

r := secret.MapResolver(map[string]secret.Provider{
    "alpha": secret.Static(alphaSecrets),
    "beta":  secret.Env("BETA_"),
}, secret.Static(defaults))
tenantID := "alpha"
v, err := r.For(tenantID).Secret(ctx, name)

Anti-replay signing: replay

import "github.com/ubyte-source/go-authware/v2/replay"

Three headers carry the envelope: X-Auth-Timestamp (Unix seconds), X-Auth-Nonce (16 random bytes, hex) and X-Auth-Signature (hex HMAC-SHA256). The signed input joins six lines: method, host with ASCII letters lowercased and without an IPv6 zone (net/http sends a zone over HTTP/2 and cuts it from its last % over HTTP/1.1), request URI (escaped path and raw query), hex SHA-256 of the body, timestamp and nonce. Sign the host and URI the verifier receives: a proxy that rewrites either breaks verification.

const capacity, window = 8192, 5 * time.Minute
key := secret.New("an example key of at least 32 bytes")

store, err := replay.NewMemoryStore(capacity)
if err != nil {
    log.Fatal(err)
}
verifier, err := replay.NewVerifier(key, store, replay.WithWindow(window))
if err != nil {
    log.Fatal(err)
}
mux.Handle("/api/", verifier.Middleware(apiHandler))

signer, err := replay.NewSigner(key)
if err != nil {
    log.Fatal(err)
}
client := &http.Client{Transport: cred.NewTransport(nil, signer)}
  • NewSigner draws each nonce from crypto/rand and stamps the time of time.Now; NewVerifier takes WithWindow (whole seconds from 1s to 1h, default 5m) and reads the same clock.
  • NewSigner, NewVerifier and NewMemoryStore refuse a short key, a window out of range, a nil store or a capacity below 1 with an error wrapping ErrInvalidConfig.
  • Signer.Sign refuses, before it changes the request, a host net/http would not send as it is, with a byte outside ASCII or another its Host header check refuses, with ErrInvalidHost, as no signature over it could verify.
  • Verify requires each header exactly once in canonical form, checks the timestamp window, accepts a body of at most 1 MiB (and restores it), compares the MAC in constant time and only then records the nonce, checking the window again once the store finds the nonce fresh. Request failures wrap ErrRejected.
  • Verifier.Middleware serves the next handler a bodiless request itself, and a copy of a request with a body carrying the verified body, and changes no field of the caller's request. It answers rejected requests 401 unauthorized with a WWW-Authenticate challenge naming X-Auth-Signature, and 503 service unavailable with Retry-After: 1 when the store fails; call Verify for the cause.
  • NewMemoryStore(capacity) is an in-process store ordered by expiry that reads time from time.Now; full of live nonces it fails closed with ErrStoreFull, so size it above peak signed requests per second times twice the window plus one second, the longest a nonce stays live. A fleet of verifiers needs a shared NonceStore.

Benchmarks

Medians of six samples of go test -run '^$' -bench . -benchmem -count=6 ./... with Go 1.27.3 on linux/amd64, an Intel Xeon Gold 6442Y pinned to 11 cores with GOMAXPROCS 11 on a shared host. Tokens carry "typ":"JWT", and cached tokens expire.

Package Benchmark Time [ns/op] Allocated [B/op] Allocations [allocs/op]
root StaticAuthenticator shared token (43 bytes) 154 0 0
root StaticAuthenticator shared key (64 bytes) 147 0 0
root MTLSAuthenticator common name 40 80 1
root MTLSAuthenticator subject DN 421 304 9
root MTLSAuthenticator SPKI pin 132 80 1
root OAuthAuthenticatorValidateToken RS256 31163 1633 12
root OAuthAuthenticatorValidateToken RS384 30998 1633 12
root OAuthAuthenticatorValidateToken RS512 31418 1632 12
root OAuthAuthenticatorValidateToken PS256 32014 1584 16
root OAuthAuthenticatorValidateToken PS384 32842 1713 16
root OAuthAuthenticatorValidateToken PS512 32844 1745 16
root OAuthAuthenticatorValidateToken ES256 75848 816 12
root OAuthAuthenticatorValidateToken ES384 582750 1080 20
root OAuthAuthenticatorValidateToken ES512 1536340 1496 20
root OAuthAuthenticatorValidateToken EdDSA 49394 256 3
root OAuthAuthenticatorValidateToken HS256 1730 256 3
root OAuthAuthenticatorValidateToken HS384 2226 256 3
root OAuthAuthenticatorValidateToken HS512 2148 256 3
root GateAuthenticate static token 141 0 0
root GateAuthenticate OAuth token 1808 224 3
root GateAuthenticate malformed token 322 0 0
root GateMiddleware accept 1967 592 5
root GateMiddleware deny 900 288 3
root GateMiddleware static deny 254 48 1
root GateCheckHandler bearer 250 64 1
root GateCheckHandler OAuth 2344 336 5
root GateCheckHandler bearer deny 332 112 2
root GateCheckHandler OAuth deny 1103 352 4
root GateRequire any scope 26 0 0
root GateRequire all scopes 20 0 0
root GateRequire deny 88 48 1
root GateRequire no identity 388 224 3
root KeySourceKey known kid 44 0 0
root KeySourceKey unknown kid 92 0 0
root KeySourceKeyParallel unknown kid 19 0 0
root KeySourceGet (parallel) 3.6 0 0
root LookupAlgorithm 11 0 0
root Identity Subject 1.9 0 0
root Identity Mode 1.8 0 0
root Identity Scopes (one scope) 24 16 1
root Identity HasScope 2.9 0 0
root Identity PeerCertificate 1.9 0 0
root Identity Claim (20-byte value) 136 16 1
root Identity ClaimString (20-byte value) 105 0 0
root Identity ClaimInt64 44 0 0
root Identity ClaimFloat64 123 0 0
root Identity ClaimBool 108 0 0
root Identity Claims (four claims) 484 360 4
root HasClaim string 114 0 0
root HasClaim int64 49 0 0
root FacadeEndpoints 71 0 0
root SecurityHeaders 72 48 1
root NewRedactor (log record) 761 0 0
root RedactHeader (default names) 103 0 0
cred CachedSourceToken (hit, expiring token) 7.3 0 0
cred TokenApply (1.5 KiB token) 685 1808 2
cred AsSigner (cached token) 24 16 1
cred NewTransport plain (1.5 KiB token) 384 1024 6
cred NewTransport renewing (1.5 KiB expiring token) 400 1024 6
cred SigV4Sign 650 728 13
cred SigV4SignBody (4 KiB s3 PUT, STS) 4118 1934 18
cred WriteLowerName/writeLowerName (4 names) 156 128 2
cred WriteLowerName/strings.ToLower (4 names) 279 144 5
cred AppendQueryComponent/appendQueryComponent 122 0 0
cred AppendQueryComponent/url (QueryUnescape+QueryEscape) 290 128 3
cred PlainSegments/plainSegments (Lambda invoke path) 25 0 0
cred PlainSegments/strings.Contains (Lambda invoke path) 49 0 0
cred HexString/hexString (SHA-256 sum) 56 64 1
cred HexString/hex.EncodeToString (SHA-256 sum) 74 128 2
cred JoinLines/joinLines (IAM canonical request) 96 256 1
cred JoinLines/strings.Join (IAM canonical request) 185 512 2
jsonobj Iterate 244 0 0
syntax AppendSegment 176 0 0
keyedmac MACSum (43-byte message) 174 0 0
replay SignerSign no body 1032 160 2
replay SignerSign 4 KiB body 3813 208 4
replay SignerSignParallel 208 160 2
replay VerifierVerify no body 692 0 0
replay VerifierVerify 4 KiB body 4248 4934 3
replay VerifierVerifyReplayedParallel 138 0 0
replay VerifierMiddleware no body 683 0 0
replay VerifierMiddleware no body parallel 140 0 0
replay MemoryStoreSeen 346 48 1
replay MemoryStoreSeenFreshParallel 302 48 1
replay MemoryStoreSeenReplayedParallel 77 0 0
replay AppendRequestURI appendRequestURI 18 0 0
replay AppendRequestURI URL.RequestURI 47 16 1
replay AppendLower appendLower 16 0 0
replay AppendLower strings.ToLower 62 16 1
replay ExpiryHeap expiryHeap (1024 entries) 120193 0 0
replay ExpiryHeap container/heap (1024 entries) 165760 0 0
secret Value Reveal (1 KiB secret) 1.8 0 0
secret Value Equal (1 KiB secret) 644 0 0

KeySourceGet and KeySourceKeyParallel call from 32 goroutines at once and divide the wall time among them; where they land on the cores moves each sample, so their rows give the lowest and the highest of the six.

Project layout

go-authware/
├── doc.go, doc_test.go        # package documentation, shared test fixtures
├── *.go ↔ *_test.go           # Gate, modes, JWT, discovery, facade, hardening
├── internal/
│   ├── flight/                # detached single-flight
│   ├── jsonobj/               # strict JSON objects through go-jsonfast
│   ├── keyedmac/              # pooled HMAC states of one key
│   ├── netguard/              # outbound URL policy, no-redirect client, bounded bodies and digests
│   ├── oauthwire/             # OAuth token requests, responses, errors and parameter names
│   ├── problems/              # configuration problems joined under one sentinel, scope tokens and lists
│   ├── reply/                 # plain-text 401, 403 and 503 answers
│   ├── retry/                 # the 30s backoff after a failed fetch
│   └── syntax/                # URI, header, scope and compact JWS rules
├── cred/                      # outbound credentials
├── secret/                    # secret values and providers
├── replay/                    # anti-replay signing
└── .github/                   # CI workflows, CodeQL config, Dependabot

Every code file foo.go has one foo_test.go holding all of its tests, benchmarks, fuzz targets and examples; doc.go has none, and doc_test.go holds only shared fixtures.

Development

make ci          # modcheck, vet, lint, vuln, deadcode, test, race, bench-smoke, cover
make final       # fmtcheck, ci, nilaway, race-repeat, fuzz-final, testtime, treecheck, on an idle machine
make bench       # every benchmark with allocations
make fuzz        # every fuzz target (or FUZZ_TARGETS=pkg:Target), FUZZTIME each (default 30s)
make fuzz-list   # every fuzz target as the JSON array of the fuzz workflow
make help        # every target

See CONTRIBUTING.md for the conventions and SECURITY.md for the security policy.

Security

The threat model, the defenses the code enforces, its limits and the verification gates are in SECURITY.md. Report vulnerabilities through GitHub's private reporting flow described there.

Dependencies

github.com/ubyte-source/go-jsonfast v0.4.1

No golang.org/x/oauth2, no cloud SDKs: every protocol is implemented against the standard library, with JSON through go-jsonfast.

Versioning

We use SemVer. Releases are tracked in the repository tags.

Authors

See also the list of contributors.

License

MIT, see LICENSE.

Support

If go-authware is useful for your services, consider supporting the work:

Buy Me A Coffee

Documentation

Overview

Package authware authenticates HTTP requests for Go servers. A Gate built by New from a Config, or from the environment through ConfigFromEnv, enforces exactly one explicit Mode: ModeNone admits everyone, ModeBearer and ModeAPIKey compare a shared secret, ModeOAuth verifies JWT access tokens from an issuer, and ModeMTLS checks the client certificate. The Gate stores the caller's Identity in the request context, guards handlers with Capability checks and serves the OAuth metadata and authorization server facade, while SecurityHeaders and NewRedactor harden handlers and keep credentials out of logs. Only New builds a usable Gate. A Gate and an Identity are safe for concurrent use, and a zero Identity, like a nil one, has no subject, mode, scope, certificate or claim. The zero value of each config struct holds no setting, and its methods only read it, so it is safe for concurrent use while nothing modifies it; New copies its Config, using as it is only the logger it names, and a copy of the client that follows no redirect and bounds its timeout. Arguments of pointer, interface and function types, handlers and contexts included, must not be nil, in the functions the package returns too, unless a godoc says what nil means.

Index

Examples

Constants

This section is empty.

Variables

View Source
var (
	// ErrInvalidConfig reports an invalid configuration; New joins one per
	// problem.
	ErrInvalidConfig = errors.New(errPrefix + "invalid config")
	// ErrMissingCredentials reports a request that carries no credentials.
	ErrMissingCredentials = errors.New(errPrefix + "missing credentials")
	// ErrInvalidCredentials reports credentials that fail verification.
	ErrInvalidCredentials = errors.New(errPrefix + "invalid credentials")
	// ErrTokenExpired reports a token past its expiry.
	ErrTokenExpired = errors.New(errPrefix + "token expired")
	// ErrInsufficientScope reports an identity lacking a required scope.
	ErrInsufficientScope = errors.New(errPrefix + "insufficient scope")
	// ErrKeysUnavailable reports that verification keys cannot be obtained.
	ErrKeysUnavailable = errors.New(errPrefix + "verification keys unavailable")
	// ErrInsecureURL reports a URL refused by the outbound URL policy of
	// CheckOutboundURL, which New and every fetch of a Gate apply.
	ErrInsecureURL = errors.New("insecure URL")
)

Functions

func CheckOutboundURL

func CheckOutboundURL(raw string) (*url.URL, error)

CheckOutboundURL parses raw and returns it when it is an absolute https URL, or an http URL to a loopback host, with a host and no userinfo; the error wraps ErrInsecureURL and never echoes raw, which may hold credentials.

func EnvNames

func EnvNames(prefix string) []string

EnvNames returns the name of the variable of every Config field but HTTPClient and ErrorLog, each preceded by prefix.

func NewRedactor

func NewRedactor(inner slog.Handler, keys ...string) slog.Handler

NewRedactor wraps inner, not nil, so attributes, headers and URL parameters named by keys, or SensitiveHeaders, and credential parameters of URL queries, fragments and URL-valued headers log as "***" at any depth, passwords as URL.Redacted does.

Example
noTime := &slog.HandlerOptions{ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
	if a.Key == slog.TimeKey {
		return slog.Attr{}
	}
	return a
}}
logger := slog.New(NewRedactor(slog.NewTextHandler(os.Stdout, noTime)))
logger.Info("request", slog.String("authorization", "Bearer secret"), slog.String("path", "/api"))
Output:
level=INFO msg=request authorization=*** path=/api

func RedactHeader

func RedactHeader(h http.Header, keys ...string) http.Header

RedactHeader masks in place the values of the headers named by keys, or by SensitiveHeaders when keys is empty, and returns h.

Example
h := http.Header{headerAuthorization: {"Bearer secret"}, "Accept": {"*/*"}}
fmt.Println(RedactHeader(h))
Output:
map[Accept:[*/*] Authorization:[***]]

func SecurityHeaders

func SecurityHeaders(cfg *SecurityHeadersConfig) func(http.Handler) http.Handler

SecurityHeaders writes the response headers selected by cfg, computed once; a nil cfg writes nothing.

Example
apiHandler := http.NotFoundHandler()
headers := SecurityHeaders(&SecurityHeadersConfig{
	HSTSMaxAge:            31536000,
	HSTSIncludeSubDomains: true,
	ContentTypeNosniff:    true,
	FrameOptions:          "DENY",
	ReferrerPolicy:        "no-referrer",
})
handler := headers(apiHandler)
w := httptest.NewRecorder()
handler.ServeHTTP(w, httptest.NewRequestWithContext(context.Background(), http.MethodGet, pathRoot, http.NoBody))
fmt.Println(w.Header().Get("Strict-Transport-Security"), w.Header().Get(headerFrameOptions))
Output:
max-age=31536000; includeSubDomains DENY

func SensitiveHeaders

func SensitiveHeaders() []string

SensitiveHeaders returns the default redaction set, a fresh slice per call. It names the default API key header X-Api-Key only: a Gate reading the key from another header needs that name added.

func WithIdentity

func WithIdentity(ctx context.Context, id *Identity) context.Context

WithIdentity returns a copy of ctx carrying id.

Types

type APIKeyConfig

type APIKeyConfig struct {
	// Key (AUTH_APIKEY) is the shared API key: a header value of at least 32
	// bytes.
	Key secret.Value
	// Header (AUTH_APIKEY_HEADER) carries the key; default X-Api-Key. Without
	// it, the key of an Authorization: ApiKey header is read.
	Header string
}

APIKeyConfig configures ModeAPIKey.

type BearerConfig

type BearerConfig struct {
	// Token (AUTH_BEARER_TOKEN) is the shared bearer token: at least 32 bytes of
	// a header value without space or tab.
	Token secret.Value
}

BearerConfig configures ModeBearer.

type Capability

type Capability struct {
	// contains filtered or unexported fields
}

Capability is an admission check over an authenticated Identity. The zero Capability denies every identity.

func HasAllScopes

func HasAllScopes(scopes ...string) Capability

HasAllScopes requires every scope; with none it admits any identity.

func HasAnyScope

func HasAnyScope(scopes ...string) Capability

HasAnyScope requires at least one of scopes; with none it always denies.

func HasClaim

func HasClaim[T string | int64 | float64 | bool](name string, value T) Capability

HasClaim requires the named claim to equal value as a JSON value of T's kind: a string, an integer with no fraction or exponent within int64's range, a number whose nearest float64 is finite, or a boolean.

func HasMode

func HasMode(m Mode) Capability

HasMode requires the identity to come from mode m.

func HasSubject

func HasSubject(subject string) Capability

HasSubject requires the identity's subject to equal subject.

func NewCapability

func NewCapability(fn func(*Identity) bool) Capability

NewCapability wraps fn as a Capability; a nil fn denies every identity.

func (Capability) Allow

func (c Capability) Allow(id *Identity) bool

Allow reports whether id satisfies the capability; a nil id never does.

type Config

type Config struct {
	// HTTPClient is the base of every outbound fetch; New uses a guarded copy.
	HTTPClient *http.Client
	// ErrorLog receives, at warn level, the cause of every failed fetch of the
	// keys or the issuer metadata and of every facade request the upstream fails,
	// and at debug level of a token relay canceled with its request; nil logs nothing.
	ErrorLog *slog.Logger
	// Mode (AUTH_MODE) is required; there is no inference.
	Mode Mode
	// Realm (AUTH_REALM) names the protection space in challenges; default
	// "restricted".
	Realm string
	// Bearer configures ModeBearer.
	Bearer BearerConfig
	// APIKey configures ModeAPIKey.
	APIKey APIKeyConfig
	// OAuth configures ModeOAuth.
	OAuth OAuthConfig
	// MTLS configures ModeMTLS.
	MTLS MTLSConfig
}

Config selects the mode and carries its settings; the sections of the other modes must stay empty.

func ConfigFromEnv

func ConfigFromEnv(prefix string) (*Config, error)

ConfigFromEnv reads every Config field but HTTPClient and ErrorLog from its variable, preceded by prefix; in a list, a backslash keeps the next byte in the element. ErrInvalidConfig names each malformed variable, never its value.

Example

ExampleConfigFromEnv reads the EXAMPLE_AUTH_* variables; with no mode set, New refuses the configuration instead of admitting every request.

cfg, err := ConfigFromEnv("EXAMPLE_")
if err != nil {
	log.Fatal(err)
}
gate, err := New(cfg)
fmt.Println(gate == nil, errors.Is(err, ErrInvalidConfig))
Output:
true true

func (*Config) Validate

func (c *Config) Validate() error

Validate reports every configuration problem of c, a nil c included, joined, each wrapping ErrInvalidConfig; c itself is not modified.

type FacadeConfig

type FacadeConfig struct {
	// ClientID (AUTH_OAUTH_FACADE_CLIENT_ID) is the client registered upstream
	// on behalf of every client of the facade; when it is also the Audience,
	// RequiredScopes or RequireAccessTokenType must be set.
	ClientID string
	// ClientSecret (AUTH_OAUTH_FACADE_CLIENT_SECRET) authenticates ClientID
	// upstream; empty means a public client.
	ClientSecret secret.Value
	// ScopePrefix (AUTH_OAUTH_FACADE_SCOPE_PREFIX) qualifies scopes sent
	// upstream, such as api://app.
	ScopePrefix string
	// UpstreamResource (AUTH_OAUTH_FACADE_UPSTREAM_RESOURCE) is sent upstream
	// as the resource parameter; empty omits it.
	UpstreamResource string
}

FacadeConfig enables the authorization server facade when ClientID is set.

Example

ExampleFacadeConfig enables the authorization server facade in front of Microsoft Entra ID and mounts its endpoints beside /mcp.

mcpHandler := http.NotFoundHandler()
clientSecret := secret.New("the client secret of the Entra app")
gate, err := New(&Config{
	Mode: ModeOAuth,
	OAuth: OAuthConfig{
		Issuer:    "https://login.microsoftonline.com/contoso/v2.0",
		Audience:  "api://orders",
		PublicURL: "https://mcp.example.com",
		Facade: FacadeConfig{
			ClientID:     "orders-mcp",
			ClientSecret: clientSecret,
			ScopePrefix:  "api://orders",
		},
	},
})
if err != nil {
	log.Fatal(err)
}
mux := http.NewServeMux()
mux.Handle("/mcp", gate.Middleware(mcpHandler))
gate.Mount(mux, "/mcp") // metadata, /authorize, /register, /token
w := httptest.NewRecorder()
mux.ServeHTTP(w, httptest.NewRequestWithContext(context.Background(), http.MethodPost,
	"https://mcp.example.com/register", strings.NewReader(`{"redirect_uris":["http://127.0.0.1:8765/cb"]}`)))
fmt.Println(w.Code)
Output:
201

type Gate

type Gate struct {
	// contains filtered or unexported fields
}

Gate authenticates requests in the configured mode and guards handlers. Only New builds a usable Gate, which is safe for concurrent use.

func New

func New(cfg *Config) (*Gate, error)

New builds a Gate from cfg, reporting every configuration problem at once, a nil cfg included; each wraps ErrInvalidConfig.

Example
gate, err := New(&Config{Mode: ModeBearer, Bearer: BearerConfig{Token: secret.New(testLongSecret)}})
if err != nil {
	fmt.Println(err)
	return
}
api := gate.Middleware(gate.Require()(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	id, _ := IdentityFromContext(r.Context())
	w.Header().Set("X-Subject", id.Subject())
})))
r := httptest.NewRequestWithContext(context.Background(), http.MethodGet, pathRoot, http.NoBody)
r.Header.Set(headerAuthorization, "Bearer "+testLongSecret)
w := httptest.NewRecorder()
api.ServeHTTP(w, r)
fmt.Println(w.Code, w.Header().Get("X-Subject"))
Output:
200 static-bearer

func (*Gate) Authenticate

func (g *Gate) Authenticate(r *http.Request) (*Identity, error)

Authenticate checks the credentials of r. Errors match one of the ErrMissingCredentials, ErrInvalidCredentials, ErrTokenExpired, ErrInsufficientScope or ErrKeysUnavailable sentinels.

func (*Gate) CheckHandler

func (g *Gate) CheckHandler() http.Handler

CheckHandler serves nginx auth_request, never cached: 200 with X-Auth-Subject, X-Auth-Method and any X-Auth-Scopes, or the challenge for the X-Original-URI path, 403 in a mode without one, or 503 with Retry-After while the keys are unavailable.

Example

ExampleGate_CheckHandler answers an nginx auth_request subrequest.

gate, err := New(&Config{Mode: ModeBearer, Bearer: BearerConfig{Token: secret.New(testLongSecret)}})
if err != nil {
	log.Fatal(err)
}
mux := http.NewServeMux()
mux.Handle("/auth/check", gate.CheckHandler())
r := httptest.NewRequestWithContext(context.Background(), http.MethodGet, "/auth/check", http.NoBody)
r.Header.Set(headerAuthorization, "Bearer "+testLongSecret)
w := httptest.NewRecorder()
mux.ServeHTTP(w, r)
fmt.Println(w.Code, w.Header().Get(headerSubject))
Output:
200 static-bearer

func (*Gate) Middleware

func (g *Gate) Middleware(next http.Handler) http.Handler

Middleware passes authenticated requests to next, not nil, their Identity in the context; others get the challenge of the mode, resource_metadata in an OAuth one, 403 in a mode without one, or 503 with Retry-After while the keys are unavailable.

func (*Gate) Mode

func (g *Gate) Mode() Mode

Mode returns the configured mode.

func (*Gate) Mount

func (g *Gate) Mount(mux *http.ServeMux, endpoints ...string)

Mount registers on mux, not nil, in ModeOAuth any facade routes and the metadata of each path an endpoint path pattern matches, sub-paths included, the bare path naming the first; it panics, as ServeMux.Handle does, if a pattern is invalid or conflicts.

Example

ExampleGate_Mount guards /mcp in ModeOAuth and serves its protected resource metadata.

mcpHandler := http.NotFoundHandler()
gate, err := New(&Config{
	Mode: ModeOAuth,
	OAuth: OAuthConfig{
		Issuer:         "https://login.example.com/tenant",
		Audience:       "api://orders",
		RequiredScopes: []string{"orders.read"},
	},
})
if err != nil {
	log.Fatal(err)
}

mux := http.NewServeMux()
mux.Handle("/mcp", gate.Middleware(mcpHandler))
gate.Mount(mux, "/mcp") // protected resource metadata for /mcp
for _, path := range []string{"/mcp", "/.well-known/oauth-protected-resource/mcp"} {
	w := httptest.NewRecorder()
	mux.ServeHTTP(w, httptest.NewRequestWithContext(context.Background(), http.MethodGet,
		"https://api.example"+path, http.NoBody))
	fmt.Println(path, w.Code)
}
Output:
/mcp 401
/.well-known/oauth-protected-resource/mcp 200

func (*Gate) Require

func (g *Gate) Require(checks ...Capability) func(http.Handler) http.Handler

Require admits requests whose Identity, stored by Middleware, passes every check. Without an identity it answers 401, or 403 in a mode without a challenge, and 403 on a failed check.

Example

ExampleGate_Require admits only OAuth identities that hold the admin scope and the tenant claim acme; a request without a token gets 401.

adminHandler := http.NotFoundHandler()
gate, err := New(validOAuth())
if err != nil {
	log.Fatal(err)
}
admin := gate.Middleware(gate.Require(
	HasMode(ModeOAuth),
	HasAllScopes("admin"),
	HasClaim("tenant", "acme"),
)(adminHandler))
w := httptest.NewRecorder()
admin.ServeHTTP(w, httptest.NewRequestWithContext(context.Background(), http.MethodGet, pathRoot, http.NoBody))
fmt.Println(w.Code)
Output:
401

type Identity

type Identity struct {
	// contains filtered or unexported fields
}

Identity is an authenticated caller. It is immutable and safe to share. Its methods accept a nil Identity, which has no subject, mode, scope, certificate or claim.

func IdentityFromContext

func IdentityFromContext(ctx context.Context) (*Identity, bool)

IdentityFromContext returns the identity stored by WithIdentity; ok is false, and the identity nil, when there is none or it is nil.

Example

ExampleIdentityFromContext reads the identity WithIdentity stored in the request context.

r := httptest.NewRequestWithContext(context.Background(), http.MethodGet, pathRoot, http.NoBody)
r = r.WithContext(WithIdentity(r.Context(), scoped("orders.read")))
id, ok := IdentityFromContext(r.Context())
fmt.Println(ok, id.Subject(), id.Mode(), id.Scopes(), id.HasScope("orders.read"))
team, ok := id.ClaimString("team")
fmt.Println(team, ok)
Output:
true user oauth [orders.read] true
platform-engineering true

func (*Identity) Claim

func (id *Identity) Claim(name string) (value any, ok bool)

Claim returns the named token claim as a string, int64, float64, bool or nil, or as its JSON text when it decodes to none of those, as an object, an array or a number beyond float64 does.

func (*Identity) ClaimBool

func (id *Identity) ClaimBool(name string) (value, ok bool)

ClaimBool returns the named claim when it is a JSON boolean.

func (*Identity) ClaimFloat64

func (id *Identity) ClaimFloat64(name string) (value float64, ok bool)

ClaimFloat64 returns the named claim rounded to the nearest float64 when it is a JSON number and that float64 is finite.

func (*Identity) ClaimInt64

func (id *Identity) ClaimInt64(name string) (value int64, ok bool)

ClaimInt64 returns the named claim when it is a JSON integer, with no fraction or exponent, within int64's range.

func (*Identity) ClaimString

func (id *Identity) ClaimString(name string) (value string, ok bool)

ClaimString returns the named claim when it is a JSON string.

func (*Identity) Claims

func (id *Identity) Claims() iter.Seq2[string, any]

Claims returns an iterator over the token claims, each value a string, int64, float64, bool or nil, else its JSON text; a nil Identity yields none.

func (*Identity) HasScope

func (id *Identity) HasScope(scope string) bool

HasScope reports whether scope was granted.

func (*Identity) Mode

func (id *Identity) Mode() Mode

Mode returns the mode that authenticated the caller.

func (*Identity) PeerCertificate

func (id *Identity) PeerCertificate() *x509.Certificate

PeerCertificate returns the client certificate in ModeMTLS, else nil; the certificate is shared and must not be modified.

func (*Identity) Scopes

func (id *Identity) Scopes() []string

Scopes returns a copy of the granted scopes, each a scope token.

func (*Identity) Subject

func (id *Identity) Subject() string

Subject returns the caller's subject, a header value that a Gate leaves empty only in ModeNone; a nil identity has none.

type MTLSConfig

type MTLSConfig struct {
	// AllowedSubjects (AUTH_MTLS_ALLOWED_SUBJECTS, a semicolon list) holds common
	// names, or distinguished names when an entry contains '=', header values
	// written as pkix.Name.String renders them, a dotted type's value as #DER hex.
	AllowedSubjects []string
	// AllowedSPKIPins (AUTH_MTLS_SPKI_PINS, a list of base64 digests) holds the
	// SHA-256 digests of accepted SubjectPublicKeyInfo.
	AllowedSPKIPins [][]byte
}

MTLSConfig configures ModeMTLS. A certificate passes when a verified chain matches a subject, or when its SPKI SHA-256 matches a pin.

Example

ExampleMTLSConfig admits a client certificate by its common name over a verified chain, or by the SHA-256 pin of its key.

client, pinned := testCert("client.example"), testCert("anyone")
pin := sha256.Sum256(pinned.RawSubjectPublicKeyInfo)
spkiSHA256 := pin[:]
gate, err := New(&Config{
	Mode: ModeMTLS,
	MTLS: MTLSConfig{
		AllowedSubjects: []string{"client.example", "CN=admin,O=corp"},
		AllowedSPKIPins: [][]byte{spkiSHA256},
	},
})
if err != nil {
	log.Fatal(err)
}
r := httptest.NewRequestWithContext(context.Background(), http.MethodGet, pathRoot, http.NoBody)
r.TLS = &tls.ConnectionState{PeerCertificates: []*x509.Certificate{client},
	VerifiedChains: [][]*x509.Certificate{{client}}}
id, err := gate.Authenticate(r)
fmt.Println(id.Subject(), err)
r.TLS = &tls.ConnectionState{PeerCertificates: []*x509.Certificate{pinned}}
id, err = gate.Authenticate(r)
fmt.Println(id.Subject(), err)
Output:
client.example <nil>
sha256/BI1oy9BwcDx6zD32DDP2nf3UUS7j3zekFjDCbOaPfIc= <nil>

type Mode

type Mode string

Mode names an authentication scheme.

const (
	ModeNone   Mode = "none"
	ModeBearer Mode = "bearer"
	ModeAPIKey Mode = "apikey"
	ModeOAuth  Mode = "oauth"
	ModeMTLS   Mode = "mtls"
)

These are the modes a Gate enforces; Config.Mode selects exactly one.

type OAuthConfig

type OAuthConfig struct {
	// Issuer (AUTH_OAUTH_ISSUER) must equal the token iss claim byte for byte.
	Issuer string
	// Audience (AUTH_OAUTH_AUDIENCE) must appear in the token aud claim.
	Audience string
	// RequiredScopes (AUTH_OAUTH_REQUIRED_SCOPES, a list) must all be granted
	// to every token.
	RequiredScopes []string
	// JWKSURL (AUTH_OAUTH_JWKS_URL) locates the signing keys; empty discovers
	// them from Issuer.
	JWKSURL string
	// HMACSecret (AUTH_OAUTH_HMAC_SECRET) verifies HS* tokens instead of a
	// JWKS; at least 32 bytes, and 48 or 64 to verify HS384 or HS512.
	HMACSecret secret.Value
	// ClockSkew (AUTH_OAUTH_CLOCK_SKEW) is tolerated on exp, nbf and iat;
	// default 30s.
	ClockSkew time.Duration
	// KeysCacheTTL (AUTH_OAUTH_KEYS_CACHE_TTL) is the lifetime of fetched
	// keys and issuer metadata; default 5m.
	KeysCacheTTL time.Duration
	// FetchTimeout (AUTH_OAUTH_FETCH_TIMEOUT) bounds JWKS, discovery and
	// facade fetches; default 10s.
	FetchTimeout time.Duration
	// PublicURL (AUTH_OAUTH_PUBLIC_URL) is the external origin; it wins over
	// the request.
	PublicURL string
	// Resource describes the protected resource in its metadata document.
	Resource ResourceConfig
	// Facade enables the authorization server facade.
	Facade FacadeConfig
	// RequireAccessTokenType (AUTH_OAUTH_REQUIRE_AT_JWT) accepts only tokens
	// typed at+jwt.
	RequireAccessTokenType bool
	// TrustForwardedProto (AUTH_OAUTH_TRUST_FORWARDED_PROTO) takes the scheme
	// from X-Forwarded-Proto.
	TrustForwardedProto bool
}

OAuthConfig configures ModeOAuth: JWT access tokens checked against an issuer.

type ResourceConfig

type ResourceConfig struct {
	// Identifier (AUTH_OAUTH_RESOURCE) is the resource URL; empty means origin plus the
	// escaped request path after /.well-known/oauth-protected-resource, or for that bare
	// path the first endpoint unless it is /.
	Identifier string
	// Name (AUTH_OAUTH_RESOURCE_NAME) is the resource_name member.
	Name string
	// Documentation (AUTH_OAUTH_RESOURCE_DOCUMENTATION) is the
	// resource_documentation member.
	Documentation string
	// AuthorizationServers (AUTH_OAUTH_AUTHORIZATION_SERVERS, a list) defaults to
	// Issuer when it is a secure URL; a facade advertises the origin instead
	// and refuses an explicit list.
	AuthorizationServers []string
}

ResourceConfig describes the protected resource in its metadata document.

type SecurityHeadersConfig

type SecurityHeadersConfig struct {
	// HSTSMaxAge is the Strict-Transport-Security max-age in seconds; a
	// non-positive value writes no Strict-Transport-Security.
	HSTSMaxAge int
	// CSP is the Content-Security-Policy value.
	CSP string
	// FrameOptions is the X-Frame-Options value.
	FrameOptions string
	// ReferrerPolicy is the Referrer-Policy value.
	ReferrerPolicy string
	// PermissionsPolicy is the Permissions-Policy value.
	PermissionsPolicy string
	// HSTSIncludeSubDomains adds includeSubDomains to Strict-Transport-Security.
	HSTSIncludeSubDomains bool
	// HSTSPreload adds preload to Strict-Transport-Security.
	HSTSPreload bool
	// ContentTypeNosniff writes X-Content-Type-Options: nosniff.
	ContentTypeNosniff bool
}

SecurityHeadersConfig selects the headers written by SecurityHeaders; zero fields write nothing.

Directories

Path Synopsis
Package cred attaches credentials to outbound HTTP requests: a TokenSource produces a Token, a Signer modifies a request in place, AsSigner turns a TokenSource into a Signer, Basic builds the Token of HTTP Basic credentials and NewTransport signs a clone of every request a net/http.Client sends.
Package cred attaches credentials to outbound HTTP requests: a TokenSource produces a Token, a Signer modifies a request in place, AsSigner turns a TokenSource into a Signer, Basic builds the Token of HTTP Basic credentials and NewTransport signs a clone of every request a net/http.Client sends.
internal
flight
Package flight runs one shared call on behalf of many concurrent callers: a Group starts at most one call at a time, detached from the cancellation of the caller that starts it and bounded by its own timeout, so a caller that gives up returns early with its own context error while the call completes for everyone still waiting.
Package flight runs one shared call on behalf of many concurrent callers: a Group starts at most one call at a time, detached from the cancellation of the caller that starts it and bounded by its own timeout, so a caller that gives up returns early with its own context error while the call completes for everyone still waiting.
jsonobj
Package jsonobj holds the shape every JSON document the module parses must have: exactly one UTF-8 object, nested at most 32 deep, in which no object repeats a member name, as go-jsonfast checks and walks it.
Package jsonobj holds the shape every JSON document the module parses must have: exactly one UTF-8 object, nested at most 32 deep, in which no object repeats a member name, as go-jsonfast checks and walks it.
keyedmac
Package keyedmac computes the HMAC of one key: a MAC keeps the keyed states of its hash in a pool, so a sum that reuses one costs no key schedule, and appends to room the caller owns.
Package keyedmac computes the HMAC of one key: a MAC keeps the keyed states of its hash in a pool, so a sum that reuses one costs no key schedule, and appends to room the caller owns.
netguard
Package netguard holds the outbound URL policy shared by every fetch the module makes: Check accepts https URLs and plain http only toward a loopback host, and refuses userinfo in any form; Client derives a net/http.Client that never follows redirects, so the policy checked on the first URL is the policy of every request.
Package netguard holds the outbound URL policy shared by every fetch the module makes: Check accepts https URLs and plain http only toward a loopback host, and refuses userinfo in any form; Client derives a net/http.Client that never follows redirects, so the policy checked on the first URL is the policy of every request.
oauthwire
Package oauthwire holds the OAuth 2.0 wire format shared by the outbound credential sources and the authorization server facade: the parameter names and error codes both sides use, the client parameters (SetClientParams), strict token response decoding (ParseTokenResponse), error responses (WriteError), uncached JSON replies (WriteJSON) over WriteBody, the token request (NewTokenRequest) and the metadata request (NewGetRequest) to URLs accepted by the netguard policy, the bounded fetch (Fetch) of a caller-supplied non-redirecting client, which reads the status of an answer before its body, and the token answer of any status (Send) the facade relays.
Package oauthwire holds the OAuth 2.0 wire format shared by the outbound credential sources and the authorization server facade: the parameter names and error codes both sides use, the client parameters (SetClientParams), strict token response decoding (ParseTokenResponse), error responses (WriteError), uncached JSON replies (WriteJSON) over WriteBody, the token request (NewTokenRequest) and the metadata request (NewGetRequest) to URLs accepted by the netguard policy, the bounded fetch (Fetch) of a caller-supplied non-redirecting client, which reads the status of an answer before its body, and the token answer of any status (Send) the facade relays.
problems
Package problems collects every problem one validation finds, each wrapping the configuration sentinel of the package that validates, and joins them into a single error, so that a constructor reports all that is wrong with its input at once; List.ScopeToken is the one rule of a scope token and List.Scopes the one of a scope list.
Package problems collects every problem one validation finds, each wrapping the configuration sentinel of the package that validates, and joins them into a single error, so that a constructor reports all that is wrong with its input at once; List.ScopeToken is the one rule of a scope token and List.Scopes the one of a scope list.
reply
Package reply writes the plain-text refusals of the middleware: Error answers 401, 403 or 503 byte for byte as net/http.Error does, with at most one more header, such as the challenge (Challenge) or the pause before a retry (RetryAfter), all its header values held in one array.
Package reply writes the plain-text refusals of the middleware: Error answers 401, 403 or 503 byte for byte as net/http.Error does, with at most one more header, such as the challenge (Challenge) or the pause before a retry (RetryAfter), all its header values held in one array.
retry
Package retry paces the calls that follow a failure or a forced call: a Backoff holds the end of a pause of After that a failed call starts or a forced call claims, and compares instants by their monotonic readings, so a step of the wall clock neither shortens nor stretches a pause.
Package retry paces the calls that follow a failure or a forced call: a Backoff holds the end of a pause of After that a failed call starts or a forced call claims, and compares instants by their monotonic readings, so a step of the wall clock neither shortens nor stretches a pause.
syntax
Package syntax holds the character rules, the compact JWS splitter and the strict base64url decoder shared across the module: IsControl spots an ASCII control byte, IsUnreserved accepts an unreserved URI character, IsToken a header name or an authentication scheme, IsScope an OAuth scope token and IsFieldValue a value that travels intact in one header line, while SplitJWS splits the compact JWS form and AppendSegment decodes unpadded base64url, the encoding of its segments.
Package syntax holds the character rules, the compact JWS splitter and the strict base64url decoder shared across the module: IsControl spots an ASCII control byte, IsUnreserved accepts an unreserved URI character, IsToken a header name or an authentication scheme, IsScope an OAuth scope token and IsFieldValue a value that travels intact in one header line, while SplitJWS splits the compact JWS form and AppendSegment decodes unpadded base64url, the encoding of its segments.
Package replay signs outbound HTTP requests with HMAC-SHA256 and rejects replayed ones: a Signer, which implements github.com/ubyte-source/go-authware/v2/cred.Signer, attaches a timestamp, a nonce and a signature of the request, and a Verifier, directly or through its Middleware, checks the signature in constant time and the timestamp against a window before it records the nonce in a NonceStore, such as the bounded in-process store of NewMemoryStore; a fleet of verifiers needs a shared one.
Package replay signs outbound HTTP requests with HMAC-SHA256 and rejects replayed ones: a Signer, which implements github.com/ubyte-source/go-authware/v2/cred.Signer, attaches a timestamp, a nonce and a signature of the request, and a Verifier, directly or through its Middleware, checks the signature in constant time and the timestamp against a window before it records the nonce in a NonceStore, such as the bounded in-process store of NewMemoryStore; a fleet of verifiers needs a shared one.
Package secret carries secret strings and the providers that load them: a non-zero Value renders as *** through fmt, log/slog and the JSON and text encoders, but fmt prints its type for %T and the address it holds for %p, %w and in an unexported field; Value.Reveal alone reads it back and Value.Equal compares in constant time, while Static, Env, File and MapResolver build the Provider and Resolver that resolve keys to Values, a missing key or an empty value yielding ErrNotFound.
Package secret carries secret strings and the providers that load them: a non-zero Value renders as *** through fmt, log/slog and the JSON and text encoders, but fmt prints its type for %T and the address it holds for %p, %w and in an unexported field; Value.Reveal alone reads it back and Value.Equal compares in constant time, while Static, Env, File and MapResolver build the Provider and Resolver that resolve keys to Values, a missing key or an empty value yielding ErrNotFound.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL