auth

package
v0.26.0 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2026 License: AGPL-3.0 Imports: 44 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	// BootstrapUsername is the local account created on first start.
	BootstrapUsername = "admin"
	// BootstrapTokenName is the name of the access token created from
	// BootstrapOptions.AdminTokenFile.
	BootstrapTokenName = "bootstrap"
)
View Source
const (
	CIOIDCMalformed         = "malformed"
	CIOIDCUnknownIssuer     = "unknown_issuer"
	CIOIDCIssuerUnreachable = "issuer_unreachable"
	CIOIDCInvalidToken      = "invalid_token"
	CIOIDCAudience          = "audience_mismatch"
	CIOIDCConditions        = "conditions_not_met"
	CIOIDCAccountDisabled   = "service_account_disabled"
)

Reasons an ID token is refused (CIOIDCDenialError.Reason). They go to the log and the audit trail, never to the caller.

View Source
const (
	// OIDCPolicyMinTTL and OIDCPolicyMaxTTL bound the lifetime of an exchanged
	// token in seconds; OIDCPolicyDefaultTTL applies when a policy names none.
	OIDCPolicyMinTTL     = 60
	OIDCPolicyMaxTTL     = 3600
	OIDCPolicyDefaultTTL = 900
)

Limits of a CI OIDC trust policy.

View Source
const (
	// DexGroupsScope makes Dex release the groups claim.
	DexGroupsScope = "groups"
	// DexFederatedIDScope makes Dex release federated_claims (connector_id
	// and the upstream user_id) in the ID token.
	DexFederatedIDScope = "federated:id"
)

Dex scopes OpenArtifact asks for when a provider is pinned to a connector.

View Source
const (
	CredentialSession     = "session"
	CredentialBearerToken = "bearer_token"
	CredentialBasicToken  = "basic_token"
	CredentialLegacy      = "legacy"
	CredentialNone        = "none"
)

Credential names describe how a request was authenticated.

View Source
const (
	// DefaultIDPMetadataRefreshSeconds is how long fetched IdP metadata is
	// reused when saml_config.idp_metadata_refresh_seconds is unset.
	DefaultIDPMetadataRefreshSeconds = 3600
	// MinIDPMetadataRefreshSeconds and MaxIDPMetadataRefreshSeconds bound the
	// per-provider refresh interval.
	MinIDPMetadataRefreshSeconds = 60
	MaxIDPMetadataRefreshSeconds = 86400
)
View Source
const (
	SSOIconGoogle    = "google"
	SSOIconGitHub    = "github"
	SSOIconGitLab    = "gitlab"
	SSOIconOkta      = "okta"
	SSOIconAuth0     = "auth0"
	SSOIconKeycloak  = "keycloak"
	SSOIconAuthentik = "authentik"
	SSOIconGitea     = "gitea"
	SSOIconBitbucket = "bitbucket"
	SSOIconAtlassian = "atlassian"
	SSOIconOpenShift = "openshift"
	SSOIconOpenStack = "openstack"
	SSOIconOpenID    = "openid"
	SSOIconLDAP      = "ldap"
	SSOIconSAML      = "saml"
	SSOIconKey       = "key"
)

Icon keys of the login button. The web UI maps each to a glyph; vendors without a glyph in the bundled icon set (Microsoft Entra, Ping, OneLogin, JumpCloud, Duo, Dex) resolve to the generic OpenID or SAML key instead.

View Source
const (
	TokenPrefixAccess = "oa_pat_"
	TokenPrefixDeploy = "oa_dep_"
	TokenKindAccess   = "access"
	TokenKindDeploy   = "deploy"
)
View Source
const (
	SessionCookieName = "oa_session"
)
View Source
const SettingHMACKey = "auth.hmac_key"

SettingHMACKey is the system_settings key holding the generated login-state HMAC key (encrypted with internal/crypto when a secret key is set).

View Source
const SettingProjectsSelfCreate = "projects.self_create"

SettingProjectsSelfCreate is the system setting that lets any authenticated human user create a project (and become its owner). When unset, the projects.selfCreate config value (OPENARTIFACT_PROJECTS_SELF_CREATE) decides.

View Source
const SettingSAMLSPKeypair = "saml.sp_keypair"

SettingSAMLSPKeypair is the system_settings key holding the generated SAML service-provider keypair: one value with the PEM private key followed by the PEM certificate (encrypted with internal/crypto when a secret key is set).

Variables

View Source
var (
	ErrSSOProviderNotFound = errors.New("sso provider not found")
	ErrSSOProviderDisabled = errors.New("sso provider disabled")
	ErrOIDCSecretUnusable  = errors.New("oidc client secret cannot be decrypted")
	ErrOIDCDiscoveryFailed = errors.New("oidc discovery failed")
	ErrIDTokenMissing      = errors.New("id token missing")
	ErrIDTokenExpired      = errors.New("id token expired")
	// ErrOIDCUnknownType is returned for a stored oidc_config.type this build
	// does not implement.
	ErrOIDCUnknownType = errors.New("unsupported oidc provider type")
	// ErrOIDCConfigInvalid is returned when a stored config cannot work (for
	// example a multi-tenant Entra authority without allowed tenants).
	ErrOIDCConfigInvalid = errors.New("oidc provider configuration invalid")
)
View Source
var (
	ErrIDPMetadataUnavailable = errors.New("idp metadata unavailable")
	// ErrSAMLSignatureInvalid covers a signature that does not verify
	// (tampered, foreign certificate, wrapped assertion, unusable metadata
	// certificate) and, through ErrSAMLSignatureMissing, a response with no
	// signature where one is required.
	ErrSAMLSignatureInvalid = errors.New("saml signature invalid")
	// ErrSAMLSignatureMissing means neither the response nor the assertion is
	// signed. It matches ErrSAMLSignatureInvalid too.
	ErrSAMLSignatureMissing     = fmt.Errorf("%w: response and assertion are unsigned", ErrSAMLSignatureInvalid)
	ErrSAMLAudienceMismatch     = errors.New("saml audience mismatch")
	ErrSAMLAssertionExpired     = errors.New("saml assertion expired")
	ErrSAMLAssertionNotYetValid = errors.New("saml assertion not yet valid")
	ErrSAMLRequestMismatch      = errors.New("saml InResponseTo does not match the login request")
	ErrSAMLDestinationMismatch  = errors.New("saml destination or recipient mismatch")
	ErrSAMLIssuerMismatch       = errors.New("saml issuer mismatch")
	ErrSAMLBadStatus            = errors.New("saml response status is not success")
)
View Source
var (
	ErrSAMLRequestUntracked = errors.New("saml response does not match a pending login request")
	ErrSAMLReplay           = errors.New("saml assertion already used")
	ErrSAMLTrackerKey       = errors.New("saml request tracker key not configured")
)
View Source
var ErrAccessTokenNotAccepted = errors.New("oidc access token not accepted")

ErrAccessTokenNotAccepted means a bearer credential is not an OIDC access token this server accepts (unknown issuer, wrong audience, unknown user…).

View Source
var ErrAccountDisabled = errors.New("account disabled")
View Source
var (
	// ErrBootstrapSecret is wrapped by every invalid bootstrap secret error.
	ErrBootstrapSecret = errors.New("invalid bootstrap secret")
)
View Source
var ErrEmailAlreadyInUse = errors.New("email already in use")
View Source
var ErrEmptyPattern = errors.New("pattern must not be empty")

ErrEmptyPattern is returned for an empty repository filter or path pattern. An empty regular expression matches everything, so it must never be stored.

View Source
var ErrIdentityConflict = errors.New("account is already linked to a different sso identity")

ErrIdentityConflict is returned when an SSO login would re-bind a local user that is already bound to a different external identity or provider.

View Source
var ErrInvalidRelayState = errors.New("invalid relay state")
View Source
var ErrNoSettingsStore = errors.New("no settings store to persist the generated key")

ErrNoSettingsStore is returned when a generated key is needed but there is no database to persist it in.

View Source
var ErrSAMLKeypairCorrupt = errors.New("stored saml sp keypair is corrupt")

ErrSAMLKeypairCorrupt is returned when the stored SP keypair cannot be parsed. It is never repaired by regenerating: a new certificate would silently break every IdP that already trusts the published one.

View Source
var ErrSSOLoginDenied = errors.New("sso login denied")

ErrSSOLoginDenied marks a login the identity provider authenticated but local policy rejects (unverified email, wrong hosted domain or tenant, organization gate). Handlers answer it with one generic 403 and log the wrapped detail.

View Source
var ErrUserNotProvisioned = errors.New("user not provisioned")
View Source
var ErrUsernameUnavailable = errors.New("no free username available")

ErrUsernameUnavailable is returned when no free username could be derived.

View Source
var SessionDuration = defaultSessionDurationHours * time.Hour

Functions

func AttachSSOSession added in v0.8.0

func AttachSSOSession(ctx context.Context, db AttachSSOSessionStore, sessionID, providerSlug, rawIDToken string) error

AttachSSOSession records the SSO provider that created the session identified by sessionID together with the (encrypted) ID token, so logout can run RP-initiated logout.

func BootstrapIfEmpty

func BootstrapIfEmpty(ctx context.Context, db BootstrapIfEmptyStore, log *logger.Logger, opts BootstrapOptions) error

BootstrapIfEmpty creates the first admin account on an empty instance.

The user row, its admin-all assignment and the optional bootstrap token are written in one transaction guarded by an advisory lock (CreateBootstrapAdmin), so concurrent replicas cannot both create an admin, and an interrupted bootstrap cannot leave an admin without rights. When users already exist it ignores the supplied secrets and only repairs the "admin exists but nobody holds admin-all" state left by older versions.

func CompilePattern added in v0.2.0

func CompilePattern(pattern string) (*regexp.Regexp, error)

CompilePattern compiles a repository filter or path pattern exactly the way the evaluator matches it: "*" is shorthand for ".*", an empty pattern is rejected, and the expression is anchored so it must match the whole value ("dev" no longer matches "devops"). The API validates with this function so what is accepted at write time is what is enforced at request time.

func ConditionsMatch added in v0.16.0

func ConditionsMatch(conditions []models.OIDCCondition, claims map[string]any) bool

ConditionsMatch reports whether claims satisfy every condition: each named claim must be present and one of its values must match one of the condition's patterns.

func ConfigureSessionDuration

func ConfigureSessionDuration(d time.Duration)

func CreateProjectToken added in v0.6.0

CreateProjectToken mints a deploy token for a new service account of the project (see database.ProjectTokenSpec); spec.TokenHash is filled here.

func CreateSession

func CreateSession(ctx context.Context, db CreateSessionStore, userID, ip, userAgent string) (string, *models.Session, error)

func CreateToken

func CreateToken(
	ctx context.Context,
	db CreateTokenStore,
	kind, name, userID string,
	scopes []string,
	expiresAt *time.Time,
) (string, *models.Token, error)

func DeleteSession

func DeleteSession(ctx context.Context, db DeleteSessionStore, cookieValue string) error

func GlobMatch added in v0.16.0

func GlobMatch(pattern, s string) bool

GlobMatch reports whether s matches pattern, which must match the whole string. "*" matches any run of characters (including none and "/", so "refs/heads/*" matches "refs/heads/release/1.2") and "?" matches exactly one character; every other character stands for itself, case-sensitively. There is no escape: claim values of CI systems do not contain the two wildcards.

func IDPMetadataRefresh added in v0.8.0

func IDPMetadataRefresh(cfg models.SAMLConfig) time.Duration

IDPMetadataRefresh returns the effective refresh interval of cfg: the configured value clamped to [60s, 24h], one hour when unset.

func IsEntraGUID added in v0.8.0

func IsEntraGUID(s string) bool

IsEntraGUID reports whether s is a GUID (an Entra tenant or object ID).

func IsEntraMultiTenantAuthority added in v0.8.0

func IsEntraMultiTenantAuthority(issuer string) bool

IsEntraMultiTenantAuthority reports whether issuer names one of Microsoft identity platform's tenant-less v2.0 authorities (https://login.microsoftonline.com/{common|organizations|consumers}/v2.0, trailing slash optional). Their discovery document advertises an issuer with a literal {tenantid} placeholder, so the issuer check must be done by hand.

func IsUnknownKeyError

func IsUnknownKeyError(err error) bool

IsUnknownKeyError reports whether err is go-oidc's JWKS signature failure (no published key verified the token), the only kind a key rotation or a stale discovery document can explain. go-oidc errors are unstructured, so the specific message is matched; other verification failures (expiry, audience, issuer, malformed token) are not retried.

func NewTokenSecret added in v0.6.0

func NewTokenSecret(kind string) (string, string, error)

NewTokenSecret generates a token of the given kind. It returns the secret to hand to the user once and the lookup digest to store.

func OIDCCallbackURL added in v0.20.0

func OIDCCallbackURL(baseURL, slug string) string

OIDCCallbackURL is the redirect URI an identity provider must allow for the OIDC provider slug.

func OIDCIssuers added in v0.8.0

func OIDCIssuers(ctx context.Context, db OIDCIssuersStore) ([]string, error)

OIDCIssuers returns the issuer URL of every enabled OIDC provider. It is what the protected-resource metadata advertises as authorization servers.

func ProjectRoleAllows added in v0.6.0

func ProjectRoleAllows(role string, admin bool, action ProjectAction) bool

ProjectRoleAllows reports whether role (or admin, an implicit owner) may perform action. An unknown action is never allowed.

func ResolveHMACKey added in v0.8.0

func ResolveHMACKey(ctx context.Context, store SettingsStore, configured string, log *logger.Logger) ([]byte, error)

ResolveHMACKey returns the key that signs SAML RelayState and request trackers. A configured key (AUTH_HMAC_KEY) wins; otherwise a random key is generated once and stored in system_settings, so restarts and every replica share it.

func ResolveSSOIcon added in v0.20.0

func ResolveSSOIcon(p *models.SSOProvider) string

ResolveSSOIcon is the icon the login button of p shows, never empty. An explicit icon wins; then a GitHub provider type, a Dex connector id naming a known vendor, and the host or path of the issuer (OIDC) or the metadata URL (SAML); else the generic OpenID or SAML key.

func RevokeAllSessions added in v0.2.0

func RevokeAllSessions(ctx context.Context, db RevokeAllSessionsStore, userID string) error

RevokeAllSessions deletes every session of a user (password change/reset, account disable).

func RevokeOtherSessions added in v0.2.0

func RevokeOtherSessions(ctx context.Context, db RevokeOtherSessionsStore, userID, keepCookie string) error

RevokeOtherSessions deletes every session of a user except the one carried by keepCookie. An unusable cookie keeps nothing.

func SAMLACSURL added in v0.20.0

func SAMLACSURL(baseURL, slug string) string

SAMLACSURL is the assertion consumer service URL of the SAML provider slug.

func SAMLEntityID added in v0.20.0

func SAMLEntityID(baseURL, slug string) string

SAMLEntityID is the service-provider entity id (and metadata URL) of the SAML provider slug.

func SessionAbsoluteLifetime added in v0.2.0

func SessionAbsoluteLifetime() time.Duration

SessionAbsoluteLifetime is the hard cap on a session's total lifetime. It is never shorter than the idle duration.

func SignRelayState

func SignRelayState(redirect, key string) string

SignRelayState returns redirect with its signing time, MAC'd under key. The result is valid for ten minutes.

func TouchSession added in v0.2.0

func TouchSession(ctx context.Context, db TouchSessionStore, session *models.Session) error

TouchSession slides the idle expiry of a session forward, at most once per sessionTouchInterval and never beyond the absolute session lifetime.

func TouchToken added in v0.2.0

func TouchToken(ctx context.Context, db TouchTokenStore, token *models.Token)

TouchToken records usage of an authenticated token, at most once per tokenTouchInterval so a busy CI client does not hammer one hot row.

The token comes from the auth cache, whose LastUsedAt is stale for the whole cache TTL, so the throttle is tracked per token ID in process memory instead.

func UpdateLastUsed

func UpdateLastUsed(ctx context.Context, db UpdateLastUsedStore, tokenID string)

UpdateLastUsed records token usage synchronously with a short bounded timeout (no per-request goroutines). Failures are ignored: usage bookkeeping must never fail a request.

func ValidClaimPath added in v0.21.0

func ValidClaimPath(s string) bool

ValidClaimPath reports whether s names a claim: up to 64 letters, digits or _ . : - where a dot joins the names of nested claims (kubernetes.io.namespace), so it neither starts nor ends with a dot and has no empty segment.

func ValidDexConnectorID added in v0.20.0

func ValidDexConnectorID(id string) bool

ValidDexConnectorID reports whether id is usable as dex_connector_id.

func ValidSSOIcon added in v0.20.0

func ValidSSOIcon(key string) bool

ValidSSOIcon reports whether key is storable: empty (automatic) or a known key.

func ValidateOIDCPolicy added in v0.16.0

func ValidateOIDCPolicy(p *models.OIDCTrustPolicy) error

ValidateOIDCPolicy checks the fields of a trust policy an administrator writes (everything but the service account, which the caller resolves) and normalizes it: an unset TTL becomes OIDCPolicyDefaultTTL. The messages are meant for the administrator.

func ValidateSession

func ValidateSession(ctx context.Context, db ValidateSessionStore, cookieValue string) (*models.Session, error)

func ValidateToken

func ValidateToken(ctx context.Context, db ValidateTokenStore, tokenString string) (*models.Token, *models.User, error)

func VerifyOIDCAccessToken added in v0.8.0

func VerifyOIDCAccessToken(ctx context.Context, db VerifyOIDCAccessTokenStore, baseURL, rawToken, audience string) (*models.User, error)

VerifyOIDCAccessToken validates a JWT access token issued by one of the enabled OIDC providers for this server and returns the user it maps to.

The token must be signed by the provider that its iss names, be unexpired and carry audience (the canonical MCP resource URI, RFC 8707) in aud; ID tokens minted for the web login (aud = client ID) therefore never qualify. The subject must already be linked to a local user through that provider (ListEnabledSSOProviders/GetUserByExternalID): access tokens never provision users, and disabled users are refused.

func VerifyRelayState

func VerifyRelayState(encoded, key string) (string, error)

VerifyRelayState returns the redirect of a state SignRelayState made with key less than ten minutes ago.

Types

type AttachSSOSessionStore added in v0.15.0

type AttachSSOSessionStore interface {
	SetSessionSSO(ctx context.Context, sessionID string, providerSlug string, encryptedIDToken string) error
}

AttachSSOSessionStore is the part of the database AttachSSOSession needs.

type BootstrapIfEmptyStore added in v0.15.0

type BootstrapIfEmptyStore interface {
	CountUsers(ctx context.Context) (int, error)
	RepairBootstrapAdmin(ctx context.Context, username string) (bool, error)
	// contains filtered or unexported methods
}

BootstrapIfEmptyStore is the part of the database BootstrapIfEmpty needs.

type BootstrapOptions added in v0.11.0

type BootstrapOptions struct {
	// AdminPasswordFile is read for the initial password; it wins over
	// AdminPassword.
	AdminPasswordFile string
	AdminPassword     string
	// ForcePasswordChange forces a password change at the first login of a
	// supplied password. A generated password always forces it.
	ForcePasswordChange bool
	// AdminTokenFile is read for the secret of the "bootstrap" access token.
	AdminTokenFile string
	// AdminTokenTTL is the lifetime of the bootstrap token; 0 = none.
	AdminTokenTTL time.Duration
	// GeneratedPasswordTTL is how long a generated password stays valid;
	// 0 = forever.
	GeneratedPasswordTTL time.Duration

	// Now is the clock (default time.Now); Stderr receives the banner
	// (default os.Stderr).
	Now    func() time.Time
	Stderr io.Writer
}

BootstrapOptions configures first-admin provisioning (config section "bootstrap"). The zero value generates a random password that never expires.

type CIOIDC added in v0.16.0

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

CIOIDC authenticates ID tokens of CI systems against the trust policies. It only ever contacts issuers an administrator named in an enabled policy; the iss claim of a token is read unverified solely to pick the policies (and so the issuer) its signature is then checked against.

func NewCIOIDC added in v0.16.0

func NewCIOIDC(store CIOIDCStore) *CIOIDC

NewCIOIDC returns an authenticator over store.

func (*CIOIDC) Authenticate added in v0.16.0

func (x *CIOIDC) Authenticate(ctx context.Context, raw, policyName string) (*CIOIDCMatch, error)

Authenticate verifies raw (signature through the issuer's published keys, issuer, expiry, not-before, issued-at) and returns the first policy, oldest first, that trusts it: the audience is the one the policy names, every claim condition holds and the service account is enabled. When policyName is not empty only that policy is considered. A refusal is a *CIOIDCDenialError; any other error is the store's.

func (*CIOIDC) WithServiceAccountFiles added in v0.21.0

func (x *CIOIDC) WithServiceAccountFiles(tokenFile, caFile string) *CIOIDC

WithServiceAccountFiles sets the projected service account token and the CA bundle the serviceaccount discovery mode presents to, and trusts for, an issuer (in a pod: /var/run/secrets/kubernetes.io/serviceaccount/{token,ca.crt}). The token is read for every request, as the kubelet rotates it; the CA is read whenever an issuer is discovered.

type CIOIDCDenialError added in v0.16.0

type CIOIDCDenialError struct {
	Reason   string
	Verified bool
	Issuer   string
	Subject  string
	Err      error
}

CIOIDCDenialError is the refusal of an ID token. Verified is set when the token's signature, issuer and times were checked before it was refused, so Issuer and Subject are authentic; the audit trail records only such refusals as an attempt (anything else may be noise from anyone).

func (*CIOIDCDenialError) Error added in v0.16.0

func (d *CIOIDCDenialError) Error() string

func (*CIOIDCDenialError) Unwrap added in v0.16.0

func (d *CIOIDCDenialError) Unwrap() error

type CIOIDCMatch added in v0.16.0

type CIOIDCMatch struct {
	Policy  *models.OIDCTrustPolicy
	Claims  map[string]any
	Subject string
}

CIOIDCMatch is an accepted ID token: the policy that trusts it and its verified claims.

type CIOIDCStore added in v0.16.0

type CIOIDCStore interface {
	ListEnabledOIDCPoliciesByIssuer(ctx context.Context, issuer string) ([]*models.OIDCTrustPolicy, error)
}

CIOIDCStore is the part of the database CIOIDC needs.

type CreateProjectTokenStore added in v0.15.0

type CreateProjectTokenStore interface {
	CreateProjectToken(ctx context.Context, spec database.ProjectTokenSpec) (*models.Token, error)
}

CreateProjectTokenStore is the part of the database CreateProjectToken needs.

type CreateSessionStore added in v0.15.0

type CreateSessionStore interface {
	CreateSession(ctx context.Context, session *models.Session) (*models.Session, error)
}

CreateSessionStore is the part of the database CreateSession needs.

type CreateTokenStore added in v0.15.0

type CreateTokenStore interface {
	CreateToken(ctx context.Context, token *models.Token) (*models.Token, error)
}

CreateTokenStore is the part of the database CreateToken needs.

type DeleteSessionStore added in v0.15.0

type DeleteSessionStore interface {
	DeleteSession(ctx context.Context, tokenHash string) error
}

DeleteSessionStore is the part of the database DeleteSession needs.

type Evaluator

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

func NewEvaluator

func NewEvaluator(db EvaluatorStore, log *logger.Logger, allowAnonymousRead bool) *Evaluator

func (*Evaluator) DecideProject added in v0.6.0

func (e *Evaluator) DecideProject(
	ctx context.Context,
	principal Principal,
	projectName string,
	action ProjectAction,
) (ProjectDecision, error)

DecideProject answers a project control-plane check for the project with the given name: a global admin always passes (a missing project is then the handler's 404); anybody else needs a role that is high enough, and a caller without any role sees ProjectHidden whether or not the project exists.

func (*Evaluator) Evaluate

func (e *Evaluator) Evaluate(ctx context.Context, principal Principal, repoName, artifactPath, action string) (bool, error)

func (*Evaluator) EvaluateProject added in v0.6.0

func (e *Evaluator) EvaluateProject(ctx context.Context, principal Principal, projectName string, action ProjectAction) (bool, error)

EvaluateProject reports whether the principal may perform action on the named project. A global admin may; so may a member whose role is high enough. An unknown project is never allowed (except to an admin, whose handler 404s).

func (*Evaluator) EvaluateRepoAdmin added in v0.6.0

func (e *Evaluator) EvaluateRepoAdmin(ctx context.Context, principal Principal, repoName string) (bool, error)

EvaluateRepoAdmin reports whether the principal may administer the named repository: configure or delete it, manage its cleanup policies and quota, empty its trash. A global admin may, and so may a maintainer or owner of the repository's project. A repository-scoped "manage" permission target does not qualify (it only covers what it always did), and neither does a project role pass Evaluate(..., "manage"). Anonymous callers, deploy tokens, scoped tokens and repositories of the system project never qualify except for a global admin; an unknown repository is never administrable.

func (*Evaluator) PathReadFilter added in v0.8.0

func (e *Evaluator) PathReadFilter(
	ctx context.Context,
	principal Principal,
) (func(repo *models.Repository, artifactPath string) (bool, error), error)

PathReadFilter is RepoReadFilter for an artifact path inside the repository: the returned predicate reports whether the principal may read artifactPath of a repository, so a permission target whose path_pattern limits it to part of the repository (one docker image, say) is matched against the path. The targets are loaded once, however many (repository, path) pairs are checked.

func (*Evaluator) ProjectRole added in v0.6.0

func (e *Evaluator) ProjectRole(ctx context.Context, principal Principal, projectID string) (string, bool, error)

ProjectRole returns the principal's role in the project (empty for a non-member) and whether the principal is a global admin. The role never includes the admin's implicit ownership: callers combine both through ProjectRoleAllows. Anonymous callers, deploy tokens, scoped tokens and the system project (which grants nothing) have no role.

func (*Evaluator) ProjectRoles added in v0.6.0

func (e *Evaluator) ProjectRoles(ctx context.Context, principal Principal) (map[string]string, error)

ProjectRoles returns the principal's role per project ID (the highest of its recorded ownership, membership and group grants), without the implicit ownership of global admins. Anonymous callers, deploy tokens, scoped tokens and the system project yield nothing.

func (*Evaluator) RepoReadFilter added in v0.2.0

func (e *Evaluator) RepoReadFilter(ctx context.Context, principal Principal) (func(repo *models.Repository) (bool, error), error)

RepoReadFilter returns a predicate reporting whether the principal may read a repository by name. The principal's permission targets are loaded once, so filtering N repositories costs one query instead of N. Project roles apply as in Evaluate (decided from the repository's ProjectID).

type EvaluatorStore added in v0.15.0

type EvaluatorStore interface {
	GetPermissionTargetByName(ctx context.Context, name string) (*models.PermissionTarget, error)
	GetPermissionTargetsForPrincipal(ctx context.Context, userID string, groupIDs []string) ([]*models.PermissionTarget, error)
	GetPermissionTargetsByIDs(ctx context.Context, ids []string) ([]*models.PermissionTarget, error)
	GetProjectByName(ctx context.Context, name string) (*models.Project, error)
	GetRepositoryByName(ctx context.Context, name string) (*models.Repository, error)
	ListProjectGrantsByUser(ctx context.Context, userID string) ([]*models.ProjectGrant, error)
	ListPublicRepositoryNames(ctx context.Context) ([]string, error)
}

EvaluatorStore is the part of the database Evaluator needs.

type ExchangeResult added in v0.8.0

type ExchangeResult struct {
	// Provider is the provider that produced the result; after a key-rotation
	// reload it is the freshly loaded one.
	Provider *OIDCProvider
	// AccessToken is the OAuth 2.0 access token. It is a credential: never log it.
	AccessToken string
	// RawIDToken, IDToken and Claims are set for OIDC providers only; Claims
	// are the verified ID token claims.
	RawIDToken string
	IDToken    *gooidc.IDToken
	Claims     map[string]any
}

ExchangeResult is the outcome of redeeming an authorization code.

func ExchangeWithRetry

func ExchangeWithRetry(ctx context.Context, db ExchangeWithRetryStore, slug, baseURL, code, codeVerifier string) (*ExchangeResult, error)

ExchangeWithRetry redeems the authorization code exactly once. If the ID token fails with go-oidc's signature-verification error (possible key rotation), the same raw ID token is re-verified with a freshly loaded provider; the code is never re-exchanged. Reloads are limited to one per provider per oidcReloadMinInterval. Plain OAuth 2.0 providers only get the token exchange; their identity comes from Identity.

type ExchangeWithRetryStore added in v0.15.0

type ExchangeWithRetryStore interface {
	LoadOIDCProviderStore
}

ExchangeWithRetryStore is the part of the database ExchangeWithRetry needs.

type LoadOIDCProviderStore added in v0.15.0

type LoadOIDCProviderStore interface {
	GetSSOProviderBySlug(ctx context.Context, slug string) (*models.SSOProvider, error)
}

LoadOIDCProviderStore is the part of the database LoadOIDCProvider needs.

type LoadSAMLProviderStore added in v0.15.0

type LoadSAMLProviderStore interface {
	CreateSystemSettingIfAbsent(ctx context.Context, key string, value string) (bool, error)
	GetSSOProviderBySlug(ctx context.Context, slug string) (*models.SSOProvider, error)
	GetSystemSetting(ctx context.Context, key string) (string, error)
}

LoadSAMLProviderStore is the part of the database LoadSAMLProvider needs.

type LookupSessionSSOStore added in v0.15.0

type LookupSessionSSOStore interface {
	GetSessionSSO(ctx context.Context, tokenHash string) (*models.SessionSSO, error)
}

LookupSessionSSOStore is the part of the database LookupSessionSSO needs.

type OIDCIssuersStore added in v0.15.0

type OIDCIssuersStore interface {
	ListEnabledSSOProviders(ctx context.Context) ([]*models.SSOProvider, error)
}

OIDCIssuersStore is the part of the database OIDCIssuers needs.

type OIDCProvider

type OIDCProvider struct {
	Slug          string
	Provider      *gooidc.Provider
	Verifier      *gooidc.IDTokenVerifier
	Config        oauth2.Config
	Cfg           models.OIDCConfig
	UpdatedAt     time.Time
	EndSessionURL string
	// contains filtered or unexported fields
}

OIDCProvider is a loaded "oidc" kind provider. For Type "" it carries the discovery result and ID token verifier; for the plain OAuth 2.0 flavours (github, oauth2) Provider and Verifier are nil and identity comes from API calls made with the access token (see Identity).

func LoadOIDCProvider

func LoadOIDCProvider(ctx context.Context, db LoadOIDCProviderStore, slug, baseURL string) (*OIDCProvider, error)

LoadOIDCProvider loads an enabled OIDC provider. Disabled providers are rejected with ErrSSOProviderDisabled.

func LoadOIDCProviderRow added in v0.2.0

func LoadOIDCProviderRow(ctx context.Context, row *models.SSOProvider, baseURL string) (*OIDCProvider, error)

LoadOIDCProviderRow builds the provider for an already-fetched row without checking Enabled; it exists so admins can test-connect a disabled provider. Public login paths MUST use LoadOIDCProvider.

func (*OIDCProvider) AuthURL

func (p *OIDCProvider) AuthURL(state, nonce, codeChallenge string) string

AuthURL builds the authorization redirect. The nonce is bound into the ID token and therefore only sent for OIDC providers.

func (*OIDCProvider) EndSession

func (p *OIDCProvider) EndSession(idTokenHint, postLogoutRedirectURI string) (string, bool)

EndSession builds the RP-initiated logout URL (OIDC RP-Initiated Logout 1.0) for the IdP's end_session_endpoint. ok is false when the IdP has none, or when it is not an http(s) URL (the SPA navigates to the result).

func (*OIDCProvider) Identity added in v0.8.0

func (p *OIDCProvider) Identity(ctx context.Context, res *ExchangeResult, log *logger.Logger) (SSOClaims, error)

Identity turns a completed exchange into the claims the provisioner consumes, after applying the provider's login policy. For OIDC it maps the verified ID token claims (plus Entra groups overage resolution); for the OAuth 2.0 flavours it queries the provider's API with the access token. A policy rejection is an ErrSSOLoginDenied.

func (*OIDCProvider) IsOAuth2 added in v0.8.0

func (p *OIDCProvider) IsOAuth2() bool

IsOAuth2 reports whether the provider is a plain OAuth 2.0 flavour (GitHub or generic) that has no discovery document, ID token or nonce.

type Principal

type Principal struct {
	UserID             *string
	Username           string
	GroupIDs           []string
	IsAnonymous        bool
	IsLegacy           bool
	MustChangePassword bool
	// Credential is how the request authenticated (Credential* constants).
	// Ambient credentials (session cookie) require CSRF protection; explicit
	// ones (token headers, legacy key) do not.
	Credential string
	// TokenKind and TokenScopes describe the credential when the request was
	// authenticated with a personal/deploy token. They are empty for session
	// and legacy-key authentication. TokenScopes holds permission-target IDs:
	// when non-empty the token's rights are the intersection of those targets
	// (assigned to the owner or not) and the owner's own rights.
	TokenKind   string
	TokenScopes []string
	// TokenID is the id of that token (audit events record it).
	TokenID string
	// ServiceProjectID is set for a project token's service account: the only
	// project the principal belongs to. Such a principal ignores permission
	// targets and holds only the role of its own project.
	ServiceProjectID string
}

func (Principal) IsToken added in v0.2.0

func (p Principal) IsToken() bool

IsToken reports whether the request was authenticated with an API token.

type ProjectAction added in v0.6.0

type ProjectAction string

ProjectAction is a control-plane action on a project (as opposed to the data actions read/write/delete on its repositories, see project_roles.go).

const (
	// ProjectActionRead: see the project, its repositories, members and groups (viewer).
	ProjectActionRead ProjectAction = "project.read"
	// ProjectActionMembersManage: add, change and remove members and groups
	// below the maintainer role (maintainer). Granting or changing maintainer
	// and owner roles takes an owner; the handler enforces that per target.
	ProjectActionMembersManage ProjectAction = "members.manage"
	// ProjectActionTokens: list, mint and revoke project tokens (viewer). A
	// viewer only sees and revokes the tokens it minted itself; maintainers
	// see and revoke all of them (the handler enforces that per token).
	ProjectActionTokens ProjectAction = "tokens.create"
	// ProjectActionUpdate: edit display name and description (owner).
	ProjectActionUpdate ProjectAction = "project.update"
	// ProjectActionDelete: delete the project (owner).
	ProjectActionDelete ProjectAction = "project.delete"
	// ProjectActionRepoCreate: create a repository in the project (maintainer).
	ProjectActionRepoCreate ProjectAction = "repo.create"
	// ProjectActionRepoAdmin: update, delete and run the cleanup, quota and trash
	// of a repository of the project (maintainer); see EvaluateRepoAdmin.
	ProjectActionRepoAdmin ProjectAction = "repo.admin"
	// ProjectActionRepoTransfer: move a repository out of the project (owner;
	// the handler also needs ownership of the target project).
	ProjectActionRepoTransfer ProjectAction = "repo.transfer"
)

Project control-plane actions. Each needs a minimum project role; a global admin (the "manage" permission) is an implicit owner of every project.

type ProjectDecision added in v0.6.0

type ProjectDecision int

ProjectDecision is the outcome of a project control-plane check.

const (
	// ProjectAllow: the action is permitted.
	ProjectAllow ProjectDecision = iota
	// ProjectForbidden: the caller sees the project (holds a role) but the role
	// is too low for the action (HTTP 403).
	ProjectForbidden
	// ProjectHidden: the caller has no role in the project, or the project does
	// not exist: both look the same (HTTP 404), so existence does not leak.
	ProjectHidden
)

func ProjectDecisionFor added in v0.6.0

func ProjectDecisionFor(role string, admin bool, action ProjectAction) ProjectDecision

ProjectDecisionFor maps a role to the outcome for action: allowed, forbidden (a role that is too low) or hidden (no role at all).

type ProjectSettings added in v0.6.0

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

ProjectSettings is the effective project configuration: stored system settings layered over the config defaults.

func NewProjectSettings added in v0.6.0

func NewProjectSettings(store SettingStore, selfCreateDefault bool) *ProjectSettings

NewProjectSettings returns the project settings; selfCreateDefault is the config/env value used until an administrator saves the setting.

func (*ProjectSettings) SelfCreate added in v0.6.0

func (s *ProjectSettings) SelfCreate(ctx context.Context) (bool, error)

SelfCreate reports whether any authenticated user may create projects. A stored value wins over the config default; an unreadable or malformed value fails closed (off), because it widens who may create projects.

func (*ProjectSettings) SetSelfCreate added in v0.6.0

func (s *ProjectSettings) SetSelfCreate(ctx context.Context, on bool) error

SetSelfCreate stores the setting; it overrides the config default from now on.

type Provisioner

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

func NewProvisioner

func NewProvisioner(db ProvisionerStore, log *logger.Logger) *Provisioner

func (*Provisioner) Provision

func (p *Provisioner) Provision(ctx context.Context, provider *models.SSOProvider, claims SSOClaims) (*models.User, error)

func (*Provisioner) SyncSSOGroupsFromClaims

func (p *Provisioner) SyncSSOGroupsFromClaims(ctx context.Context, userID string, provider *models.SSOProvider, idpGroups []string) error

func (*Provisioner) SyncSSOPermissionsFromGroups

func (p *Provisioner) SyncSSOPermissionsFromGroups(ctx context.Context, provider *models.SSOProvider, idpGroups []string) error

SyncSSOPermissionsFromGroups grants the mapped permission target to every local group the logging-in user holds through the IdP group mapping.

It is deliberately add-only. Permission assignments on a group are shared by all of its members, so removing one based on a single user's claims would strip access from every other member (and flap with login order). Revoking a mapping is done by an admin editing the assignment, not by a login.

type ProvisionerStore added in v0.15.0

type ProvisionerStore interface {
	CreateUser(ctx context.Context, user *models.User) (*models.User, error)
	GetGroupByName(ctx context.Context, name string) (*models.Group, error)
	GetOrCreateGroup(ctx context.Context, name string) (*models.Group, error)
	GetOrCreatePermissionAssignment(ctx context.Context, targetID string, principalType string, principalID string) error
	GetPermissionTargetByName(ctx context.Context, name string) (*models.PermissionTarget, error)
	GetUserByEmail(ctx context.Context, email string) (*models.User, error)
	GetUserByExternalID(ctx context.Context, externalID string, providerSlug string) (*models.User, error)
	GetUserByUsername(ctx context.Context, username string) (*models.User, error)
	SyncSSOGroups(ctx context.Context, userID string, groupIDs []string) error
	UpdateUserSSO(ctx context.Context, userID string, externalID string, providerSlug string) error
	UpdateUserSSOProfile(ctx context.Context, id string, email *string, fullName *string, lastLogin time.Time) error
}

ProvisionerStore is the part of the database Provisioner needs.

type RevokeAllSessionsStore added in v0.15.0

type RevokeAllSessionsStore interface {
	DeleteSessionsByUser(ctx context.Context, userID string) error
}

RevokeAllSessionsStore is the part of the database RevokeAllSessions needs.

type RevokeOtherSessionsStore added in v0.15.0

type RevokeOtherSessionsStore interface {
	DeleteOtherSessionsByUser(ctx context.Context, userID string, keepTokenHash string) error
	DeleteSessionsByUser(ctx context.Context, userID string) error
}

RevokeOtherSessionsStore is the part of the database RevokeOtherSessions needs.

type SAMLCallbackStore added in v0.15.0

type SAMLCallbackStore interface {
	// contains filtered or unexported methods
}

SAMLCallbackStore is the part of the database SAMLProviderParseCallback needs.

type SAMLProvider

type SAMLProvider struct {
	Slug string
	Cfg  models.SAMLConfig
	// SP is the strict service provider: it only accepts a response to an
	// AuthnRequest tracked by StartLogin.
	SP       *samlsp.Middleware
	EntityID string
	AcsURL   string
	// contains filtered or unexported fields
}

func LoadSAMLProvider

func LoadSAMLProvider(
	ctx context.Context,
	db LoadSAMLProviderStore,
	slug, baseURL string,
	appCfg *config.Config,
	log *logger.Logger,
) (*SAMLProvider, error)

LoadSAMLProvider loads an enabled SAML provider. Disabled providers are rejected with ErrSSOProviderDisabled.

func LoadSAMLProviderRow added in v0.2.0

func LoadSAMLProviderRow(
	ctx context.Context,
	store SettingsStore,
	row *models.SSOProvider,
	baseURL string,
	appCfg *config.Config,
	log *logger.Logger,
) (*SAMLProvider, error)

LoadSAMLProviderRow builds the provider for an already-fetched row without checking Enabled; it exists so admins can test-connect a disabled provider. Public login paths MUST use LoadSAMLProvider. store persists the generated SP keypair when none is configured.

func (*SAMLProvider) MetadataXML

func (p *SAMLProvider) MetadataXML() ([]byte, error)

func (*SAMLProvider) ParseCallback

func (p *SAMLProvider) ParseCallback(
	w http.ResponseWriter,
	r *http.Request,
	db SAMLCallbackStore,
	trackerKey []byte,
) (*saml.Assertion, error)

ParseCallback validates a SAML response at the ACS and returns its verified assertion. See ResponseMode for the two paths.

SP-initiated: the response must answer the AuthnRequest tracked by StartLogin (signed cookie, InResponseTo), carry a valid signature, audience and time window, and its assertion ID must not have been seen before. The tracker cookie is cleared whatever the outcome (single use).

IdP-initiated (opt-in): the same validation, with InResponseTo required to be empty on the response and on every SubjectConfirmationData; no tracker is consulted and an SP-initiated tracker cookie is left alone.

func (*SAMLProvider) ResponseMode added in v0.8.0

func (p *SAMLProvider) ResponseMode(r *http.Request) SAMLResponseMode

ResponseMode routes an ACS request. It peeks at Response/@InResponseTo in the (still unverified) document: a response that names a request is SP-initiated; one that names none is IdP-initiated, which only a provider with allow_idp_initiated serves. The peek is a routing hint, never a security decision: each path validates the response in full, and the IdP-initiated path itself insists on an empty InResponseTo, so a document that lies to the peek is rejected either way.

func (*SAMLProvider) StartLogin added in v0.2.0

func (p *SAMLProvider) StartLogin(w http.ResponseWriter, relayState string, trackerKey []byte) (string, error)

StartLogin builds the AuthnRequest, records its ID in a signed, short-lived cookie scoped to the ACS path, and returns the IdP redirect URL. The ACS refuses any response that is not an answer to a request tracked this way.

type SAMLResponseMode added in v0.8.0

type SAMLResponseMode int

SAMLResponseMode says how an ACS request is validated.

const (
	// SAMLSPInitiated: the response must answer a request tracked by StartLogin.
	SAMLSPInitiated SAMLResponseMode = iota
	// SAMLIDPInitiated: an unsolicited response, accepted only when the provider
	// enables it.
	SAMLIDPInitiated
)

type SSOClaims

type SSOClaims struct {
	ExternalID   string
	ProviderSlug string
	Username     string
	Email        string
	// EmailVerified is true only when the IdP asserted that Email is verified
	// (OIDC email_verified == true). Unverified emails are never used to link
	// to, or overwrite the email of, an existing account.
	EmailVerified bool
	FullName      string
	Groups        []string
	// GroupsPresent distinguishes "the IdP did not tell us the user's groups"
	// (claim or attribute absent, Entra overage not resolved) from "the IdP
	// says the user has no groups". Only a present set, even an empty one,
	// replaces the user's SSO-managed memberships; an absent one keeps them,
	// so a misconfigured IdP cannot silently revoke group access.
	GroupsPresent bool
}

type SessionSSOInfo added in v0.8.0

type SessionSSOInfo struct {
	ProviderSlug string
	IDToken      string
}

SessionSSOInfo is the decrypted SSO record of a session.

func LookupSessionSSO added in v0.8.0

func LookupSessionSSO(ctx context.Context, db LookupSessionSSOStore, cookieValue string) (*SessionSSOInfo, error)

LookupSessionSSO returns the SSO provider and ID token behind a session cookie, or nil when the session is not an SSO session (or is unknown).

type SettingStore added in v0.6.0

type SettingStore interface {
	GetSystemSetting(ctx context.Context, key string) (string, error)
	SetSystemSetting(ctx context.Context, key, value string) error
}

SettingStore reads and writes system settings (*database.PostgresDB satisfies it).

type SettingsStore added in v0.8.0

type SettingsStore interface {
	GetSystemSetting(ctx context.Context, key string) (string, error)
	CreateSystemSettingIfAbsent(ctx context.Context, key, value string) (bool, error)
}

SettingsStore is the part of the database the generated SSO keys need.

type TouchSessionStore added in v0.15.0

type TouchSessionStore interface {
	UpdateSessionLastSeen(ctx context.Context, sessionID string, expiresAt time.Time) error
}

TouchSessionStore is the part of the database TouchSession needs.

type TouchTokenStore added in v0.15.0

type TouchTokenStore interface {
	UpdateLastUsedStore
}

TouchTokenStore is the part of the database TouchToken needs.

type UpdateLastUsedStore added in v0.15.0

type UpdateLastUsedStore interface {
	UpdateTokenLastUsed(ctx context.Context, tokenID string) error
}

UpdateLastUsedStore is the part of the database UpdateLastUsed needs.

type ValidateSessionStore added in v0.15.0

type ValidateSessionStore interface {
	GetSessionByTokenHash(ctx context.Context, hash string) (*models.Session, error)
}

ValidateSessionStore is the part of the database ValidateSession needs.

type ValidateTokenStore added in v0.15.0

type ValidateTokenStore interface {
	GetTokenByHash(ctx context.Context, hash string) (*models.Token, error)
	GetUserByID(ctx context.Context, id string) (*models.User, error)
}

ValidateTokenStore is the part of the database ValidateToken needs.

type VerifyOIDCAccessTokenStore added in v0.15.0

type VerifyOIDCAccessTokenStore interface {
	ListEnabledSSOProviders(ctx context.Context) ([]*models.SSOProvider, error)
	// contains filtered or unexported methods
}

VerifyOIDCAccessTokenStore is the part of the database VerifyOIDCAccessToken needs.

Jump to

Keyboard shortcuts

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