token

package
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Nov 16, 2026 License: MIT Imports: 26 Imported by: 0

Documentation

Overview

Package token issues, refreshes, verifies and revokes Access tokens (decision 0005): RS256 JWTs signed with a per-instance key, with the reference and refresh tokens that go with them, and the short-lived registry tokens of the Docker token flow. Only digests of tokens are stored; the store record (token_id, subject, scope, expiry) is what revocation removes.

Role

access module, core layer: the token service. The access module's binding of the access/api Tokens, the token API handlers in access/adapters/http and the OIDC exchange call it, and the authenticator verifies tokens through it as its authn.TokenVerifier; other modules reach it only through access/api. The package imports the standard library, the kernel, platform/instance, platform/settings and platform/tx, and the module's api, core/authn (ErrInvalidToken and the API restriction check), core/model and core/port.

Inputs

  • New: a Store, which the metadata store satisfies, and Options (the clock and the RSA key size). The instance identity must exist.
  • Issue: a Request; IssueRegistry: a RegistryRequest.
  • Refresh and RefreshAs: a refresh token, and for RefreshAs the user and token it must belong to (RefreshCheck).
  • Verify and VerifyExpired: a token as a client presents it.
  • Revoke: a token id; RevokeValue: a token as a client presents it.
  • EncryptedPassword: a user name. Rotate: nothing.

Outputs

  • Issued: the stored record, the token's secrets and its lifetime in seconds. Only an encrypted password's reference token can be shown again (EncryptedPassword); the other secrets exist only in the reply.
  • model.Token, the record a token verifies to, or an error wrapping authn.ErrInvalidToken.
  • ErrInvalidRequest, ErrNeverExpiresAdminOnly and ErrRefreshOtherUser for a refused request, and accessapi.ErrNotRevocable for a token too short-lived to revoke.
  • Signing keys and token records in the store; Issuer, the iss of this instance's tokens.

Invariants

  • A token stored without a purpose leaves only digests of its secrets in the store; an encrypted password's reference token is kept sealed so that it can be shown again.
  • A token verifies only while its record exists, so a revoked token fails at once. A registry token has no record: its short life, its grants, its parent token and its user's current permissions bound it.
  • A refresh revokes the token it replaces in the transaction that issues the new one.
  • After Rotate, the keys it replaces keep verifying until the latest expiry of the tokens stored then, so no token is refused early.

References

  • Decision 0005: docs/research/decisions/0005-authentication-and-tokens.md.
  • Decision 0017: docs/research/decisions/0017-sealed-columns-and-master-key.md (signing keys and an encrypted password's reference token are sealed at rest).
  • Decision 0023: docs/research/decisions/0023-release-bundles-and-distribution.md (release-bundle signing keys share the key store).
  • Decision 0044: docs/research/decisions/0044-modular-monolith-migration.md ("Names the migration introduces", which lists Store).
  • Target layout: docs/research/architecture-options/5-modular-monolith.md, line 278 (core/token), line 539 (its files) and line 989 (the package mapping row).
  • Plan: docs/implementation/plan.md#p4-identity-and-authorization and #p9d-modular-monolith-migration, epic ACC (https://github.com/weaveplatform/artifactweave/issues/940).
  • https://github.com/weaveplatform/artifactweave/issues/1064

Status

Implemented P4: access tokens, reference and refresh tokens, revocation and key rotation (pull request 95), refresh with an expired access token and the encrypted password (pull request 108), and OIDC exchanged identities (pull request 145). Registry tokens came with the Docker registry (pull requests 246 and 305), and later changes aligned expiry, revocation and transient users with 7.x (pull requests 449 and 486). API restrictions on issuance and refresh came with retry safety and bounded API execution (pull request 905). Moved here in P9d, where New takes Store.

Testing

  • token_test.go: TestUnitIssueAndVerify, TestUnitIssueRefuses, TestUnitTamperedTokens, TestUnitExpiryAndTouch, TestUnitRevoke, TestUnitRefresh, TestUnitRestrictionPreservesRefreshCredential, TestUnitNotAfterCapsTheLifetime, TestUnitRefreshKeepsIdentity, TestUnitVerifyExpired, TestUnitRefreshAs, TestUnitEncryptedPassword, TestUnitEncryptedPasswordRace, TestUnitRotation, TestUnitSharedStore (a second service on the same store reuses the key and verifies the first one's tokens), TestUnitNewNeedsIdentity and TestUnitReferenceForm; TestUnitCLIDecodesThePayload and TestUnitCLISafeProperty read a token as the JFrog CLI does.
  • registry_test.go: TestUnitIssueRegistry, TestUnitIssueRegistryRefuses, TestUnitRegistryRecordRefuses, TestUnitIssueRegistryKeepsScopeAndIdentity, TestUnitRegistryTokenEndsWithItsParent and TestUnitRegistryTokenParentUnreadable.
  • fault_test.go: TestUnitStoreFailures, TestUnitBadStoredKeys and TestUnitRecordMismatches.
  • username_test.go: TestUnitRefreshAsFoldsUsername (a refresh's user matches the token's in any case, #1432).
  • accessapi_test.go: compiles only while Request and RegistryRequest convert to and from their access/api counterparts.

The tests run on the metadata store's in-memory store.

Index

Constants

View Source
const (
	// DefaultAudience is the audience Access gives a token issued without one.
	DefaultAudience = "*@*"
)
View Source
const (

	// DefaultKeyBits is the RSA key size.
	DefaultKeyBits = 2048
)

Variables

View Source
var (
	// ErrInvalidRequest reports an issue request the service refuses.
	ErrInvalidRequest = errors.New("token: invalid token request")
	// ErrNeverExpiresAdminOnly refuses a token that never expires to a
	// caller who is not an administrator. It wraps ErrInvalidRequest, which
	// the OIDC exchange answers 400; the token API tests for it first and
	// answers 403, as createtoken documents a refused expires_in.
	ErrNeverExpiresAdminOnly = fmt.Errorf(
		"%w: only an administrator may issue a token that never expires",
		ErrInvalidRequest,
	)
	// ErrRefreshOtherUser refuses a refresh token of another user than the
	// one refreshing: "The authenticated user must match the user of the
	// access token being refreshed" (createtoken.json, which answers 403).
	ErrRefreshOtherUser = errors.New("token: the refresh token belongs to another user")
)

Functions

This section is empty.

Types

type Issued

type Issued struct {
	// Record is what was stored: the token's id, subject, scope, lifetime
	// and digests.
	Record model.Token
	// AccessToken is the signed JWT.
	AccessToken string
	// RefreshToken is set when the request asked for a refreshable token.
	RefreshToken string
	// ReferenceToken is set when the request asked for one or gave a
	// purpose.
	ReferenceToken string
	// ExpiresIn is the lifetime in seconds; zero means never.
	ExpiresIn int64
}

Issued is a new token and its secrets, which are never stored and so cannot be shown again.

type Options

type Options struct {
	// Now supplies the time; nil means time.Now.
	Now func() time.Time
	// KeyBits is the RSA key size; zero means DefaultKeyBits. Only tests set
	// it, to keep key generation cheap.
	KeyBits int
}

Options configures New. Zero values mean the defaults.

type RefreshCheck

type RefreshCheck struct {
	// Username, when set, must be the refreshed token's user, in any case,
	// or the refresh fails with ErrRefreshOtherUser.
	Username string
	// TokenID, when set, must be the refreshed token's id, or the refresh
	// fails as an invalid refresh token: the caller presented that token as
	// its credential, and it must not vouch for refreshing another.
	TokenID string
}

RefreshCheck is what a refresh must match beyond a valid refresh token.

type RegistryRequest

type RegistryRequest struct {
	// Username names the token's user, as Request's does.
	Username string
	// ExpiresIn is the lifetime; it must be positive, and at most
	// accessapi.RegistryTokenExpiry.
	ExpiresIn time.Duration
	// Access is what the token grants, which its registry claim carries.
	Access kernel.RegistryAccess
	// Scope is the scope of the credential that obtained the token, which
	// the token keeps so it never acts more broadly; it defaults to
	// applied-permissions/user, a password's.
	Scope kernel.Scope
	// Identity is that credential's identity when it came from an OIDC
	// exchange, so the token resolves to the same transient or synthetic
	// user it does.
	Identity kernel.TokenIdentity
	// Parent is the id of the stored token that obtained it, empty for a
	// password or anonymous caller. The token is refused once the parent is
	// revoked.
	Parent string
}

RegistryRequest asks for a registry token (decision 0005).

type Request

type Request struct {
	// Username names the token's user, the subject's last part; it may not
	// be empty or contain a slash.
	Username string
	// Scope defaults to applied-permissions/user.
	Scope kernel.Scope
	// ExpiresIn defaults to token.default_expiry (model.DefaultTokenExpiry
	// when unset); zero means never and needs ByAdmin.
	ExpiresIn *time.Duration
	// Refreshable also issues a refresh token, and makes the token
	// revocable.
	Refreshable bool
	// ForceRevocable makes the token revocable whatever its lifetime;
	// without it, one that expires within model.DefaultRevocableThreshold
	// and is not refreshable is not revocable (model.Revocable).
	ForceRevocable bool
	// Audience defaults to DefaultAudience.
	Audience string
	// Description is stored with the token and returned with it.
	Description string
	// ProjectKey is stored with the token: the project it was issued for,
	// empty for none.
	ProjectKey string
	// IncludeReference also issues a reference token.
	IncludeReference bool
	// ByAdmin is whether the caller is an administrator.
	ByAdmin bool
	// Purpose marks a token its user holds at most one of
	// (model.TokenPurposeEncryptedPassword). Such a token always has a
	// reference token, and keeps it sealed so it can be shown again.
	Purpose string
	// Identity is how the token's subject resolves to a user. An OIDC token
	// exchange, and an administrator minting for a name that is no stored
	// user, issue a token for a user who need not be stored.
	Identity kernel.TokenIdentity
	// NotAfter, when set, is the latest the token may expire; a longer or
	// unending lifetime is cut to it. A transient user's token for itself
	// sets it to the expiry of the token that minted it: the user exists
	// only through that token, so a token outliving it would outlast the
	// 24 hours an OIDC mapping allows.
	NotAfter time.Time
}

Request asks for a token for a user.

type Service

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

Service issues and verifies tokens over a store.

func New

func New(ctx context.Context, st Store, o Options) (*Service, error)

New returns a Service. The instance identity must exist: the issuer is jfac@<the instance's id>. The first signing key is created when there is none.

func (*Service) EncryptedPassword

func (s *Service) EncryptedPassword(ctx context.Context, username string) (string, error)

EncryptedPassword returns the user's encrypted password: the reference token of their model.TokenPurposeEncryptedPassword token, which never expires. A user holds at most one, created on first use and shown again after, so every client given it keeps working until the password changes and the identity service revokes it.

func (*Service) Issue

func (s *Service) Issue(ctx context.Context, r Request) (Issued, error)

Issue creates a token.

func (*Service) IssueRegistry

func (s *Service) IssueRegistry(_ context.Context, r RegistryRequest) (Issued, error)

IssueRegistry signs a registry token: an access token with the user's applied permissions whose registry claim carries what it grants. Nothing stores it, as Artifactory stores no token below its persistence threshold, so it cannot be listed or revoked; its short life, the grants and the user's current permissions bound it instead (Verify).

func (*Service) Issuer

func (s *Service) Issuer() string

Issuer is this instance's Access service id, the iss of its tokens.

func (*Service) Refresh

func (s *Service) Refresh(ctx context.Context, refreshToken string) (Issued, error)

Refresh exchanges a refresh token for a new token with the same subject, scope, lifetime and options, and revokes the old one. A refresh token stays usable for accessapi.DefaultRefreshGrace after its token expires.

func (*Service) RefreshAs

func (s *Service) RefreshAs(
	ctx context.Context,
	refreshToken string,
	c RefreshCheck,
) (Issued, error)

RefreshAs is Refresh for a refresh token that must pass c. The user is checked before the token, so another user's refresh token is ErrRefreshOtherUser whichever token the caller presented.

func (*Service) Revoke

func (s *Service) Revoke(ctx context.Context, id string) error

Revoke revokes the token with id.

func (*Service) RevokeValue

func (s *Service) RevokeValue(ctx context.Context, raw string) error

RevokeValue revokes the token whose access or reference token is raw.

func (*Service) Rotate

func (s *Service) Rotate(ctx context.Context) error

Rotate makes a new signing key active. The keys it replaces keep verifying until the latest expiry of the tokens stored now, or for ever when one of them never expires, so no token issued before the rotation is refused early.

func (*Service) Verify

func (s *Service) Verify(ctx context.Context, raw string) (model.Token, error)

Verify resolves an access token (a JWT) or a reference token to its record. A token that is malformed, badly signed, signed by an unknown or retired key, expired, or revoked (no record) fails with an error wrapping authn.ErrInvalidToken.

func (*Service) VerifyExpired

func (s *Service) VerifyExpired(ctx context.Context, raw string) (model.Token, error)

VerifyExpired resolves an access token (a JWT) as Verify does, but accepts one whose only fault is its expiry. Signature, key, revocation and subject are all still checked; a reference token always fails. It serves only the refresh grant, which the JFrog CLI sends with the access token it is replacing, by then often expired. The record outlives its expiry for accessapi.DefaultRefreshGrace (the gc keeps it), which bounds how long after expiry this succeeds.

type Store

type Store interface {
	tx.Runner
	// Instance holds the instance identity, whose id the issuer names.
	Instance() instance.InstanceStore
	// Settings holds token.default_expiry and the signing key state.
	Settings() settings.SettingsStore
	// Tokens holds the token records, which keep digests of the tokens,
	// never the tokens themselves.
	Tokens() port.TokenStore
	// Keys holds the signing keys.
	Keys() port.KeyStore
	// APIRestrictions holds the API restrictions that issuance and refresh
	// check.
	APIRestrictions() port.APIRestrictionStore
}

Store is what the service needs from persistence: the instance identity its issuer names, the settings that hold token.default_expiry and the signing key state, the token records and signing keys, the API restrictions that issuance and refresh check, and the unit of work a refresh runs in. The metadata store satisfies it, so the composition root passes its store as it is.

Jump to

Keyboard shortcuts

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