Documentation
¶
Overview ¶
Package api is the access module's published surface: the permission vocabulary, signing key pairs and certificates, the subject and repository that a permission question names, the helpers that recognise a token by its shape, the contracts through which other modules ask access to verify credentials, evaluate and decide permissions, issue and revoke tokens, and read keys, users, API restrictions, projects, permission grants and the anonymous access setting, and the context accessors that carry a request's principal together with its permission decider.
Role ¶
access module, api layer. Other modules reach access only through this package, and it imports only kernel and the standard library (decision 0044, dependency rules 5 and 6), so it declares its own types. Artifacts code uses the vocabulary, Keypair, Certificate, Repo and Subject heavily, and an api package cannot import access core, so they are declared here rather than in the core packages that evaluate them. The contracts are today's calls from other modules into access, which is wider than the target layout's api: Restrictions, Projects, Grants and AnonymousAccess are added to it, Authenticator rechecks credentials as well as verifying them, and Authorizer evaluates a principal once for a request and a subject that no request authenticated, besides the target layout's For. The decider travels in the request's context, bound to the principal's entry, rather than in the principal (decision 0044, "Composition and HTTP"), so kernel.Principal stays a plain value.
Inputs ¶
None: the package holds values, pure functions, interfaces and the context accessors, which read and write only the context they are given. The access module implements the interfaces: the evaluator's *Decider in access/core/authz satisfies Decider, and its AsAPI and FromAPI convert between the two, AsAPI never returning a typed nil; the module root, package access, binds every contract into the API that its New returns, and accessapitest below this package fakes each contract for other modules' tests.
Outputs ¶
- The permission vocabulary: ResourceType and its constants, the special targets (TargetAny, TargetAnyLocal, TargetAnyRemote and TargetAnyDistribution) with BuildInfoRepository and ReleaseBundlesRepository, and Actions with its constants. AccessNames, LegacyNames and Letters spell a set of actions in the three wire forms; ParseAccessActions, ParseLegacyActions and ParseLetters read them back and refuse an unknown name with ErrUnknownAction.
- Keypair, of a KeypairType, and Certificate: the signing key pairs and the client certificates of remote repositories.
- Subject, who a request acts as, and Repo, the repository a permission target names.
- Token shapes: IsReferenceToken and LooksLikeToken tell a token from a password; ErrNotRevocable refuses to revoke a short-lived token.
- The user name rule: FoldUsername is the lower-case spelling a user name is stored and matched in, and SameUsername compares two names by it, so a module that checks a name a client sent against the request's principal matches it as the authenticator did.
- Authenticator: verifying a password or a token, the anonymous access switch, and rechecking a verified credential against current state (Current, CurrentRegistry and RestoreDownload).
- Decider: the permission questions about one request's subject. RepoVisibility, an intersection of RepoSets, is its VisibleRepos answer: the repositories IsRepoVisible admits, described for a store's filter.
- Basic and Bearer credentials as 7.x reads them: BasicCredentials decodes an Authorization value, IgnoredAuthorization reports the Basic values that carry no credential at all, BearerToken reads the token of a Bearer value as the props filter and RequestUtils read it, and Blank is Java's isBlank, which 7.x applies to those values.
- API keys as 7.x reads them: APIKey is the key a request sends, X-JFrog-Art-Api unless it is blank and otherwise X-Api-Key whenever it is sent, which authenticates the request whatever its Authorization header says; APIKeySent reports a key header that is not blank, for which a refusal answers 403.
- Authorizer: evaluating a principal's permissions once for a request (Authorize), for a principal the request did not authorise (For), and for a subject no request authenticated (Decide). SubjectOf is the subject an evaluation starts from for a principal.
- The request's caller: WithCaller stores a principal and its decider in a context, WithDecider binds a decider to the principal a context already carries, and DeciderFrom reads it back.
- Tokens, with TokenRequest, RegistryTokenRequest and IssuedToken: issuing, revoking and clearing access tokens, and a user's encrypted password. DefaultRefreshGrace and RegistryTokenExpiry are the token lifetimes other modules apply: how long a token record outlives its expiry, and a registry token's lifetime.
- Keys: reading key pairs and certificates.
- Identity, with UserInfo and its Enabled rule: reading user accounts and the groups new users join.
- Restrictions: checking a user's temporary API restriction.
- Projects: reading project environments, membership and existence. EnvironmentDev, EnvironmentProd and BuiltinEnvironments are the built-in environments, which are not stored.
- Grants, with PathPair and ErrScanLimit: who holds what on an item, and whether moving content changes who may reach it.
- AnonymousAccess: reading and switching the anonymous access setting.
- Settings: the access options other modules read.
- API: one implementation of each contract, as the module publishes them, with the Settings.
Invariants ¶
- Error texts are observable in API responses and logs, so they stay byte-identical: "unknown permission action" and "token: token is not revocable".
- Actions marshals to the list of its Access names, such as ["READ","WRITE"], which stored permission documents hold; the JSON stays byte-identical.
- Keypair and Certificate never serialise a private key or passphrase (json:"-"); the stores seal them at rest (decision 0017).
- A Decider answers exactly as the access module's evaluator does, and a token scope only removes actions (decision 0006). VisibleRepos().Has agrees with IsRepoVisible on every stored repository, so a listing that filters in its store shows what one that asked about each repository would.
- A decider answers only for the WithPrincipal call it was bound to (kernel.PrincipalBinding), never for a principal that another call stored, even one of equal value: a context derived with a later kernel.WithPrincipal sees no decider, and one derived in any other way sees the same one. Comparing bindings is safe because PrincipalBinding returns the pointer that WithPrincipal stored.
- WithDecider never stores a typed nil: a nil decider, or one holding a nil pointer, is stored as none, so DeciderFrom never returns a decider that is nil inside. access/core/authn's WithAuthorized and DeciderFrom use these same accessors, so a decider stored through either package is visible through both.
- TokenRequest and RegistryTokenRequest carry every field of the token service's requests, in the same order and of the same types, so the module converts them and issuance keeps the rules of decision 0005.
- Every contract call that reads or writes a store uses the caller's context, so a call inside a store transaction takes part in it, and the store's sentinels, such as kernel.ErrNotFound, reach the caller for errors.Is.
References ¶
- Decision 0044: docs/research/decisions/0044-modular-monolith-migration.md, "Public types and published api surface", "Composition and HTTP" (the per-request decider bound through kernel.PrincipalBinding) and "Names the migration introduces".
- Target layout: docs/research/architecture-options/5-modular-monolith.md, "Full package tree", lines 258 to 272, and "Access and identity", lines 529 to 574 ("Authorizer.For ... once per operation" at line 568).
- Decision 0005: docs/research/decisions/0005-authentication-and-tokens.md (reference tokens, tokens sent as a Basic password, revocable tokens, registry tokens, and the 401 and 403 split).
- Decision 0006: docs/research/decisions/0006-authorization-native-permission-model.md (the permission model, its three wire forms and token scopes; "Once per request", line 169: the middleware's single evaluation).
- Decision 0043: docs/research/decisions/0043-api-reliability.md (Current refreshes the credential a replay rechecks, and a restricted user's rechecks answer 403).
- Decision 0013: docs/research/decisions/0013-projects-and-environments.md.
- Decision 0017: docs/research/decisions/0017-sealed-columns-and-master-key.md.
- Research 05: docs/research/05-platform-identity-and-security-apis.md, "Permissions v2", "Access tokens v1" and "Reference tokens", and its note on user name case (#1432).
- Plan: docs/implementation/plan.md#p9d-modular-monolith-migration, epic ACC (https://github.com/weaveplatform/artifactweave/issues/940), and #p4-identity-and-authorization.
- https://github.com/weaveplatform/artifactweave/issues/963
Status ¶
Implemented P4 to P9c and moved here in P9d: the vocabulary, Keypair, Certificate, Subject, Repo, the token shapes and SubjectOf. Added in P9d: the contracts Authenticator, Authorizer, Decider, Tokens, Keys, Identity, Restrictions, Projects, Grants and AnonymousAccess, the Settings value, the API aggregate, and the context accessors WithCaller, WithDecider and DeciderFrom. Added by #1432: FoldUsername and SameUsername, the user name rule that access/core/model applies. Added by #1408: RepoSet, RepoVisibility and Decider.VisibleRepos. The target layout's hooks.go, with the token gate (P17), and events.go, with the access events (P11), are not created yet.
Testing ¶
- TestUnitActionsSpellings, TestUnitActionsJSON: the three spellings of every action, case-insensitive Access names, ErrUnknownAction, and the JSON form.
- TestUnitIsReferenceToken, TestUnitLooksLikeToken: the reference-token form and how a Basic password is told apart from a token.
- TestUnitUserInfoEnabled: which account statuses may act.
- TestUnitFoldUsername: user names fold to lower case and match in any case, as 7.x matches them.
- TestUnitSubjectOf: the subject of a password, a token, a token with an empty scope, a groups-scoped token and the anonymous principal, as the evaluator has always started from it.
- TestUnitRepoVisibilityHas: a set holds every repository, its classes' and its keys', and a visibility the intersection of its sets.
- TestUnitDeciderContext: a decider answers for the WithPrincipal call it was bound to, through derived contexts and never after a later WithPrincipal; a nil or typed-nil decider hides an outer one. access/core/authn's TestUnitDeciderSharedWithAccessAPI checks that its accessors share the context key.
- TestUnitBasicCredentials, TestUnitBearerToken, TestUnitBlank: which Authorization values 7.x reads as Basic or Bearer credentials, which it reads no credential from, blank as Java's isBlank tells it, and the user, secret or token it reads.
- TestUnitAPIKey: which key header is read, the first line of it, a blank X-JFrog-Art-Api giving way to X-Api-Key, an X-Api-Key sent empty read as a key, and which requests sent a key that is not blank.
Index ¶
- Constants
- Variables
- func APIKey(h http.Header) (string, bool)
- func APIKeySent(h http.Header) bool
- func BasicCredentials(value string) (user, secret string, ok bool)
- func BearerToken(value string) (string, bool)
- func Blank(s string) bool
- func FoldUsername(name string) string
- func IgnoredAuthorization(value string) bool
- func IsReferenceToken(s string) bool
- func LooksLikeToken(s string) bool
- func SameUsername(a, b string) bool
- func WithCaller(ctx context.Context, p kernel.Principal, d Decider) context.Context
- func WithDecider(ctx context.Context, d Decider) context.Context
- type API
- type Actions
- type AnonymousAccess
- type Authenticator
- type Authorizer
- type Certificate
- type Decider
- type Grants
- type Identity
- type IssuedToken
- type Keypair
- type KeypairType
- type Keys
- type PathPair
- type Projects
- type RegistryTokenRequest
- type Repo
- type RepoSet
- type RepoVisibility
- type ResourceType
- type Restrictions
- type Settings
- type Subject
- type TokenRequest
- type Tokens
- type UserInfo
Constants ¶
const ( TargetAny = "ANY" TargetAnyLocal = "ANY LOCAL" TargetAnyRemote = "ANY REMOTE" TargetAnyDistribution = "ANY DISTRIBUTION" // BuildInfoRepository is the fixed target of the legacy build section. BuildInfoRepository = "artifactory-build-info" // ReleaseBundlesRepository is the default target of the legacy release // bundle section, the default release bundle source repository. ReleaseBundlesRepository = "release-bundles" )
Special targets. A target is otherwise a repository key (or, for builds, the build-info repository).
const ( EnvironmentDev = "DEV" EnvironmentProd = "PROD" )
The built-in environments. They are not stored: they cannot be renamed or deleted, and a repository belongs to DEV unless told otherwise.
const ( // DefaultRefreshGrace is how long after a token expires its refresh // token is still accepted, so its record is kept that long. DefaultRefreshGrace = 24 * time.Hour // RegistryTokenExpiry is a registry token's lifetime, shortened to the // remaining life of the credential that obtained it. RegistryTokenExpiry = time.Hour )
The token lifetimes that other modules apply to the tokens access issues (decision 0005).
Variables ¶
var BuiltinEnvironments = []string{EnvironmentDev, EnvironmentProd}
BuiltinEnvironments are the global environments every instance has.
var ErrNotRevocable = errors.New("token: token is not revocable")
ErrNotRevocable refuses to revoke a token shorter than the revocable threshold that was neither forced revocable nor refreshable.
var ErrScanLimit = errors.New("access: permission scan limit exceeded")
ErrScanLimit reports a permission scan that found more permissions than the caller's limit. The caller refuses its operation rather than act on a partial answer.
var ErrUnknownAction = errors.New("unknown permission action")
ErrUnknownAction reports an action name or letter no wire form defines.
Functions ¶
func APIKey ¶
APIKey returns the API key a request sends as 7.x reads it, reporting whether it sends one: X-JFrog-Art-Api unless it is blank, and otherwise X-Api-Key whenever it is sent, even empty (AuthenticationFilterUtils.getApiKeyTokenKeyValue, 7.161.26). The props filter that reads it comes before the Basic filter in the chain (AuthenticationFilterListSorter) and accepts every request that sends a key (PropsAuthenticationFilter.acceptFilter), so such a request is authenticated by the key alone, whatever its Authorization header says. The key comes back as it was sent, first header line only, as HttpServletRequest.getHeader reads it.
func APIKeySent ¶
APIKeySent reports whether either API key header is not blank, which is when 7.x's entry point answers a refused credential 403 rather than 401, "if not the client keeps asking for credentials indefinitely on 401 responses" (ArtifactoryBasicAuthenticationEntryPoint.isAlreadyAuthedApiKeyRequest, 7.161.26). An X-Api-Key sent blank is read as a key and refused, but is answered 401.
func BasicCredentials ¶
BasicCredentials returns the user name and secret of an Authorization value that 7.x reads as Basic credentials. It reports false for another scheme, for a value IgnoredAuthorization reports, and for one that does not decode to "<user>:<secret>", which the authentication answers 401 as a credential that does not verify, as Spring's Basic filter does.
func BearerToken ¶
BearerToken returns the token of an Authorization value that 7.x reads as a Bearer credential, reporting false for any other value. 7.161.26 reads one in two places: the props filter takes "Bearer " exactly in a value of at least nine UTF-16 units, whatever follows, and RequestUtils.getBearerAuthenticationValue takes "bearer " in any case followed by a value that is not blank. So "Bearer" alone, "Bearer " with at most one space after it, a lower-case "bearer" with only spaces after it, and "Bearer" followed by a tab carry no Bearer credential. The token comes back without the spaces around it, as artifactweave has always verified it; a value of spaces alone is read and does not verify.
func Blank ¶
Blank reports whether s is empty or holds only whitespace as Java's Character.isWhitespace defines it, the test of Commons Lang's StringUtils.isBlank, which 7.x applies to the value after the Basic and Bearer schemes and to the X-JFrog-Art-Api header: the space separators but the no-break spaces, the line and paragraph separators, and the ASCII controls tab to carriage return and file to unit separator.
func FoldUsername ¶
FoldUsername is the spelling a user name is stored and matched in: lower case. Access compares user names without regard to case and stores them in lower case: JFrog's SCIM page says "User names are case-insensitive", Get Permissions matches "Usernames ... case-insensitively, group names exactly", and RTFACT-29660 (7.55.13) says that a user created "with capitalization" is stored lower-case. Group names keep their case (#1309).
The rule is here, not only in the access module's model, so that another module that compares a user name a client sent with the request's principal, as Conan's login does, matches it as the authenticator did. strings.ToLower rather than strings.EqualFold, so that matching is equality of the spelling the stores hold.
func IgnoredAuthorization ¶
IgnoredAuthorization reports whether an Authorization value names the Basic scheme in a form 7.x reads no credential from: the scheme spelled other than exactly "Basic " (another case, or a tab after it), a blank value, or "Og==". 7.161.26's RequestUtils.getBasicAuthorization admits only "Basic " followed by a value neither blank nor "Og==", and no other filter of the open source chain reads a Basic value, so AccessFilter serves such a request as one without credentials. JFrog meant it so for "Og==" since 3.4.0: "Artifactory should ignore it and continue as anonymous" (RTFACT-6765). Net/http's Request.BasicAuth matches the scheme in any case, which is why callers that must agree with 7.x read Basic through BasicCredentials instead. Bearer is read by BearerToken, and the authentication counts any other scheme as no credential either.
func IsReferenceToken ¶
IsReferenceToken reports whether s has the reference-token form, which is how the authenticator tells a reference token from a JWT or an API key.
func LooksLikeToken ¶
LooksLikeToken reports whether a Basic password is an access or reference token rather than a password: the JFrog CLI sends tokens as the password of a Basic credential.
func SameUsername ¶
SameUsername reports whether a and b name the same user.
func WithCaller ¶
WithCaller returns ctx carrying p, stored with kernel.WithPrincipal, and d as p's decider (WithDecider). It is how a principal that Authorizer evaluated enters a context: a principal stored with kernel.WithPrincipal alone has no decider, so permission checks refuse it or evaluate it again.
func WithDecider ¶
WithDecider returns ctx carrying d as the decider of ctx's principal, bound to kernel.PrincipalBinding(ctx): DeciderFrom answers with d only while that WithPrincipal call's principal is ctx's, so a context derived with a later kernel.WithPrincipal no longer sees it, and a context derived in any other way, such as with a deadline, does. A nil d, or one holding a nil pointer, is stored as no decider and hides a decider that ctx carries.
Types ¶
type API ¶
type API struct {
Authenticator Authenticator
Authorizer Authorizer
Tokens Tokens
Keys Keys
Identity Identity
Restrictions Restrictions
Projects Projects
Grants Grants
AnonymousAccess AnonymousAccess
Settings Settings
}
API is the access module's published surface: one implementation of each contract, which the module builds and app hands to the other modules, and the access settings they read. A contract field is nil, never a typed nil, when the module has no such service, as Authenticator is without an authenticator and Tokens without a token service; a caller tests the field and answers as it does when that service is absent.
type Actions ¶
type Actions uint8
Actions is a set of permission actions. The internal model uses the Access v2 vocabulary; the legacy letters and names map onto it one to one (managedXrayMeta is SCAN, distribute is EXECUTE).
const ( ActionRead Actions = 1 << iota ActionAnnotate ActionWrite ActionDelete ActionManage ActionScan ActionExecute )
Actions, in the order the Access API lists them.
func ParseAccessActions ¶
ParseAccessActions reads Access v2 action names, case-insensitively as Access does.
func ParseLegacyActions ¶
ParseLegacyActions reads legacy v2 action names.
func ParseLetters ¶
ParseLetters reads legacy v1 action letters.
func (Actions) AccessNames ¶
AccessNames are the actions in the Access v2 spelling.
func (Actions) LegacyNames ¶
LegacyNames are the actions in the legacy v2 permission-target spelling.
func (Actions) MarshalJSON ¶
MarshalJSON stores actions as Access names so a permission document reads the same as the Access API.
func (*Actions) UnmarshalJSON ¶
UnmarshalJSON reads Access names.
type AnonymousAccess ¶
type AnonymousAccess interface {
// Enabled reports whether anonymous access is on. A setting that was
// never written is an error matching kernel.ErrNotFound, which callers
// read as off.
Enabled(ctx context.Context) (bool, error)
// SetEnabled turns anonymous access on or off.
SetEnabled(ctx context.Context, on bool) error
}
AnonymousAccess reads and switches the security.anonymous_access setting, which lets a request without credentials act as the anonymous user. Each call uses ctx for the store it reads or writes, so a call inside a store transaction takes part in it.
type Authenticator ¶
type Authenticator interface {
// Basic verifies a user name and password. Wrong credentials, an unknown
// or disabled user and a user without an internal password answer
// kernel.ErrBadCredentials alike. A locked account answers
// kernel.ErrAccountLocked whatever the password, and a correct but
// expired password answers kernel.ErrPasswordExpired with the principal,
// marked PasswordExpired. While basic authentication is switched off,
// every password answers 401 "Basic authentication with a password is
// disabled; use an access token"; while the name is suspended after
// failed logins, every password answers a 403 that says how many seconds
// to wait.
Basic(ctx context.Context, name, password string) (kernel.Principal, error)
// Token verifies an access or reference 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), which must then name the token's
// subject. The subject must still be an enabled user, so disabling a user
// disables their tokens; a token that does not verify answers
// kernel.ErrBadCredentials.
Token(ctx context.Context, raw, user string) (kernel.Principal, error)
// AnonymousAllowed reports whether a request without credentials acts as
// the anonymous user: the security.anonymous_access setting, which is off
// when it was never written, as in Artifactory.
AnonymousAllowed(ctx context.Context) (bool, error)
// Current rechecks a principal that a password, a token or anonymous
// access authenticated earlier, after a slow remote read or for queued
// work, against current local state: the user's status and password, the
// token's record and expiry, the basic-authentication and anonymous
// access settings, the password expiry policy and the user's API
// restriction. It returns the principal as it is now, or
// kernel.ErrBadCredentials once the credential no longer holds, which a
// registry token's principal (CurrentRegistry rechecks those) and a
// principal that no credential authenticated always answer. It retains,
// forwards and verifies no credential a second time, and reads only local
// state, so a publication may call it inside its transaction.
Current(ctx context.Context, p kernel.Principal) (kernel.Principal, error)
// CurrentRegistry rechecks a verified registry token's principal without
// turning it into a general access token: its grants, scope and expiry
// stay as they were, and the current user and the token it descends from
// can only remove access. A principal that is no verified registry token,
// or whose token has expired, answers kernel.ErrBadCredentials.
CurrentRegistry(ctx context.Context, p kernel.Principal) (kernel.Principal, error)
// RestoreDownload rechecks, as Current does, the credential that a signed
// download envelope names for the user name: a token, a password or
// anonymous access. The caller verifies the envelope's signature,
// subject, path, digest and expiry first, since holding a
// DownloadCredential proves nothing. A credential of an unknown kind, or
// with fields its kind does not have, answers kernel.ErrBadCredentials.
RestoreDownload(
ctx context.Context,
name string,
ref kernel.DownloadCredential,
) (kernel.Principal, error)
}
Authenticator verifies credentials and rechecks credentials it verified earlier against current state (decision 0005). It answers who a credential acts as, never what that principal may do: Authorizer evaluates the permissions. A credential that does not verify answers kernel.ErrBadCredentials, and a verified user whose API access an administrator has restricted answers kernel.ErrAPIRestricted (decision 0043); an error reading the stores is wrapped with what was being read. Each call uses ctx for the stores it reads, so a call inside a store transaction takes part in it.
type Authorizer ¶
type Authorizer interface {
// Authorize evaluates p's permissions, with the anonymous user's grants
// applying only while anonymousEnabled holds. It returns p with Admin
// and Groups set to what the evaluation decided (a token scope can
// remove the admin flag and narrow the groups, and a group with admin
// privileges makes a member an administrator) and the Decider that
// answers every permission question for it; the two belong together in
// the request's context (WithCaller). A store error is wrapped as "auth:
// permissions: %w", and the principal returned with it is the zero
// value.
Authorize(
ctx context.Context,
p kernel.Principal,
anonymousEnabled bool,
) (kernel.Principal, Decider, error)
// For evaluates p's permissions for a caller that holds no decider for
// it, reading the anonymous access setting first; a setting that was
// never written counts as off. It wraps an error reading the setting as
// "anonymous access setting: %w" and an error evaluating as "evaluate
// permissions: %w".
For(ctx context.Context, p kernel.Principal) (Decider, error)
// Decide evaluates s, a subject that no request authenticated, such as
// the user a signed upload names, with the anonymous user's grants
// applying only while anonymousEnabled holds. Its error is the
// evaluator's, unwrapped, for the caller to wrap.
Decide(ctx context.Context, s Subject, anonymousEnabled bool) (Decider, error)
}
Authorizer evaluates a principal's permissions (decision 0006), once for a request in the middleware and again for a principal the middleware did not see, such as the caller of queued work. Each call reads the permissions and groups through ctx, so a call inside a store transaction takes part in it. On error each call returns a nil Decider.
type Certificate ¶
type Certificate struct {
Alias string
PEM string
PrivateKey string `json:"-"`
IssuedTo string
IssuedBy string
IssuedOn time.Time
ValidUntil time.Time
Fingerprint string
}
Certificate is a client certificate that remote repositories present to upstreams (clientTlsCertificate). PEM holds the certificate chain and PrivateKey its key, sealed at rest (decision 0017). Every other field is parsed from the PEM once at upload, so listings never re-parse.
type Decider ¶
type Decider interface {
// IsAdmin reports whether the subject acts as an administrator, which
// the administrator-only endpoints require.
IsAdmin() bool
// Groups returns the groups the subject acts through: all of its groups,
// or those a token scope names. The slice is the caller's to change.
Groups() []string
// IsRepoVisible reports whether the subject may see repo in a listing
// and read its configuration.
IsRepoVisible(repo Repo) bool
// VisibleRepos describes the repositories IsRepoVisible admits, for a
// store to apply as a filter: for every stored repository r (a key
// without the "-cache" suffix, which repository keys never carry),
// VisibleRepos().Has(r) equals IsRepoVisible(r).
VisibleRepos() RepoVisibility
// Allows reports whether the subject holds every action in want on the
// file at path in repo, in the rt section of the permissions. Asking for
// no action is refused.
Allows(rt ResourceType, repo Repo, path string, want Actions) bool
// AllowsFolder is Allows for the folder at path, which also counts as
// permitted when a permitted path lies below it.
AllowsFolder(rt ResourceType, repo Repo, path string, want Actions) bool
// AllowsAll reports whether the subject holds every action in want on
// every path below folder in repo ("" for every path of the
// repository), whatever paths the repository holds, so that a list
// may count and page in the store what lies there rather than asking
// Allows of each path. True means Allows and AllowsFolder are true for
// each such path. False says nothing about any one path, which Allows
// then decides: it holds when some permission, and the token scope
// that narrows it, cover the folder whole, and may be false for
// grants that only together cover it. Asking for no action is
// refused.
AllowsAll(rt ResourceType, repo Repo, folder string, want Actions) bool
// System reports whether the subject may use a system capability, an
// area such as "info" or "metrics", with the actions in want: an
// administrator may, anyone else only through a token's system scope
// that covers the area and the actions.
System(area string, want kernel.ScopeActions) bool
}
Decider answers the permission questions other modules ask about one request's subject, from the snapshot of the permissions taken when it was built (decision 0006). The access module's evaluator implements it, and an implementation answers exactly as that evaluator does: a token scope only removes actions, except that applied-permissions/admin acts as an administrator. The methods only read that snapshot, so a Decider may be used from several goroutines. It holds only what other modules ask; the questions about permission documents and the subject's own grants stay on the evaluator, because only access's permission handlers ask them.
func DeciderFrom ¶
DeciderFrom returns the decider that WithDecider bound to ctx's principal, and true. It returns nil and false when ctx carries no principal, when the decider was bound to a principal that a later WithPrincipal replaced, and when the bound decider is nil, which a caller answers as it does a request that was never authorised: by refusing, or by evaluating the principal with Authorizer.For.
type Grants ¶
type Grants interface {
// ItemGrants returns the actions each user and each group holds on the
// item at path, a folder when folder is true, through the permissions
// whose artifact section names one of targets with include and exclude
// patterns that admit path. targets are tried in order, and a permission
// counts at most once, for the first of them whose patterns admit path;
// a user's or group's actions are the union over the permissions that
// count. A store error names the target it was reading.
ItemGrants(
ctx context.Context,
targets []string,
path string,
folder bool,
) (users, groups map[string]Actions, err error)
// AccessChange returns the name of the first permission, in name order,
// whose artifact targets covering the repository repoKey of class admit
// some pair's source and destination differently, or "" when none does.
// It reads the permissions in pages of limit, which must be positive,
// and returns ErrScanLimit once it reads more than limit permissions; a
// store error is returned as the store gave it.
AccessChange(
ctx context.Context,
repoKey, class string,
pairs []PathPair,
limit int,
) (permission string, err error)
}
Grants scans the stored permissions for questions about content rather than about one subject: who holds what on an item, and whether moving content would change who may reach it. Only the artifact sections of the permissions count. Each call uses ctx for the store it reads, so a call inside a store transaction takes part in it.
type Identity ¶
type Identity interface {
// User returns the account called name; an error matching
// kernel.ErrNotFound when there is none.
User(ctx context.Context, name string) (UserInfo, error)
// AutoJoinGroups returns the names of the groups new users join, in
// order. A transient user, which a token names while no stored account
// has its name, acts through these groups.
AutoJoinGroups(ctx context.Context) ([]string, error)
}
Identity reads user accounts and the groups new users join, for modules that resolve a user named outside the request's principal, such as the subject of a signed URL. Each call uses ctx for the store it reads, so a call inside a store transaction takes part in it.
type IssuedToken ¶
type IssuedToken struct {
AccessToken, RefreshToken, ReferenceToken string
// ExpiresIn is the lifetime in seconds; zero means never.
ExpiresIn int64
// TokenID is the token's id, which its record and its jti claim carry.
TokenID string
// IssuedAt is when the token was issued, in whole seconds, as its iat
// claim carries it.
IssuedAt time.Time
}
IssuedToken is a new token and its secrets, which are never stored and so cannot be shown again. RefreshToken is set only for a refreshable token, and ReferenceToken only when the request asked for one or had a purpose.
type Keypair ¶
type Keypair struct {
Name string
Type KeypairType
Alias string
PublicKey string
PrivateKey string `json:"-"`
Passphrase string `json:"-"`
}
Keypair is a named signing key pair (the security API's pairName). The private key and passphrase are sealed at rest (decision 0017).
type KeypairType ¶
type KeypairType string
KeypairType is the kind of a stored key pair.
const ( KeypairRSA KeypairType = "RSA" KeypairGPG KeypairType = "GPG" KeypairEd25519 KeypairType = "Ed25519" // KeypairECDSA signs npm packages (decision 0034, "Signatures"). KeypairECDSA KeypairType = "ECDSA" )
Key pair types the security API accepts.
type Keys ¶
type Keys interface {
// Keypair returns the key pair called name; an error matching
// kernel.ErrNotFound when there is none.
Keypair(ctx context.Context, name string) (Keypair, error)
// Certificate returns the certificate with alias; an error matching
// kernel.ErrNotFound when there is none.
Certificate(ctx context.Context, alias string) (Certificate, error)
}
Keys reads the key material other modules sign or connect with: the signing key pairs of repositories and the client certificates of remote repositories. Private keys and passphrases come back unsealed, ready to use, so a caller never logs or serialises them (decision 0017). Each call uses ctx for the store it reads, so a call inside a store transaction takes part in it.
type PathPair ¶
PathPair is a path and the path its content takes after a move, such as a repository migration. Folder marks a pair of folders, which a permission target also admits when it admits a path below them.
type Projects ¶
type Projects interface {
// Environments returns the names of a project's environments, or of the
// global environments for project "", ordered by name and spelled as
// stored; a project that does not exist has none. The built-in DEV and
// PROD are not among them.
Environments(ctx context.Context, project string) ([]string, error)
// Member returns nil when user is a member of project; an error matching
// kernel.ErrNotFound when they are not, or the project does not exist.
Member(ctx context.Context, project, user string) error
// Exists returns nil when project exists; an error matching
// kernel.ErrNotFound when it does not.
Exists(ctx context.Context, project string) error
}
Projects reads projects, their environments and their members (decision 0013), for the modules that check a repository's project and environments. Each call uses ctx for the store it reads, so a call inside a store transaction takes part in it.
type RegistryTokenRequest ¶
type RegistryTokenRequest struct {
// Username is the user the token acts for: required, and without a
// slash.
Username string
// ExpiresIn is the lifetime; it must be positive and at most one hour,
// and the caller shortens it to the remaining life of the credential
// that obtained the token.
ExpiresIn time.Duration
// Access is what the token grants, in the Docker token specification's
// form.
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
}
RegistryTokenRequest asks Tokens.IssueRegistry for a registry token, which the Docker token endpoint hands out (decision 0005). It has every field of the token service's registry request, in the same order and of the same types.
type Repo ¶
Repo identifies a permission target: a repository's key and class (local, remote, virtual, federated, distribution), or the fixed build-info or release-bundle repository of those resources. "<remote>-cache" is accepted for a remote's cache and resolves to the remote.
type RepoSet ¶
RepoSet is a set of stored repositories named the way permission targets and token scopes name them: every repository, or those of the listed classes together with those of the listed keys. The zero RepoSet holds none.
type RepoVisibility ¶
type RepoVisibility []RepoSet
RepoVisibility is the set of repositories a subject sees in a listing, as the intersection of its sets: a repository is visible when every set holds it, so a RepoVisibility with no set shows every repository. It describes what Decider.IsRepoVisible answers in terms a store can apply as a filter, so a listing can count and page what the caller sees in its query rather than reading every repository and asking about each (decision 0043, "Paging classes and the next pointer").
func (RepoVisibility) Has ¶
func (v RepoVisibility) Has(r Repo) bool
Has reports whether every set holds r.
type ResourceType ¶
type ResourceType string
ResourceType is a section of an Access v2 permission.
const ( ResourceArtifact ResourceType = "artifact" ResourceBuild ResourceType = "build" ResourceReleaseBundle ResourceType = "release_bundle" ResourceDestination ResourceType = "destination" ResourcePipelineSource ResourceType = "pipeline_source" )
Resource types. Destination carries Distribution's DESTINATION permissions (decision 0023); pipeline sources are accepted for round-tripping only.
type Restrictions ¶
type Restrictions interface {
// Check returns nil when user may call the API at now: no restriction is
// stored for them, it has ended, or ctx is marked for the administrator
// recovery routes. While a restriction lasts it returns an error that
// answers 403 "API access is temporarily restricted". It reads the
// stored restriction on every call, with no cache, and fails closed: a
// restriction it cannot read is an error.
Check(ctx context.Context, user string, now time.Time) error
}
Restrictions checks the temporary restriction an administrator can put on a user's authenticated API calls. A module that verifies a credential outside the request's authentication, such as a refresh grant or a signed download, checks it before it acts for the user. Each call uses ctx for the store it reads, so a call inside a store transaction takes part in it.
type Settings ¶
type Settings struct {
// AllowBasicAuthTokens lets a password sent with Basic create tokens
// through POST /access/api/v1/tokens (token.allow_basic_auth); false
// refuses it, as Artifactory 7.x does by default.
AllowBasicAuthTokens bool
// GlobalEnvironmentLimit caps the global environments, DEV and PROD
// included (environments.global_limit); zero or less means Access's
// default of 10.
GlobalEnvironmentLimit int
}
Settings are the access options of the application configuration that other modules read. The zero value behaves as the defaults do.
type Subject ¶
type Subject struct {
Name string
Groups []string
Admin bool
Anonymous bool
// Scope is the scope of the token the request carries; nil for password
// authentication, which acts with everything the subject holds.
Scope *kernel.Scope
}
Subject is who a request acts as. Groups are the groups the subject belongs to; the token service (#74) may instead put a token's scoped groups here when it mints a token for a subject that is not a user.
func SubjectOf ¶
SubjectOf returns p as the permission evaluator starts from it: the user's own admin flag and groups, and the token's scope when a token authenticated p. It is here rather than in access core because other modules build the subject of a remote read from the request's principal and may import only this package. The groups never alias p's.
type TokenRequest ¶
type TokenRequest struct {
// Username is the user the token is for: required, and without a slash.
Username string
// Scope defaults to applied-permissions/user.
Scope kernel.Scope
// ExpiresIn defaults to token.default_expiry, one year while no
// administrator has set it; zero means never and needs ByAdmin.
ExpiresIn *time.Duration
Refreshable bool
ForceRevocable bool
Audience string
Description string
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, such as the
// encrypted password's ("encrypted_password"). 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, so the token never
// outlives the 24 hours an OIDC mapping allows.
NotAfter time.Time
}
TokenRequest asks Tokens.Issue for an access token for a user. It has every field of the token service's own request, in the same order and of the same types, so the access module converts one to the other and issuance keeps every rule of decision 0005.
type Tokens ¶
type Tokens interface {
// Issue creates and stores a token. It refuses a request without a
// user name, with a negative lifetime, for a token that never expires
// from a caller who is not an administrator, or whose NotAfter has
// passed, and a user whose API access is restricted; a second token of a
// purpose the user already holds is an error matching
// kernel.ErrConflict.
Issue(ctx context.Context, r TokenRequest) (IssuedToken, error)
// IssueRegistry signs a registry token. Nothing stores it, as
// Artifactory stores no token below its persistence threshold, so it cannot be
// listed or revoked; its short life, its grants and the user's current
// permissions bound it instead.
IssueRegistry(ctx context.Context, r RegistryTokenRequest) (IssuedToken, error)
// RevokeValue revokes the stored token whose access or reference token
// is raw: an error matching kernel.ErrNotFound when no stored token has
// that value, and ErrNotRevocable when the token is short-lived and was
// neither forced revocable nor refreshable.
RevokeValue(ctx context.Context, raw string) error
// EncryptedPassword returns user's encrypted password: the reference
// token of their encrypted-password token, which never expires. It is
// created on first use and the same value after, so every client given
// it keeps working until the password changes and revokes it.
EncryptedPassword(ctx context.Context, user string) (string, error)
// DeleteExpired removes the records of tokens that expired before
// before and returns how many it removed; tokens that never expire stay.
DeleteExpired(ctx context.Context, before time.Time) (int64, error)
}
Tokens issues and revokes access tokens (decision 0005). Each call uses ctx for the stores it reads and writes, so a call inside a store transaction takes part in it. The errors are the token service's: callers test them with errors.Is.
type UserInfo ¶
type UserInfo struct {
Name, Email string
Admin bool
Groups []string
// Status is the Access account status: "enabled", "disabled", "locked"
// or "invited", or empty for an account stored without one.
Status string
}
UserInfo is what other modules read about a user account. The password hash and the account's other fields stay inside access.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package accessapitest provides hand-written fakes of every access/api contract, for tests that need access's answers without a store or the access module: a configurable Decider, Authenticator and Authorizer, a Tokens that records its calls, map-backed Keys, Identity, Projects and AnonymousAccess, and scripted Grants and Restrictions.
|
Package accessapitest provides hand-written fakes of every access/api contract, for tests that need access's answers without a store or the access module: a configurable Decider, Authenticator and Authorizer, a Tokens that records its calls, map-backed Keys, Identity, Projects and AnonymousAccess, and scripted Grants and Restrictions. |