Documentation
¶
Overview ¶
Package authn authenticates requests and seeds the built-in principals (decision 0005): a user name and password, an access or reference token and a registry token each become a kernel.Principal, and a principal kept for work that outlives its request is rechecked against current state before that work acts for it. Passwords are Argon2id hashes in PHC string form, so the cost parameters travel with each hash and can be raised without breaking the hashes already stored.
Role ¶
access module, core layer: the authenticator. The request middleware in access/adapters/http and the access module's binding of the access/api Authenticator call it; other modules reach it only through access/api. It also evaluates a request's permissions once (Authorize), carries the principal and its decider in the context (WithAuthorized, DeciderFrom), and seeds the users, group, permissions and build-info repository a fresh instance starts with. The package imports the standard library, golang.org/x/crypto/argon2, the kernel, platform/settings, platform/tx (the seed's transaction) and platform/httpkit/apierror, the module's api, core/authz, core/model and core/port, and artifacts/api for the Repositories through which the seed creates the build-info repository.
Inputs ¶
- NewAuthenticator: the user store, the settings store (the anonymous access switch, basic authentication, the lock and expiry policies and the Access lock settings that suspension follows) and Options: the verified-password cache, the hash cost and concurrency, the TokenVerifier, the group store that a transient user's automatic groups come from, and the API restriction store.
- Basic, Token and ExpiredToken: the credentials a request presents.
- Current, CurrentRegistry and RestoreDownload: a principal verified earlier, or the reference a download envelope carries, with the token store.
- Authorize: authz.Sources and the principal.
- Seed and SeedHashed: a SeedStore (the users, groups, permissions, settings and transaction the seed writes in), the artifacts module's Repositories over the same unit of work, the admin password or its hash, and the time. Seeded needs only the settings.
Outputs ¶
- A kernel.Principal, or one of the kernel's credential sentinels (ErrBadCredentials, ErrAccountLocked, ErrPasswordExpired and ErrAPIRestricted) or the package's own (ErrBasicAuthDisabled, ErrLoginSuspended, ErrHashFormat and ErrInvalidToken).
- From Authorize, the principal as the evaluator decides it with its *authz.Decider, which WithAuthorized stores in a context and DeciderFrom reads back.
- Password hashes (HashPassword, HashPasswordWith) and their check (CheckPassword), and the stored policies with their defaults.
- The built-in principals, the build-info repository and the seed marker, written in one transaction (Seed).
Invariants ¶
- A credential reference never authenticates a new request: Current, CurrentRegistry and RestoreDownload only recheck a credential that Basic or Token verified, against the user, token, policy and anonymous access state now, and never keep, forward or verify a password or token again.
- An unknown user costs the same hash as a known one, so the time a wrong answer takes does not tell which user names exist.
- The seed writes everything or nothing, and an instance that loses the race to seed a shared database reports false, not an error.
References ¶
- Decision 0005: docs/research/decisions/0005-authentication-and-tokens.md.
- Decision 0006: docs/research/decisions/0006-authorization-native-permission-model.md (Authorize and the decider in the context).
- Decision 0019: docs/research/decisions/0019-human-authentication-tiers.md (local users and tokens first; the other tiers come later).
- Decision 0044: docs/research/decisions/0044-modular-monolith-migration.md.
- Research: docs/research/05-platform-identity-and-security-apis.md (the built-in principals) and docs/research/21-oidc-token-exchange.md (transient users).
- Target layout: docs/research/architecture-options/5-modular-monolith.md, line 277 (core/authn), lines 537 and 538 (its files) and line 986 (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: Basic authentication and the seeded principals (pull request 56), token authentication (pull request 95), the lock and expiry policies (pull request 97), a request's permissions evaluated once (pull request 101), the basic authentication switch (pull request 105), refresh with an expired access token (pull request 108) and the identities of OIDC exchanged tokens (pull request 145). Registry tokens came with the Docker registry (pull requests 246 and 305), and later changes aligned token expiry, transient users and the admin scope with 7.x (pull request 449) and added login suspension (pull request 470). P9 added the rechecks for work that outlives its request: Current (pull request 648), CurrentRegistry (pull request 664) and RestoreDownload (pull request 674); API restrictions came with retry safety and bounded API execution (pull request 905). Moved here in P9d, where the seed creates the build-info repository through the artifacts module's Repositories.
Testing ¶
- auth_test.go: TestMain lowers the hash cost for the package's tests; TestUnitHashAndCheck, TestUnitProductionHashParams, TestUnitHashParamsReachTheHashAndTheDummy, TestUnitCheckPasswordRejectsMalformedHashes, TestUnitRequire, TestUnitBasic, TestUnitBasicErrors, TestUnitAnonymousAllowed and TestUnitCacheBound.
- token_test.go: TestUnitTokenPrincipal, TestUnitExpiredToken, TestUnitEncryptedPasswordToken, TestUnitOIDCTokenIdentities, TestUnitTransientTokenScopes and TestUnitRegistryTokenPrincipal.
- policy_test.go: TestUnitPasswordExpired, TestUnitLockoutThroughBasic, TestUnitLockBeforeSuspensionAndPassword, TestUnitExpiryThroughBasic and TestUnitPolicyReadErrors.
- suspension_test.go: TestUnitSuspensionDelay, TestUnitSuspendedForMessage, TestUnitSuspensionThroughBasic, TestUnitSuspensionBeforeHashing, TestUnitSuspensionSettings, TestUnitSuspensionsBounded and TestUnitSuspensionsForgetStale.
- current_test.go, current_registry_test.go and download_test.go: TestUnitCurrentPrincipalRechecksIdentity, TestUnitCurrentRegistryKeepsGrantAndRechecksCredential, TestUnitDownloadCredentialRestoration and TestUnitDownloadCredentialRejectsUnverifiedAndMixedReferences.
- api_restriction_test.go: TestUnitAPIRestrictionCredentialsAndRecovery.
- username_test.go: TestUnitUsernamesFold and TestUnitUsernameLockFolds (logins, locks and restrictions name a user in any case, #1432).
- authorize_test.go and principal_test.go: TestUnitAuthorize, TestUnitDeciderFrom, TestUnitWithAuthorized and TestUnitDeciderSharedWithAccessAPI (one context key for this package and access/api).
- seed_test.go: TestUnitSeedInMemory, TestAccSeedSQLite, TestAccSeedPostgres, TestUnitSeedLosesARace and TestUnitSeedErrors, with a stand-in for the artifacts Repositories (internal/app's seed tests check the real one). The two acceptance tests seed the metadata store's SQLite and PostgreSQL stores; the PostgreSQL test needs Docker and skips without it.
The other tests run on the metadata store's in-memory store.
Index ¶
- Constants
- Variables
- func AccessLockSettings(ctx context.Context, settings platformsettings.SettingsStore) (model.AccessLockSettings, error)
- func Authorize(ctx context.Context, src authz.Sources, p kernel.Principal) (kernel.Principal, *authz.Decider, error)
- func BasicAuthEnabled(ctx context.Context, settings platformsettings.SettingsStore) (bool, error)
- func CheckAPIRestriction(ctx context.Context, restrictions port.APIRestrictionStore, user string, ...) error
- func CheckPassword(stored []byte, password string) (bool, error)
- func DeciderFrom(ctx context.Context) *authz.Decider
- func ExpirationPolicy(ctx context.Context, settings platformsettings.SettingsStore) (model.PasswordExpirationPolicy, error)
- func HashPassword(password string) ([]byte, error)
- func HashPasswordWith(p HashParams, password string) ([]byte, error)
- func LockPolicy(ctx context.Context, settings platformsettings.SettingsStore) (model.UserLockPolicy, error)
- func PasswordExpired(u model.User, p model.PasswordExpirationPolicy, now time.Time) bool
- func Seed(ctx context.Context, st SeedStore, repos artifactsapi.Repositories, ...) (bool, error)
- func SeedHashed(ctx context.Context, st SeedStore, repos artifactsapi.Repositories, ...) (bool, error)
- func Seeded(ctx context.Context, st interface{ ... }) (bool, error)
- func WithAPIRecovery(ctx context.Context) context.Context
- func WithAuthorized(ctx context.Context, p kernel.Principal, d *authz.Decider) context.Context
- func WithExpiredToken(ctx context.Context, r Refresher) context.Context
- type Authenticator
- func (a *Authenticator) AnonymousAllowed(ctx context.Context) (bool, error)
- func (a *Authenticator) Basic(ctx context.Context, name, password string) (kernel.Principal, error)
- func (a *Authenticator) Current(ctx context.Context, p kernel.Principal, tokens port.TokenStore) (kernel.Principal, error)
- func (a *Authenticator) CurrentRegistry(ctx context.Context, p kernel.Principal, tokens port.TokenStore) (kernel.Principal, error)
- func (a *Authenticator) ExpiredToken(ctx context.Context, raw string) (Refresher, bool)
- func (a *Authenticator) ForgetPolicies()
- func (a *Authenticator) RestoreDownload(ctx context.Context, name string, reference kernel.DownloadCredential, ...) (kernel.Principal, error)
- func (a *Authenticator) Token(ctx context.Context, raw, user string) (kernel.Principal, error)
- type ExpiredVerifier
- type HashParams
- type Options
- type Refresher
- type SeedStore
- type TokenVerifier
Constants ¶
const ( // DefaultCacheSize bounds the verified-credentials cache. An entry is a // 32-byte key and an expiry, so the bound costs well under a megabyte. DefaultCacheSize = 10_000 // DefaultCacheTTL is how long a verified password skips Argon2. The JFrog // CLI sends Basic credentials on every request, so without the cache a // large upload would pay 64 MiB and tens of milliseconds per call. DefaultCacheTTL = 5 * time.Minute )
Defaults for the zero Options fields.
const ( // DefaultLoginAttempts is how many failed logins lock an account while // the user lock policy is on. DefaultLoginAttempts = 5 // DefaultPasswordMaxAgeDays is how many days an internal password lasts // while the password expiration policy is on. DefaultPasswordMaxAgeDays = 60 )
The policies' defaults when nothing is stored, as Artifactory ships them.
const ( // AdminUser is the administrator the seed creates, with the password // Seed is given. AdminUser = "admin" // ReadersGroup is the group the seed creates, which every new user // joins automatically. ReadersGroup = "readers" // AnythingPermission grants ReadersGroup read on every repository. AnythingPermission = "Anything" // AnyRemotePermission covers every remote repository and grants no one // anything. Artifactory has shipped it without anonymous since 7.84.3, so // a request without credentials reaches remote content only through a // permission an administrator writes for anonymous. AnyRemotePermission = "Any Remote" )
Names of the built-in principals Artifactory ships (research 05).
Variables ¶
var ErrBasicAuthDisabled = apierror.New(http.StatusUnauthorized,
"Basic authentication with a password is disabled; use an access token")
ErrBasicAuthDisabled answers a user name and password while the platform accepts only tokens (basic_authentication_enabled is false).
var ErrHashFormat = errors.New("auth: unsupported password hash")
ErrHashFormat reports a stored password hash that is not an Argon2id PHC string this package can verify.
var ErrInvalidToken = errors.New("auth: invalid token")
ErrInvalidToken reports a token that does not verify: malformed, badly signed, expired, revoked, or of a subject that is not a user. Verifiers wrap it; the request answers kernel.ErrBadCredentials.
var ErrLoginSuspended = errors.New("auth: login temporarily suspended")
ErrLoginSuspended reports a Basic login refused because its user name is suspended. The error also carries the 403 the client gets.
Functions ¶
func AccessLockSettings ¶
func AccessLockSettings( ctx context.Context, settings platformsettings.SettingsStore, ) (model.AccessLockSettings, error)
AccessLockSettings returns the stored Access user lock settings, or model.DefaultAccessLockSettings.
func Authorize ¶
func Authorize( ctx context.Context, src authz.Sources, p kernel.Principal, ) (kernel.Principal, *authz.Decider, error)
Authorize evaluates p's permissions once for the request (decision 0006). It returns p with Admin and Groups set to what the evaluator decides (a token scope can remove the admin flag and narrow the groups, and an admin-privilege group makes a member an administrator) and the evaluator itself, which answers every permission question asked for p. A request stores the two with WithAuthorized, and its handlers reach the decider through DeciderFrom. On error it returns the zero kernel.Principal and a nil decider.
func BasicAuthEnabled ¶
func BasicAuthEnabled(ctx context.Context, settings platformsettings.SettingsStore) (bool, error)
BasicAuthEnabled reports whether user names and passwords are accepted over HTTP Basic. Unset means on, as Artifactory ships.
func CheckAPIRestriction ¶
func CheckAPIRestriction( ctx context.Context, restrictions port.APIRestrictionStore, user string, now time.Time, ) error
CheckAPIRestriction checks current persisted policy without a permission cache. Missing policy means unrestricted; backend failures fail closed. Restrictions are stored under folded user names, and user is folded to match: a token issued for BOB is held to bob's restriction.
func CheckPassword ¶
CheckPassword reports whether password matches the stored hash.
func DeciderFrom ¶
DeciderFrom returns the permission decider stored with ctx's principal, by WithAuthorized or accessapi.WithCaller, which handlers ask every permission question (decision 0006). It is nil when ctx carries no principal or kernel.WithPrincipal stored it, and when the stored decider is not the evaluator, such as a test's fake, so a caller evaluates the principal afresh. A context derived from ctx other than by kernel.WithPrincipal or WithAuthorized, such as one with a deadline, sees the same decider; one derived by either sees only what that call stored. The decider is bound to the call that stored the principal, not to the principal's value, so a decider can never answer for a principal another call stored.
func ExpirationPolicy ¶
func ExpirationPolicy( ctx context.Context, settings platformsettings.SettingsStore, ) (model.PasswordExpirationPolicy, error)
ExpirationPolicy returns the stored password expiration policy, or the default.
func HashPassword ¶
HashPassword returns the Argon2id hash of password in PHC form, with the production parameters.
func HashPasswordWith ¶
func HashPasswordWith(p HashParams, password string) ([]byte, error)
HashPasswordWith is HashPassword with the given parameters.
func LockPolicy ¶
func LockPolicy( ctx context.Context, settings platformsettings.SettingsStore, ) (model.UserLockPolicy, error)
LockPolicy returns the stored user lock policy, or the default.
func PasswordExpired ¶
PasswordExpired reports whether u must set a new password. An administrator's expiry applies whatever the policy; age counts only from a recorded change, so users whose password predates the record (the seeded admin of an older install) are not locked out by enabling it.
func Seed ¶
func Seed( ctx context.Context, st SeedStore, repos artifactsapi.Repositories, adminPassword string, now time.Time, ) (bool, error)
Seed creates, in one transaction, the admin user with adminPassword, the anonymous user, the readers group, the Anything and Any Remote permissions and the artifactory-build-info repository, then marks the store seeded. It reports whether this call seeded: false when the store already was, including when another instance sharing the database won a race to seed it first. The repository belongs to the artifacts module, so the seed creates it through repos, which must work over st: Create gets the transaction's context and joins the transaction as the other creates do.
func SeedHashed ¶
func SeedHashed( ctx context.Context, st SeedStore, repos artifactsapi.Repositories, adminHash []byte, now time.Time, ) (bool, error)
SeedHashed is Seed with the admin password already hashed (HashPassword or HashPasswordWith).
func WithAPIRecovery ¶
WithAPIRecovery permits credential verification for the narrowly mounted administrator recovery routes. Those routes must still call kernel.RequireAdmin; this context flag grants no identity or administrative authority.
func WithAuthorized ¶
WithAuthorized returns ctx carrying p and, for DeciderFrom, d, the decider Authorize returned with p. d is bound to this call: a context derived with a later kernel.WithPrincipal or WithAuthorized no longer sees it. It stores them with accessapi.WithCaller, so one context key serves both packages and accessapi.DeciderFrom sees d too; AsAPI keeps a nil d from becoming a typed nil there.
Types ¶
type Authenticator ¶
type Authenticator struct {
// contains filtered or unexported fields
}
Authenticator verifies credentials against the user store.
func NewAuthenticator ¶
func NewAuthenticator( users port.UserStore, settings settings.SettingsStore, o Options, ) (*Authenticator, error)
NewAuthenticator returns an Authenticator over users and settings.
func (*Authenticator) AnonymousAllowed ¶
func (a *Authenticator) AnonymousAllowed(ctx context.Context) (bool, error)
AnonymousAllowed reports whether requests without credentials act as the anonymous user. The setting is a JSON boolean; unset means off, as in Artifactory.
func (*Authenticator) Basic ¶
func (a *Authenticator) Basic( ctx context.Context, name, password string, ) (kernel.Principal, error)
Basic verifies a user name and password. Wrong credentials, an unknown or disabled user, and a user without an internal password all answer kernel.ErrBadCredentials alike; while basic authentication is switched off, every password answers ErrBasicAuthDisabled. A locked account answers kernel.ErrAccountLocked whatever the password. A correct but expired password answers kernel.ErrPasswordExpired with the principal, marked PasswordExpired. While the name is temporarily suspended after failed logins, every password answers ErrLoginSuspended (suspension.go).
The name is folded (model.FoldUsername) before anything else, so BOB logs in as bob, and a failed login as BOB counts toward bob's lock and suspension. RTFACT-29660 reports 7.55.13 counting TEST_user and test_user apart, against its own rule that user names are case-insensitive; that is not followed.
func (*Authenticator) Current ¶
func (a *Authenticator) Current( ctx context.Context, p kernel.Principal, tokens port.TokenStore, ) (kernel.Principal, error)
Current rechecks an authenticated request after a potentially slow remote read. It reads only local state, so publication can call it inside its transaction. No password or token value is retained, forwarded or verified a second time.
func (*Authenticator) CurrentRegistry ¶
func (a *Authenticator) CurrentRegistry( ctx context.Context, p kernel.Principal, tokens port.TokenStore, ) (kernel.Principal, error)
CurrentRegistry rechecks a verified registry credential without converting it into a general access token. Its original realm, grants, scope and expiry stay fixed; current user state and the parent credential can only remove access.
func (*Authenticator) ExpiredToken ¶
ExpiredToken verifies raw as an access token whatever its expiry, and whose user is still enabled. Only the refresh grant asks: the JFrog CLI refreshes with the access token it is replacing, by then often expired, as the Bearer credential (Access) or the access_token form field (legacy). This verifies identity only; the refresh transaction checks API restrictions before rotation, preserving a policy denial as 403.
func (*Authenticator) ForgetPolicies ¶
func (a *Authenticator) ForgetPolicies()
ForgetPolicies drops the cached policies, so a change made through this instance applies to its next login.
func (*Authenticator) RestoreDownload ¶
func (a *Authenticator) RestoreDownload( ctx context.Context, name string, reference kernel.DownloadCredential, tokens port.TokenStore, ) (kernel.Principal, error)
RestoreDownload rechecks a verified download envelope's original credential against current local state. It deliberately uses Current, preserving its scope, expiry, user status, password and anonymous-access fences.
func (*Authenticator) Token ¶
Token verifies a token presented as Bearer, as X-JFrog-Art-Api, or as the password of a Basic credential whose user name is user ("" for the first two). A Basic user name must name the token's subject (decision 0005). The subject must still be an enabled user: disabling a user disables their tokens.
type ExpiredVerifier ¶
type ExpiredVerifier interface {
// VerifyExpired is Verify for an access token, accepting one whose
// expiry has passed.
VerifyExpired(ctx context.Context, raw string) (model.Token, error)
}
ExpiredVerifier is a TokenVerifier that also verifies an access token whose only fault is its expiry. internal/access/core/token implements it.
type HashParams ¶
type HashParams struct {
// MemoryKiB is the memory each hash uses, in KiB.
MemoryKiB uint32
// Time is the number of passes over that memory.
Time uint32
// Threads is the number of lanes computed in parallel.
Threads uint8
}
HashParams are Argon2id's cost parameters. The zero value means the production parameters; the only other use is tests, which hash with tiny costs to stay fast. Nothing in configuration or on the command line can set them: verification reads the cost from each stored hash, so a cheap hash only ever comes from code that asked for one.
type Options ¶
type Options struct {
// CacheSize bounds how many verified passwords the cache holds; zero or
// less means DefaultCacheSize.
CacheSize int
// CacheTTL is how long a verified password skips the hash; zero or less
// means DefaultCacheTTL.
CacheTTL time.Duration
// Concurrency bounds the password hashes computed at once; zero means
// GOMAXPROCS. Each costs the hash's memory parameter, so without a bound
// a flood of wrong passwords could exhaust memory.
Concurrency int
// Now supplies the time; nil means time.Now.
Now func() time.Time
// Hash is the cost of the dummy hash checked for unknown users; the
// zero value means the production parameters. Tests set tiny costs.
Hash HashParams
// Tokens verifies access and reference tokens; nil refuses every token.
Tokens TokenVerifier
// Groups names the groups new users join automatically, which the
// transient user of a transient token joins (kernel.IdentityTransient);
// nil means none.
Groups port.GroupStore
// APIRestrictions gates newly authenticated calls and Current rechecks.
// Nil disables this policy for embedders; the application supplies it.
APIRestrictions port.APIRestrictionStore
}
Options configures NewAuthenticator.
type Refresher ¶
type Refresher struct {
// User is the name of the token's user.
User string
// TokenID is the id of the token the refresh replaces.
TokenID string
}
Refresher is the access token a refresh presents for the token it replaces, and that token's user.
type SeedStore ¶
type SeedStore interface {
tx.Runner
// Users holds the admin and anonymous users the seed creates.
Users() port.UserStore
// Groups holds the readers group the seed creates.
Groups() port.GroupStore
// Permissions holds the Anything and Any Remote permissions the seed
// creates.
Permissions() port.PermissionStore
// Settings holds the seeded marker.
Settings() settings.SettingsStore
}
SeedStore is what the seed writes: the users, the group and the permissions it creates, the settings that hold the seeded marker, and the transaction they are created in. The application passes its composite store. Every call joins the transaction ctx carries.
type TokenVerifier ¶
type TokenVerifier interface {
// Verify returns the stored record of the access or reference token
// raw. An error wrapping ErrInvalidToken means raw does not verify; any
// other means it could not be checked.
Verify(ctx context.Context, raw string) (model.Token, error)
}
TokenVerifier resolves an access token (a JWT) or a reference token to its stored record. internal/access/core/token implements it.