Help us shape the future of Go! Take the 2026 Go Developer Survey

token

package
v0.17.0 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package token provides token management for principals. Tokens are issued to principals for authentication and authorization.

Index

Constants

View Source
const (
	// TokenBytes is the number of random bytes for token generation.
	TokenBytes = 32
	// DefaultAccessTTL is the access token lifetime when none is given.
	// A longer one is capped at accesschange.MaxAccessTokenLifetime.
	DefaultAccessTTL = accesschange.DefaultAccessTokenLifetime
)

Variables

View Source
var (
	// ErrInvalidAccessToken is returned for an unknown, revoked, or
	// expired access token.
	ErrInvalidAccessToken = errors.New("token: invalid access token")
	// ErrInvalidRefreshToken is returned for an unknown, spent, revoked,
	// or expired refresh token.
	ErrInvalidRefreshToken = errors.New("token: invalid refresh token")
	// ErrRefreshTokenReused is returned when an already-rotated refresh
	// token is presented again; the token family has been revoked.
	ErrRefreshTokenReused = fmt.Errorf("%w: reused, token family revoked", ErrInvalidRefreshToken)
	// ErrDPoPMismatch is returned when a DPoP-bound refresh token is
	// presented without its key.
	ErrDPoPMismatch = errors.New("token: DPoP binding mismatch")
	// ErrScopeNotGranted is returned when a refresh asks for a scope the
	// original grant did not include.
	ErrScopeNotGranted = errors.New("token: scope not in original grant")
)

Functions

This section is empty.

Types

type Capabilities

type Capabilities struct {
	CanAccessUI       bool `json:"can_access_ui"`
	CanManageProfile  bool `json:"can_manage_profile"`
	CanActOnBehalf    bool `json:"can_act_on_behalf"`
	CanDelegate       bool `json:"can_delegate"`
	RequiresApproval  bool `json:"requires_approval"`
	CanBypassRLS      bool `json:"can_bypass_rls"`
	CanRequestOffline bool `json:"can_request_offline"`
}

Capabilities defines what a token can do.

type DefaultService

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

DefaultService implements the Service interface.

func (*DefaultService) GetCapabilitiesForType

func (s *DefaultService) GetCapabilitiesForType(principalType principal.Type) Capabilities

GetCapabilitiesForType returns the default capabilities for a principal type.

func (*DefaultService) Issue

func (s *DefaultService) Issue(ctx context.Context, input IssueInput) (*IssuedToken, error)

Issue issues a new token pair in a new token family.

func (*DefaultService) ListForPrincipal

func (s *DefaultService) ListForPrincipal(ctx context.Context, principalID uuid.UUID) ([]*Token, error)

ListForPrincipal lists all active tokens for a principal.

func (*DefaultService) Refresh

func (s *DefaultService) Refresh(ctx context.Context, input RefreshInput) (*IssuedToken, error)

Refresh rotates a token pair: it spends the presented refresh token and issues a new pair in the same family, atomically, so a refresh token works once. The new refresh token expires when the family's first one did; refreshing never extends a session. Presenting a refresh token that was already rotated means it was copied, so the whole family is revoked and ErrRefreshTokenReused is returned.

func (*DefaultService) Revoke

func (s *DefaultService) Revoke(ctx context.Context, tokenID uuid.UUID, revokeFamily bool, reason string) error

Revoke revokes a token.

func (*DefaultService) RevokeAllForPrincipal

func (s *DefaultService) RevokeAllForPrincipal(ctx context.Context, principalID uuid.UUID, reason string) error

RevokeAllForPrincipal revokes all tokens for a principal.

func (*DefaultService) RevokeBySignature

func (s *DefaultService) RevokeBySignature(ctx context.Context, accessTokenSignature string, revokeFamily bool, reason string) error

RevokeBySignature revokes a token by its access token signature.

func (*DefaultService) Validate

func (s *DefaultService) Validate(ctx context.Context, accessToken string) (*Token, error)

Validate validates an access token and returns the token record.

type IssueInput

type IssueInput struct {
	PrincipalID     uuid.UUID
	PrincipalType   principal.Type
	IssuedByAppID   *uuid.UUID
	Scopes          []string
	Audience        []string
	Capabilities    map[string]bool
	DelegationChain []string
	DPoPJKT         string // DPoP JWK thumbprint for proof-of-possession
	SessionID       string
	AccessTTL       time.Duration
	RefreshTTL      time.Duration // 0 means no refresh token
	ClientIP        string
	UserAgent       string
	ParentTokenID   *uuid.UUID // For delegation
}

IssueInput contains fields for issuing a new token.

type IssuedToken

type IssuedToken struct {
	Token        *Token `json:"token"`
	AccessToken  string `json:"access_token"`  // JWT or opaque token
	RefreshToken string `json:"refresh_token"` // Optional
	TokenType    string `json:"token_type"`    // "Bearer"
	ExpiresIn    int    `json:"expires_in"`    // Seconds until access token expires
}

IssuedToken contains both the token record and the raw tokens.

type Option added in v0.14.0

type Option func(*DefaultService)

Option configures a DefaultService.

func WithAccessChangeSink added in v0.14.0

func WithAccessChangeSink(sink accesschange.Sink) Option

WithAccessChangeSink announces RevokeAllForPrincipal to sink after it commits (ADR-010). The access-change record is written whether or not a sink is set.

type RefreshInput

type RefreshInput struct {
	RefreshToken string   `json:"-"` //nolint:gosec // G117: field holds runtime token value, not a hardcoded secret
	Scopes       []string // Optional: narrow scopes
	DPoPJKT      string   // For DPoP binding continuity
	ClientIP     string
	UserAgent    string
}

RefreshInput contains fields for refreshing a token.

type Service

type Service interface {
	// Issue issues a new token pair.
	Issue(ctx context.Context, input IssueInput) (*IssuedToken, error)

	// Refresh refreshes a token using the refresh token.
	Refresh(ctx context.Context, input RefreshInput) (*IssuedToken, error)

	// Validate validates an access token and returns the token record.
	Validate(ctx context.Context, accessToken string) (*Token, error)

	// Revoke revokes a token.
	// If revokeFamily is true, all tokens in the same family are revoked.
	Revoke(ctx context.Context, tokenID uuid.UUID, revokeFamily bool, reason string) error

	// RevokeBySignature revokes a token by its access token signature.
	RevokeBySignature(ctx context.Context, accessTokenSignature string, revokeFamily bool, reason string) error

	// GetCapabilitiesForType returns the default capabilities for a principal type.
	GetCapabilitiesForType(principalType principal.Type) Capabilities

	// ListForPrincipal lists all active tokens for a principal.
	ListForPrincipal(ctx context.Context, principalID uuid.UUID) ([]*Token, error)

	// RevokeAllForPrincipal revokes all tokens for a principal.
	RevokeAllForPrincipal(ctx context.Context, principalID uuid.UUID, reason string) error
}

Service defines the business logic interface for tokens.

func NewService

func NewService(client *ent.Client, opts ...Option) Service

NewService creates a new TokenService.

type Token

type Token struct {
	ID               uuid.UUID       `json:"id"`
	PrincipalID      uuid.UUID       `json:"principal_id"`
	PrincipalType    principal.Type  `json:"principal_type"`
	IssuedByAppID    *uuid.UUID      `json:"issued_by_app_id,omitempty"`
	FamilyID         uuid.UUID       `json:"family_id"`
	ParentTokenID    *uuid.UUID      `json:"parent_token_id,omitempty"`
	Scopes           []string        `json:"scopes"`
	Audience         []string        `json:"audience,omitempty"`
	Capabilities     map[string]bool `json:"capabilities"`
	DelegationChain  []string        `json:"delegation_chain,omitempty"`
	DPoPJKT          string          `json:"dpop_jkt,omitempty"` // DPoP JWK thumbprint
	SessionID        string          `json:"session_id,omitempty"`
	AccessExpiresAt  time.Time       `json:"access_expires_at"`
	RefreshExpiresAt *time.Time      `json:"refresh_expires_at,omitempty"`
	Revoked          bool            `json:"revoked"`
	RevokedAt        *time.Time      `json:"revoked_at,omitempty"`
	RevokedReason    string          `json:"revoked_reason,omitempty"`
	ClientIP         string          `json:"client_ip,omitempty"`
	UserAgent        string          `json:"user_agent,omitempty"`
	LastUsedAt       *time.Time      `json:"last_used_at,omitempty"`
	CreatedAt        time.Time       `json:"created_at"`
}

Token represents a token record.

Jump to

Keyboard shortcuts

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