auth

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Aug 7, 2026 License: Apache-2.0 Imports: 13 Imported by: 0

README

Auth Package

The auth package provides modular authentication strategies for the remote client.

Authenticator Interface

All strategies implement the Authenticator interface, allowing them to be easily injected into any remote.Client.

type Authenticator interface {
    Apply(req *http.Request) error
}

Construction

There are two ways to build an authenticator:

  1. From configauth.Build(authType, options) parses the JSON options for a strategy, resolves any secret references (see Secret References) once, and returns the authenticator. This is what the remote Manager uses when it loads services.json. A reference that cannot be resolved is a loud error.

    authn, err := auth.Build("oauth2", optionsJSON)
    
  2. Directly — the New* constructors take already-resolved plain values. They are pure: no I/O, no error.

    auth.NewAPIKey("X-Custom-Key", "my-secret-key")
    auth.NewBearer("my-jwt-token")
    auth.NewOAuth2("https://identity.example.com/oauth2/token", "my-client-id", "my-client-secret", []string{"read", "write"})
    

Supported Strategies

API Key Authentication

Uses a custom header (e.g., X-API-Key) with a fixed value.

Bearer Token Authentication

Uses the standard Authorization: Bearer <token> header.

OAuth2 Client Credentials Flow

Implements the OAuth2 Client Credentials flow with the following features:

  • Automatic token caching.
  • Expiry handling with a 1-minute safety buffer.
  • Synchronized token updates to prevent race conditions.
  • Scope support.

Secret References

Secret-bearing config fields (value, token, client_secret) are a secret.SecretRef — a literal value or a scheme-prefixed reference (env:NAME, file:/path) that is resolved to its concrete value. The type lives in the standalone secret module; see its README for the full scheme table and how to add a source.

In services.json, a reference is written per field:

{
  "auth": {
    "type": "oauth2",
    "options": {
      "token_url": "https://identity.example.com/oauth2/token",
      "client_id": "my-client",
      "client_secret": "env:CLIENT_SECRET",
      "scopes": ["read", "write"]
    }
  }
}

References are resolved once, at startup — when Manager.LoadServices loads the file, or via auth.Build. A missing env var or an unreadable/empty file is a loud error — a reference never silently resolves to the empty string. Resolution is not repeated per request; if a referenced value changes, restart the process to pick it up.

Strategy Configuration

APIKeyConfig

Used when the authentication type is "api_key".

Field Type Description
key string The HTTP header name (e.g., "X-API-Key").
value SecretRef The key value — a literal or a reference (see Secret References).
BearerConfig

Used when the authentication type is "bearer".

Field Type Description
token SecretRef The bearer token — a literal or a reference (see Secret References).
OAuth2Config

Used when the authentication type is "oauth2".

Field Type Description
token_url string The OAuth2 token endpoint URL.
client_id string The client identifier.
client_secret SecretRef The client secret — a literal or a reference (see Secret References).
scopes []string Optional list of requested scopes.
insecure_skip_tls_verify bool Optional. Skips TLS certificate verification on the token request only. For local development against a self-signed identity provider — never enable in production. Defaults to false.
endpoint_params object Optional. Extra parameters for the token request, sent in the request body (RFC 6749 §3.2) — for example the RFC 8707 resource indicator naming the resource server a token is for. Each value is a string or an array of strings; null is rejected rather than sent as an empty parameter. grant_type, scope, client_id and client_secret are set by the flow itself and rejected here.
{
  "token_url": "https://idp.example/oauth2/token",
  "client_id": "my-client",
  "client_secret": "env:MY_CLIENT_SECRET",
  "scopes": ["api:read"],
  "endpoint_params": { "resource": "https://api.example" }
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

type APIKey

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

func NewAPIKey

func NewAPIKey(key, value string) *APIKey

NewAPIKey builds an API-key authenticator from already-resolved values.

func (*APIKey) Apply

func (a *APIKey) Apply(req *http.Request) error

type APIKeyConfig

type APIKeyConfig struct {
	Key   string           `json:"key"`
	Value secret.SecretRef `json:"value"`
}

type Authenticator

type Authenticator interface {
	Apply(req *http.Request) error
}

Authenticator defines an interface for applying authentication to outgoing requests.

func Build added in v0.2.0

func Build(authType string, options json.RawMessage) (Authenticator, error)

Build constructs an authenticator for the given auth type from its raw JSON options. It is the single entry point callers (e.g. the remote Manager) use, so they need not know about individual strategies. Secret references are resolved here, once; an unresolvable reference is a loud error.

type Bearer

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

func NewBearer

func NewBearer(token string) *Bearer

NewBearer builds a bearer-token authenticator from an already-resolved token.

func (*Bearer) Apply

func (a *Bearer) Apply(req *http.Request) error

type BearerConfig

type BearerConfig struct {
	Token secret.SecretRef `json:"token"`
}

type EndpointParams added in v0.6.0

type EndpointParams url.Values

EndpointParams carries extra parameters for the token request. They are sent in the request body alongside grant_type and scope, as RFC 6749 §3.2 requires — for example the RFC 8707 `resource` indicator, which names the resource server an access token is for.

It is url.Values so it drops straight into the token request (and into golang.org/x/oauth2/clientcredentials.Config.EndpointParams) without conversion, but its JSON accepts either a string or an array of strings per key, since a single value is the normal case:

"endpoint_params": { "resource": "https://api.example" }
"endpoint_params": { "resource": ["https://a.example", "https://b.example"] }

func (*EndpointParams) UnmarshalJSON added in v0.6.0

func (p *EndpointParams) UnmarshalJSON(data []byte) error

UnmarshalJSON accepts a string or an array of strings for each key.

type OAuth2

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

func NewOAuth2

func NewOAuth2(tokenURL, clientID, clientSecret string, scopes []string, opts ...OAuth2Option) *OAuth2

NewOAuth2 builds an OAuth2 client-credentials authenticator from already-resolved values.

func (*OAuth2) Apply

func (a *OAuth2) Apply(req *http.Request) error

func (*OAuth2) SetInsecureSkipTLSVerify added in v0.2.0

func (a *OAuth2) SetInsecureSkipTLSVerify(skip bool)

SetInsecureSkipTLSVerify controls whether the OAuth2 token request client skips certificate verification. This is intended for local development with self-signed identity-provider certificates only.

type OAuth2Config

type OAuth2Config struct {
	TokenURL              string           `json:"token_url"`
	ClientID              string           `json:"client_id"`
	ClientSecret          secret.SecretRef `json:"client_secret"`
	Scopes                []string         `json:"scopes,omitempty"`
	InsecureSkipTLSVerify bool             `json:"insecure_skip_tls_verify,omitempty"`
	EndpointParams        EndpointParams   `json:"endpoint_params,omitempty"`
}

type OAuth2Option added in v0.6.0

type OAuth2Option func(*OAuth2)

OAuth2Option configures an OAuth2 authenticator.

func WithEndpointParams added in v0.6.0

func WithEndpointParams(params url.Values) OAuth2Option

WithEndpointParams adds extra parameters to the token request body. Empty values are ignored. See EndpointParams for what belongs here.

Jump to

Keyboard shortcuts

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