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 ¶
- Constants
- Variables
- func ValidID(id string) bool
- func ValidRecord(record Record) bool
- type Identity
- type IssueRequest
- type Manager
- func (m *Manager) Authenticate(ctx context.Context, credential authentication.Credential) (authentication.Principal, error)
- func (m *Manager) Issue(ctx context.Context, request IssueRequest) (string, Record, error)
- func (m *Manager) List(ctx context.Context, principalID string) ([]Record, error)
- func (m *Manager) Revoke(ctx context.Context, principalID string, id string) error
- type MemoryStore
- func (s *MemoryStore) Create(ctx context.Context, record Record) error
- func (s *MemoryStore) Get(ctx context.Context, id string) (Record, error)
- func (s *MemoryStore) ListByPrincipal(ctx context.Context, principalID string) ([]Record, error)
- func (s *MemoryStore) Revoke(ctx context.Context, id string, at time.Time) error
- func (s *MemoryStore) TouchLastUsed(ctx context.Context, id string, at time.Time) error
- type Options
- type Record
- type Store
Examples ¶
Constants ¶
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 ¶
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 ValidRecord ¶
ValidRecord reports whether record is well formed. Store implementations may use it to reject corrupted input.
Types ¶
type Identity ¶
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.
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 ¶
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.
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) ListByPrincipal ¶
ListByPrincipal returns the principal's records ordered by creation time and ID.
func (*MemoryStore) Revoke ¶
Revoke marks the record revoked at the given time unless already revoked.
func (*MemoryStore) TouchLastUsed ¶
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.
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.