apitoken

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2026 License: Apache-2.0 Imports: 15 Imported by: ? 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.

Documentation

Overview

Package apitoken issues and authenticates long-lived personal and service API tokens of the form <prefix>_<id>_<secret>.

The ID is 128 random bits and the secret 256 random bits, both lowercase base32 without padding. Only a digest of the full token is stored: HMAC-SHA256 keyed with Options.Pepper when configured, otherwise plain SHA-256. Because the secret carries 256 bits of entropy, an unpeppered digest cannot be brute-forced; a pepper held outside the token database additionally prevents a leaked database from being used to confirm guessed or leaked tokens. Digests are compared in constant time.

Index

Examples

Constants

View Source
const (
	// CredentialKind is the dedicated Credential kind for API tokens.
	// Manager also accepts authentication.CredentialKindBearer.
	CredentialKind = "apitoken"
	// Method is recorded in Principal.Methods for API token authentication.
	Method = "apitoken"
	// ScopeTrait holds the token scopes in Principal.Traits.
	ScopeTrait = "scope"
	// TokenIDTrait holds the token ID in Principal.Traits.
	TokenIDTrait = "apitoken_id"
)

Variables

View Source
var ErrNotFound = errors.New("apitoken: not found")

ErrNotFound reports that no token record exists for the requested ID, or that it belongs to another principal.

Functions

func ValidID

func ValidID(id string) bool

ValidID reports whether id has the canonical API token ID form.

func ValidRecord

func ValidRecord(record Record) bool

ValidRecord reports whether record is well formed. Store implementations may use it to reject corrupted input.

Types

type Identity

type Identity struct {
	ID      string
	Issuer  string
	Subject string
	Traits  map[string][]string
}

Identity is the durable subset of an authentication.Principal that an API token acts for. Authentication rebuilds a Principal from it with fresh lifetime fields, the token scopes, and the token ID.

func IdentityFromPrincipal

func IdentityFromPrincipal(principal authentication.Principal) Identity

IdentityFromPrincipal extracts the durable identity of principal.

func (Identity) Clone

func (i Identity) Clone() Identity

Clone returns an independently owned identity.

type IssueRequest

type IssueRequest struct {
	// Principal is the identity the token acts for.
	Principal Identity
	// Name is a non-empty, caller-chosen label of at most 256 bytes.
	Name string
	// Scopes are unique RFC 6749 scope tokens (at most 64), carried in
	// Principal.Traits[ScopeTrait] on authentication. They are opaque to this
	// package.
	Scopes []string
	// TTL is the token lifetime; it must be positive and at most
	// Options.MaxTTL.
	TTL time.Duration
}

IssueRequest describes a new API token.

type Manager

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

Manager issues, lists, revokes, and authenticates API tokens. It is safe for concurrent use when its Store is.

Example
package main

import (
	"context"
	"fmt"
	"time"

	"github.com/justusschock/auth/authentication"
	"github.com/justusschock/auth/authentication/apitoken"
)

func main() {
	ctx := context.Background()
	manager, err := apitoken.NewManager(apitoken.Options{
		Store:  apitoken.NewMemoryStore(),
		Prefix: "app",
		Pepper: []byte("a-32-byte-or-longer-secret-pepper"),
	})
	if err != nil {
		panic(err)
	}

	// Issue returns the token exactly once; store only the record.
	token, record, err := manager.Issue(ctx, apitoken.IssueRequest{
		Principal: apitoken.Identity{ID: "https://id.example|alice", Issuer: "https://id.example", Subject: "alice"},
		Name:      "ci",
		Scopes:    []string{"runs:write"},
		TTL:       90 * 24 * time.Hour,
	})
	if err != nil {
		panic(err)
	}

	principal, err := manager.Authenticate(ctx, authentication.Credential{
		Kind:  authentication.CredentialKindBearer,
		Token: []byte(token),
	})
	fmt.Println(principal.Subject, principal.Traits[apitoken.ScopeTrait], err)

	_ = manager.Revoke(ctx, record.Principal.ID, record.ID)
	_, err = manager.Authenticate(ctx, authentication.Credential{
		Kind:  authentication.CredentialKindBearer,
		Token: []byte(token),
	})
	fmt.Println(err)
}
Output:
alice [runs:write] <nil>
authentication: unauthenticated

func NewManager

func NewManager(options Options) (*Manager, error)

NewManager validates options and returns a Manager. It returns authentication.ErrInvalidCredential for invalid options.

func (*Manager) Authenticate

func (m *Manager) Authenticate(ctx context.Context, credential authentication.Credential) (authentication.Principal, error)

Authenticate validates an API token credential. Credentials of other kinds or without this Manager's prefix return authentication.ErrUnsupportedCredential so the Manager composes with authentication.Chain.

func (*Manager) Issue

func (m *Manager) Issue(ctx context.Context, request IssueRequest) (string, Record, error)

Issue creates a token and returns it exactly once together with its record.

func (*Manager) List

func (m *Manager) List(ctx context.Context, principalID string) ([]Record, error)

List returns the principal's tokens, including expired and revoked ones.

func (*Manager) Revoke

func (m *Manager) Revoke(ctx context.Context, principalID string, id string) error

Revoke revokes the principal's token with id. It returns ErrNotFound when the token does not exist or belongs to another principal. Revoking an already revoked token succeeds.

type MemoryStore

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

MemoryStore is a process-local Store for tests and single-process callers. Distributed deployments should provide a durable implementation.

func NewMemoryStore

func NewMemoryStore() *MemoryStore

NewMemoryStore returns an empty memory-backed store.

func (*MemoryStore) Create

func (s *MemoryStore) Create(ctx context.Context, record Record) error

Create stores a new record if its ID is unused.

func (*MemoryStore) Get

func (s *MemoryStore) Get(ctx context.Context, id string) (Record, error)

Get returns the record with id.

func (*MemoryStore) ListByPrincipal

func (s *MemoryStore) ListByPrincipal(ctx context.Context, principalID string) ([]Record, error)

ListByPrincipal returns the principal's records ordered by creation time and ID.

func (*MemoryStore) Revoke

func (s *MemoryStore) Revoke(ctx context.Context, id string, at time.Time) error

Revoke marks the record revoked at the given time unless already revoked.

func (*MemoryStore) TouchLastUsed

func (s *MemoryStore) TouchLastUsed(ctx context.Context, id string, at time.Time) error

TouchLastUsed advances the record's last-used time.

type Options

type Options struct {
	// Store persists token records. Required.
	Store Store
	// Prefix identifies tokens of this Manager, for example "app". It must be
	// 2-16 characters of [a-z0-9] starting with a letter.
	Prefix string
	// Pepper optionally keys token digests with HMAC-SHA256. When set it must
	// be 32-1024 bytes and stay stable; rotating it invalidates every token.
	Pepper []byte
	// MaxTTL bounds IssueRequest.TTL. Defaults to 365 days.
	MaxTTL time.Duration
	// LastUsedInterval throttles TouchLastUsed writes per token. Defaults to
	// one minute; a negative value disables last-used tracking.
	LastUsedInterval time.Duration
	// Random supplies token entropy. Defaults to crypto/rand.Reader; any
	// replacement must be cryptographically secure.
	Random io.Reader
	// Clock returns the current time used for issue, expiry, revocation and
	// last-used timestamps; its result is converted to UTC. Defaults to
	// time.Now.
	Clock func() time.Time
}

Options configures a Manager.

type Record

type Record struct {
	ID         string
	Digest     [32]byte
	Principal  Identity
	Name       string
	Scopes     []string
	CreatedAt  time.Time
	ExpiresAt  time.Time
	LastUsedAt time.Time
	RevokedAt  time.Time
}

Record is the durable state of one API token. Digest is the keyed hash of the full token (see Options.Pepper); the raw token is never stored. Records returned by Manager have a zero Digest.

func (Record) Clone

func (r Record) Clone() Record

Clone returns an independently owned record.

func (Record) Revoked

func (r Record) Revoked() bool

Revoked reports whether the token has been revoked.

type Store

type Store interface {
	Create(context.Context, Record) error
	Get(ctx context.Context, id string) (Record, error)
	ListByPrincipal(ctx context.Context, principalID string) ([]Record, error)
	Revoke(ctx context.Context, id string, at time.Time) error
	TouchLastUsed(ctx context.Context, id string, at time.Time) error
}

Store persists API token records. Implementations must return ErrNotFound for unknown IDs and authentication.ErrReplay when Create reuses an ID. Revoke must keep the first revocation time when called repeatedly.

Jump to

Keyboard shortcuts

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