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 ¶
- Variables
- func CheckOutboundURL(raw string) (*url.URL, error)
- func EnvNames(prefix string) []string
- func NewRedactor(inner slog.Handler, keys ...string) slog.Handler
- func RedactHeader(h http.Header, keys ...string) http.Header
- func SecurityHeaders(cfg *SecurityHeadersConfig) func(http.Handler) http.Handler
- func SensitiveHeaders() []string
- func WithIdentity(ctx context.Context, id *Identity) context.Context
- type APIKeyConfig
- type BearerConfig
- type Capability
- func HasAllScopes(scopes ...string) Capability
- func HasAnyScope(scopes ...string) Capability
- func HasClaim[T string | int64 | float64 | bool](name string, value T) Capability
- func HasMode(m Mode) Capability
- func HasSubject(subject string) Capability
- func NewCapability(fn func(*Identity) bool) Capability
- type Config
- type FacadeConfig
- type Gate
- func (g *Gate) Authenticate(r *http.Request) (*Identity, error)
- func (g *Gate) CheckHandler() http.Handler
- func (g *Gate) Middleware(next http.Handler) http.Handler
- func (g *Gate) Mode() Mode
- func (g *Gate) Mount(mux *http.ServeMux, endpoints ...string)
- func (g *Gate) Require(checks ...Capability) func(http.Handler) http.Handler
- type Identity
- func (id *Identity) Claim(name string) (value any, ok bool)
- func (id *Identity) ClaimBool(name string) (value, ok bool)
- func (id *Identity) ClaimFloat64(name string) (value float64, ok bool)
- func (id *Identity) ClaimInt64(name string) (value int64, ok bool)
- func (id *Identity) ClaimString(name string) (value string, ok bool)
- func (id *Identity) Claims() iter.Seq2[string, any]
- func (id *Identity) HasScope(scope string) bool
- func (id *Identity) Mode() Mode
- func (id *Identity) PeerCertificate() *x509.Certificate
- func (id *Identity) Scopes() []string
- func (id *Identity) Subject() string
- type MTLSConfig
- type Mode
- type OAuthConfig
- type ResourceConfig
- type SecurityHeadersConfig
Examples ¶
Constants ¶
This section is empty.
Variables ¶
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 = 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 ¶
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 ¶
EnvNames returns the name of the variable of every Config field but HTTPClient and ErrorLog, each preceded by prefix.
func NewRedactor ¶
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 ¶
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.
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 ¶
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 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 ¶
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
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 ¶
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 ¶
Authenticate checks the credentials of r. Errors match one of the ErrMissingCredentials, ErrInvalidCredentials, ErrTokenExpired, ErrInsufficientScope or ErrKeysUnavailable sentinels.
func (*Gate) CheckHandler ¶
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 ¶
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) Mount ¶
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 ¶
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 ¶
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 ¶
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) ClaimFloat64 ¶
ClaimFloat64 returns the named claim rounded to the nearest float64 when it is a JSON number and that float64 is finite.
func (*Identity) ClaimInt64 ¶
ClaimInt64 returns the named claim when it is a JSON integer, with no fraction or exponent, within int64's range.
func (*Identity) ClaimString ¶
ClaimString returns the named claim when it is a JSON string.
func (*Identity) Claims ¶
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) 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.
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 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.
Source Files
¶
- apikey.go
- bearer.go
- cache.go
- capability.go
- challenge.go
- claims.go
- config.go
- credential.go
- defaults.go
- discovery.go
- doc.go
- document.go
- env.go
- errors.go
- facade.go
- facade_authorize.go
- facade_register.go
- facade_token.go
- gate.go
- headers.go
- identity.go
- jose.go
- jwk.go
- keys.go
- mtls.go
- none.go
- oauth.go
- origin.go
- outbound.go
- params.go
- redact.go
- scope.go
- static.go
- verify.go
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. |