token

package
v0.14.0 Latest Latest
Warning

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

Go to latest
Published: Feb 28, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const (
	TokenTypeBearer = "Bearer"
)

Token type constants

Variables

View Source
var (
	// ErrTokenGeneration indicates token generation failed
	ErrTokenGeneration = errors.New("failed to generate token")

	// ErrTokenValidation indicates token validation failed
	ErrTokenValidation = errors.New("failed to validate token")

	// ErrInvalidToken indicates the token is invalid
	ErrInvalidToken = errors.New("invalid token")

	// ErrExpiredToken indicates the token has expired
	ErrExpiredToken = errors.New("token expired")

	// ErrInvalidRefreshToken indicates the refresh token is invalid
	ErrInvalidRefreshToken = errors.New("invalid refresh token")

	// ErrExpiredRefreshToken indicates the refresh token has expired
	ErrExpiredRefreshToken = errors.New("refresh token expired")

	// ErrTokenReused indicates a refresh token was reused (security alert)
	ErrTokenReused = errors.New("token reuse detected")

	// ErrInvalidScope indicates scope validation failed
	ErrInvalidScope = errors.New("invalid scope")

	// ErrHTTPTokenConnection indicates failed connection to token API
	ErrHTTPTokenConnection = errors.New("failed to connect to token API")

	// ErrHTTPTokenAuthFailed indicates token API rejected request
	ErrHTTPTokenAuthFailed = errors.New("token API rejected request")

	// ErrHTTPTokenInvalidResp indicates invalid response from token API
	ErrHTTPTokenInvalidResp = errors.New("invalid response from token API")
)

Functions

func ComputeAtHash added in v0.13.0

func ComputeAtHash(accessToken string) string

ComputeAtHash computes the at_hash claim value per OIDC Core 1.0 §3.3.2.11. at_hash = base64url( left-most 128 bits of SHA-256( ASCII(access_token) ) )

func ScopeSet added in v0.13.0

func ScopeSet(scopes string) map[string]bool

ScopeSet parses a space-separated scope string into a boolean lookup map.

Types

type APIRefreshRequest

type APIRefreshRequest struct {
	RefreshToken   string `json:"refresh_token"`
	UserID         string `json:"user_id"`
	ClientID       string `json:"client_id"`
	Scopes         string `json:"scopes"`
	EnableRotation bool   `json:"enable_rotation"`
}

APIRefreshRequest is the request payload for refresh token operations

type APIRefreshResponse

type APIRefreshResponse struct {
	Success          bool           `json:"success"`
	AccessToken      string         `json:"access_token,omitempty"`
	RefreshToken     string         `json:"refresh_token,omitempty"`
	TokenType        string         `json:"token_type,omitempty"`
	AccessExpiresIn  int            `json:"access_expires_in,omitempty"`
	RefreshExpiresIn int            `json:"refresh_expires_in,omitempty"`
	Claims           map[string]any `json:"claims,omitempty"`
	Message          string         `json:"message,omitempty"`
}

APIRefreshResponse is the expected response for refresh token operations

type APITokenGenerateRequest

type APITokenGenerateRequest struct {
	UserID    string `json:"user_id"`
	ClientID  string `json:"client_id"`
	Scopes    string `json:"scopes"`
	ExpiresIn int    `json:"expires_in,omitempty"` // seconds
}

APITokenGenerateRequest is the request payload for token generation

type APITokenGenerateResponse

type APITokenGenerateResponse struct {
	Success     bool           `json:"success"`
	AccessToken string         `json:"access_token,omitempty"`
	TokenType   string         `json:"token_type,omitempty"`
	ExpiresIn   int            `json:"expires_in,omitempty"` // seconds
	Claims      map[string]any `json:"claims,omitempty"`
	Message     string         `json:"message,omitempty"`
}

APITokenGenerateResponse is the expected response for token generation

type APITokenValidateRequest

type APITokenValidateRequest struct {
	Token string `json:"token"`
}

APITokenValidateRequest is the request payload for token validation

type APITokenValidateResponse

type APITokenValidateResponse struct {
	Valid     bool           `json:"valid"`
	UserID    string         `json:"user_id,omitempty"`
	ClientID  string         `json:"client_id,omitempty"`
	Scopes    string         `json:"scopes,omitempty"`
	ExpiresAt int64          `json:"expires_at,omitempty"` // Unix timestamp
	Claims    map[string]any `json:"claims,omitempty"`
	Message   string         `json:"message,omitempty"`
}

APITokenValidateResponse is the expected response for token validation

type HTTPTokenProvider

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

HTTPTokenProvider generates and validates tokens via external HTTP API

func NewHTTPTokenProvider

func NewHTTPTokenProvider(cfg *config.Config, retryClient *retry.Client) *HTTPTokenProvider

NewHTTPTokenProvider creates a new HTTP API token provider

func (*HTTPTokenProvider) GenerateRefreshToken

func (p *HTTPTokenProvider) GenerateRefreshToken(
	ctx context.Context,
	userID, clientID, scopes string,
) (*Result, error)

GenerateRefreshToken requests refresh token generation from external API

func (*HTTPTokenProvider) GenerateToken

func (p *HTTPTokenProvider) GenerateToken(
	ctx context.Context,
	userID, clientID, scopes string,
) (*Result, error)

GenerateToken requests token generation from external API

func (*HTTPTokenProvider) Name

func (p *HTTPTokenProvider) Name() string

Name returns provider name for logging

func (*HTTPTokenProvider) RefreshAccessToken

func (p *HTTPTokenProvider) RefreshAccessToken(
	ctx context.Context,
	refreshToken string,
	enableRotation bool,
) (*RefreshResult, error)

RefreshAccessToken requests new access token (and optionally new refresh token) from external API

func (*HTTPTokenProvider) ValidateRefreshToken

func (p *HTTPTokenProvider) ValidateRefreshToken(
	ctx context.Context,
	tokenString string,
) (*ValidationResult, error)

ValidateRefreshToken requests refresh token validation from external API

func (*HTTPTokenProvider) ValidateToken

func (p *HTTPTokenProvider) ValidateToken(
	ctx context.Context,
	tokenString string,
) (*ValidationResult, error)

ValidateToken requests token validation from external API

type IDTokenParams added in v0.13.0

type IDTokenParams struct {
	Issuer   string
	Subject  string // UserID
	Audience string // ClientID
	AuthTime time.Time
	Nonce    string
	Expiry   time.Duration
	AtHash   string // base64url(SHA-256(access_token)[:16]) – optional

	// Scope-gated profile claims (include when "profile" scope was granted)
	Name              string
	PreferredUsername string
	Picture           string
	UpdatedAt         *time.Time

	// Scope-gated email claims (include when "email" scope was granted)
	Email         string
	EmailVerified bool
}

IDTokenParams holds all data needed to generate an OIDC ID Token (OIDC Core 1.0 §2).

type LocalTokenProvider

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

LocalTokenProvider generates and validates JWT tokens locally

func NewLocalTokenProvider

func NewLocalTokenProvider(cfg *config.Config) *LocalTokenProvider

NewLocalTokenProvider creates a new local token provider

func (*LocalTokenProvider) GenerateClientCredentialsToken added in v0.12.0

func (p *LocalTokenProvider) GenerateClientCredentialsToken(
	ctx context.Context,
	userID, clientID, scopes string,
) (*Result, error)

GenerateClientCredentialsToken creates an access token for the client_credentials grant using its own configurable expiry (CLIENT_CREDENTIALS_TOKEN_EXPIRATION). The userID field carries the synthetic machine identity "client:<clientID>".

func (*LocalTokenProvider) GenerateIDToken added in v0.13.0

func (p *LocalTokenProvider) GenerateIDToken(params IDTokenParams) (string, error)

GenerateIDToken creates a signed HS256 JWT ID Token for the given params. ID tokens are not stored in the database; they are short-lived and non-revocable by design.

func (*LocalTokenProvider) GenerateRefreshToken

func (p *LocalTokenProvider) GenerateRefreshToken(
	ctx context.Context,
	userID, clientID, scopes string,
) (*Result, error)

GenerateRefreshToken creates a refresh token JWT with longer expiration

func (*LocalTokenProvider) GenerateToken

func (p *LocalTokenProvider) GenerateToken(
	ctx context.Context,
	userID, clientID, scopes string,
) (*Result, error)

GenerateToken creates a JWT token using local signing

func (*LocalTokenProvider) Name

func (p *LocalTokenProvider) Name() string

Name returns provider name for logging

func (*LocalTokenProvider) RefreshAccessToken

func (p *LocalTokenProvider) RefreshAccessToken(
	ctx context.Context,
	refreshToken string,
	enableRotation bool,
) (*RefreshResult, error)

RefreshAccessToken generates new access token (and optionally new refresh token in rotation mode)

func (*LocalTokenProvider) ValidateRefreshToken

func (p *LocalTokenProvider) ValidateRefreshToken(
	ctx context.Context,
	tokenString string,
) (*ValidationResult, error)

ValidateRefreshToken verifies a refresh token JWT

func (*LocalTokenProvider) ValidateToken

func (p *LocalTokenProvider) ValidateToken(
	ctx context.Context,
	tokenString string,
) (*ValidationResult, error)

ValidateToken verifies a JWT token using local verification

type RefreshResult

type RefreshResult struct {
	AccessToken  *Result // New access token (required)
	RefreshToken *Result // New refresh token (only present in rotation mode)
	Success      bool    // Operation success status
}

RefreshResult represents the result of a refresh token operation

type Result

type Result struct {
	TokenString string         // The JWT string
	TokenType   string         // "Bearer"
	ExpiresAt   time.Time      // Token expiration time
	Claims      map[string]any // Additional claims from provider
	Success     bool           // Generation success status
}

Result represents the result of token generation

type ValidationResult

type ValidationResult struct {
	Valid     bool
	UserID    string
	ClientID  string
	Scopes    string
	ExpiresAt time.Time
	Claims    map[string]any
}

ValidationResult represents the result of token verification

Jump to

Keyboard shortcuts

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