gitlabroles

package
v0.56.1-rc.1 Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2026 License: Apache-2.0 Imports: 9 Imported by: 0

Documentation

Overview

Package gitlabroles defines the GitLab role-credential contract (#7497, #7559, #7782).

Built-in Poller, Analyst, and Coder identities and administrator- registered custom roles are the same kind of Registry entry. Resolve selects a credential from that registry; it does not branch on a three-role enum.

This package is the internal contract for provisioning (#7498), routing (#7499), and rotation/recovery (#7500). Select / SelectAgent / Require are the dispatch-time entry points wired into fullsend poll, fullsend run, and post-review. DiagnoseLifecycle reports expiry, revocation, and overlapping tokens. CheckBuiltinReadiness is the #7501 verification for Poller, Analyst, and Coder; it does not perform legacy credential cleanup.

Runtime authentication is role-credential only: Resolve and Select select the registered role credential and never read a shared token or migration state.

Canonical documentation: docs/contributing/gitlab-role-credentials.md.

Index

Constants

View Source
const (
	PollerTokenName  = "fullsend-poller"
	AnalystTokenName = "fullsend-analyst"
	CoderTokenName   = "fullsend-coder"
)

Built-in project access token names. Custom own-credential names are derived by CustomTokenName (fullsend-role-<name>).

View Source
const DefaultRotationGrace = 24 * time.Hour

DefaultRotationGrace is how long the previous PAT stays active after a successful distribution so in-flight jobs that already hold it in their environment can finish.

View Source
const DefaultRotationLead = 30 * 24 * time.Hour

DefaultRotationLead is how far ahead of expiry a role credential is treated as due for rotation. GitLab PATs expire in at most one year.

View Source
const DeveloperAccessLevel = 30

DeveloperAccessLevel is GitLab's Developer (30) access. Role tokens use the same access level as the current shared bot PAT; GitLab project-token scopes cannot express finer boundaries.

View Source
const IdempotentRotationWindow = 5 * time.Minute

IdempotentRotationWindow is how long a just-distributed replacement is treated as the current credential for concurrent/retry attempts.

View Source
const PollerBootstrapTokenName = "fullsend-poller-bootstrap"

PollerBootstrapTokenName names the installer-only personal access token the install creates on the Poller service account for the duration of one pipeline-trigger creation (#8083). It is never published to CI/CD variables, logs, or agent environments, and it is revoked before the replacement runtime Poller credential is published.

View Source
const SharedTokenName = "fullsend-bot"

SharedTokenName is the project access token name for the shared bot PAT stored as FULLSEND_FORGE_TOKEN.

Variables

View Source
var ErrAuthFailed = errors.New("GitLab role credential authentication failed")

ErrAuthFailed indicates a role credential already failed authentication during this job; Resolve never switches identities after this.

View Source
var ErrCapabilityDenied = errors.New("GitLab role lacks required capability")

ErrCapabilityDenied indicates a registered role does not declare a required capability. Routing uses this so Analyst cannot perform code writes, Poller cannot change application code, and Coder cannot act as the Analyst approval identity through the normal role configuration.

View Source
var ErrIdentityMismatch = errors.New("authenticating GitLab token does not match selected role credential")

ErrIdentityMismatch indicates the token that will actually authenticate a GitLab API call does not match the CI/CD variable value for the dispatch-selected role. A capability check against the selected role is meaningless if a different credential ends up authenticating the call, so callers must verify the two agree before trusting Require's result.

View Source
var ErrInvalidRegistry = errors.New("invalid GitLab role registry")

ErrInvalidRegistry indicates FULLSEND_GITLAB_ROLE_REGISTRY failed to parse or validate as a role registry document.

View Source
var ErrUnconfigured = errors.New("GitLab role credential is not provisioned")

ErrUnconfigured indicates a registered role's credential secret is not yet provisioned.

View Source
var ErrUnknownJob = errors.New("job has no GitLab role mapping")

ErrUnknownJob indicates a Job has no name to resolve (an empty agent name, or a Kind Resolve does not recognize).

View Source
var ErrUnregistered = errors.New("GitLab role is not registered")

ErrUnregistered indicates a job's agent name or harness role does not match any registered role in the registry.

Functions

func AnnotateTokenLifecycle added in v0.46.0

func AnnotateTokenLifecycle(rr *RoleReport, tok TokenSnapshot, now time.Time, lead time.Duration)

AnnotateTokenLifecycle sets rr's lifecycle, expiry, and token IDs from the one token tok, with the same expiry, revocation, and lead-time rules as DiagnoseLifecycle. A lead of 0 uses DefaultRotationLead and a zero now uses time.Now. Any lifecycle state already on rr (overlap, expiry, token IDs) is discarded first, so re-annotating a report reflects only tok.

func AuthFailed

func AuthFailed(role Role, secret string) error

AuthFailed is the fail-closed annotation for a runtime 401/403 (or equivalent) of a selected credential. Callers must not Resolve again with a different job or a cleared FailedSecret.

func CustomSecretName

func CustomSecretName(role Role) string

CustomSecretName is the derived CI/CD variable for a custom role's own credential. Hyphens become underscores.

func CustomTokenName

func CustomTokenName(role Role) string

CustomTokenName is the GitLab project access token name for a custom role's own credential.

func IsManagedPollerTokenName added in v0.46.0

func IsManagedPollerTokenName(name string) bool

IsManagedPollerTokenName reports whether Fullsend creates and may revoke a credential with this name on the managed Poller account.

func IsRoleProjectTokenName

func IsRoleProjectTokenName(name string) bool

IsRoleProjectTokenName reports whether name is a built-in or custom role project access token (not the shared fullsend-bot token).

func MarshalCustomRoles

func MarshalCustomRoles(reg Registry) (string, error)

MarshalCustomRoles serializes administrator-registered custom roles as FULLSEND_GITLAB_ROLE_REGISTRY JSON. Built-in roles are omitted; an empty custom set is {"roles":[]}, which ParseRegistry treats as built-ins only. The document contains credential references and policy, never token values.

func PresenceFrom

func PresenceFrom(getenv func(string) string, reg Registry) map[string]bool

PresenceFrom snapshots each registered role secret. A nil getenv uses os.Getenv. A zero registry means built-in roles only. Values are not retained.

func RefreshLifecycleDiagnostics

func RefreshLifecycleDiagnostics(rep *Report, oldCount int)

RefreshLifecycleDiagnostics rebuilds the lifecycle portion of a report's diagnostics after callers change a role lifecycle based on trusted proof. oldCount is the lifecycle-message count before those changes. DiagnoseLifecycle appends lifecycle messages after the base diagnosis, so trimming that count preserves the base diagnostics.

func RegistryVariableName

func RegistryVariableName() string

RegistryVariableName is FULLSEND_GITLAB_ROLE_REGISTRY.

func Require

func Require(rec Registration, cap Capability) error

Require reports ErrCapabilityDenied when rec does not declare cap.

func RoleDueForRotation

func RoleDueForRotation(rr RoleReport) bool

RoleDueForRotation reports whether a role should be rotated: expired, expiring, revoked, or unverified (recovery). Overlapping is cleanup, not a new mint. Unconfigured is provisioning, not rotation.

func TokenScopes

func TokenScopes() []string

TokenScopes is the GitLab PAT scope list for every role token.

Types

type BuiltinReadiness

type BuiltinReadiness struct {
	Roles       []BuiltinRoleCheck
	Ready       bool
	Missing     []Role
	Diagnostics []string
}

BuiltinReadiness is the #7501 verification for Poller, Analyst, and Coder. It does not perform legacy credential cleanup. Ready is true only when every built-in role is provisioned, declares its required capabilities, omits the capabilities it must not hold, and maps its jobs onto that identity. Legacy shared-token presence never makes a missing built-in role ready.

func CheckBuiltinReadiness

func CheckBuiltinReadiness(present map[string]bool, reg Registry) BuiltinReadiness

CheckBuiltinReadiness verifies Poller, Analyst, and Coder against the identity and capability contract. Custom roles are ignored; shared- token presence is reported and never used as a substitute. A zero registry means built-ins only.

func (BuiltinReadiness) WithLifecycle

func (br BuiltinReadiness) WithLifecycle(lifecycle map[Role]LifecycleState) BuiltinReadiness

WithLifecycle downgrades a role's readiness to not-ready when its credential lifecycle is expired, revoked, or unverified. A present secret is not sufficient for readiness if its project access token is unusable.

type BuiltinRoleCheck

type BuiltinRoleCheck struct {
	Name         Role
	SecretName   string
	TokenName    string
	Present      bool
	Ready        bool
	Capabilities []Capability
	Jobs         []string
	Reasons      []string
}

BuiltinRoleCheck is the readiness result for one built-in GitLab role. Reasons carry secret *names* only.

type Capability

type Capability string

Capability is policy metadata used for validation. GitLab project tokens still use the coarse `api` scope; these flags are the contract routing (#7499) enforces, not GitLab ACL grants.

const (
	CapReadIssues          Capability = "read_issues"
	CapWriteIssues         Capability = "write_issues"
	CapWriteNotes          Capability = "write_notes"
	CapWriteLabels         Capability = "write_labels"
	CapDispatchPipeline    Capability = "dispatch_pipeline"
	CapWritePollState      Capability = "write_poll_state"
	CapWriteRepository     Capability = "write_repository"
	CapWriteMergeRequest   Capability = "write_merge_request"
	CapApproveMergeRequest Capability = "approve_merge_request"
)

func KnownCapabilities

func KnownCapabilities() []Capability

KnownCapabilities returns the capability vocabulary in stable order.

type CredentialKind

type CredentialKind string

CredentialKind is how a registered role obtains its token.

const (
	// CredentialOwn means the role has its own CI/CD secret.
	CredentialOwn CredentialKind = "own"
	// CredentialReuse means the role shares another registered role's
	// credential. The registry stores a reference, not a copy of the
	// secret value.
	CredentialReuse CredentialKind = "reuse"
)

type CredentialRef

type CredentialRef struct {
	Kind       CredentialKind
	SecretName string
	ReuseOf    Role
	TokenName  string
}

CredentialRef is a reference to a role credential. SecretName is a CI/CD variable name, never a token value.

type Error

type Error struct {
	Role   Role
	Secret string
	Err    error
}

Error annotates a sentinel with the role and secret name involved. Secret is a CI/CD variable name, never a token value.

func (*Error) Error

func (e *Error) Error() string

func (*Error) Unwrap

func (e *Error) Unwrap() error

type Job

type Job struct {
	Kind Kind
	// Name is an agent name or harness role (e.g. "review", "coder").
	// Ignored when Kind is KindPoller.
	Name string
}

Job selects which GitLab identity a process needs.

func AgentJob

func AgentJob(name string) Job

AgentJob is a harness/agent run identified by agent name or harness role.

func JobForAgent

func JobForAgent(reg Registry, agentName, harnessRole string) Job

JobForAgent maps a running agent onto a Job. Prefer the agent name when it is registered; otherwise use the harness role: field.

func PollerJob

func PollerJob() Job

PollerJob is the GitLab poller/controller, not an agent harness.

type Kind

type Kind string

Kind identifies the job that needs a GitLab credential.

const (
	KindPoller Kind = "poller"
	KindAgent  Kind = "agent"
)

type LifecycleState

type LifecycleState string

LifecycleState is presence plus expiry/revocation for one role.

const (
	// LifecycleUnknown means no token inventory was supplied.
	LifecycleUnknown LifecycleState = ""
	// LifecycleOK is a present secret with a matching active PAT that
	// is not inside the rotation lead time.
	LifecycleOK LifecycleState = "ok"
	// LifecycleExpiring is an active PAT whose expiry is within the lead.
	LifecycleExpiring LifecycleState = "expiring"
	// LifecycleExpired is a PAT whose expiry date has passed.
	LifecycleExpired LifecycleState = "expired"
	// LifecycleRevoked is a listed PAT that is inactive, or every
	// matching PAT is inactive, while the CI secret is still present.
	LifecycleRevoked LifecycleState = "revoked"
	// LifecycleUnverified is a present secret with no matching project
	// access token (enrolled PAT, or a token GitLab no longer lists).
	LifecycleUnverified LifecycleState = "unverified"
	// LifecycleOverlapping means two or more active PATs share this
	// role's token name: a replacement has been distributed and the
	// previous credential remains usable for in-flight jobs.
	LifecycleOverlapping LifecycleState = "overlapping"
	// LifecycleUnconfigured is a registered role whose secret is absent.
	LifecycleUnconfigured LifecycleState = "unconfigured"
)

type RegisteredReadiness

type RegisteredReadiness struct {
	Roles       []RegisteredRoleReadiness
	Ready       bool
	Missing     []Role
	Diagnostics []string
}

RegisteredReadiness verifies every role in the registry, including custom roles. It is the authorization check role routing enforces. A custom role with no agent mapping is not ready, and every mapped agent must resolve to that role's own credential.

func CheckRegisteredReadiness

func CheckRegisteredReadiness(present map[string]bool, reg Registry) RegisteredReadiness

CheckRegisteredReadiness verifies all registered roles without inspecting credential values. Built-in capability invariants are checked separately by CheckBuiltinReadiness; this function verifies registration completeness and enforced routing for both built-in and custom roles.

func (RegisteredReadiness) WithLifecycle

func (rr RegisteredReadiness) WithLifecycle(lifecycle map[Role]LifecycleState) RegisteredReadiness

WithLifecycle applies token-inventory health to registered-role readiness. It uses the same blocking lifecycle states as built-in readiness while leaving expiring and overlapping credentials usable for a controlled transition.

type RegisteredRoleReadiness

type RegisteredRoleReadiness struct {
	Name       Role
	SecretName string
	Present    bool
	Ready      bool
	Agents     []string
	Reasons    []string
}

RegisteredRoleReadiness is the readiness result for one registered role. Unlike BuiltinRoleCheck, it does not assume a fixed capability contract: administrator-registered roles are verified against the policy they declared in the trusted registry and against every agent they claim.

type Registration

type Registration struct {
	Name           Role
	Kind           RoleKind
	Responsibility string
	Credential     CredentialRef
	Capabilities   []Capability
	Agents         []string
}

Registration is one allowlisted role in the trusted registry.

func (Registration) Has

func (r Registration) Has(c Capability) bool

Has reports whether the registration declares capability c.

type Registry

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

Registry is the administrator-controlled allowlist of GitLab responsibility identities. Built-in Poller, Analyst, and Coder are always present. Custom roles come only from installation state (FULLSEND_GITLAB_ROLE_REGISTRY). Repository files, harness documents, and merge-request content are not sources of registration and cannot elevate a role.

func BuiltinRegistry

func BuiltinRegistry() Registry

BuiltinRegistry returns the three built-in roles and no custom roles. Existing installations with an empty registry variable use this set.

func LoadRegistry

func LoadRegistry(getenv func(string) string) (Registry, error)

LoadRegistry reads FULLSEND_GITLAB_ROLE_REGISTRY via getenv. A nil getenv uses os.Getenv. This is the only supported way to load custom roles.

func ParseRegistry

func ParseRegistry(raw string) (Registry, error)

ParseRegistry reads administrator registry JSON and merges it with the built-in roles. Empty or whitespace-only input is built-ins only. The document may contain credential references and policy, never raw secret values.

func (Registry) Lookup

func (r Registry) Lookup(name Role) (Registration, bool)

Lookup returns the registration for a role name.

func (Registry) Registrations

func (r Registry) Registrations() []Registration

Registrations returns a copy of the registered roles in stable order: built-ins first, then custom roles in document order.

func (Registry) RoleFor

func (r Registry) RoleFor(name string) (Registration, bool)

RoleFor maps an agent name or harness role onto a registered GitLab identity. Built-in aliases (review → analyst, code → coder) and custom agent names share this lookup.

func (Registry) ValidateAgent

func (r Registry) ValidateAgent(name string) error

ValidateAgent reports whether a custom agent (or harness role) may use name. Unregistered names return ErrUnregistered. Empty names return ErrUnknownJob.

type Report

type Report struct {
	Roles       []RoleReport
	Partial     bool
	Ready       bool
	Missing     []Role
	Diagnostics []string
}

Report is the observable role status. Diagnostics never include secret values.

Ready is true only when every registered role credential is present, for every registered role: it does not treat a lingering shared token as sufficient. This matches runtime credential selection (Resolve / Select / SelectAgent), which always requires the registered per-role secret and never reads a shared credential.

func Diagnose

func Diagnose(present map[string]bool, reg Registry) Report

Diagnose reports per-role presence, partial configuration, and readiness. Custom roles in the registry are included; an empty registry reports built-ins only.

See Report.Ready: this agrees with runtime credential selection (Resolve / Select / SelectAgent), which always requires the registered role secret, regardless of what Diagnose reports here.

func DiagnoseLifecycle

func DiagnoseLifecycle(present map[string]bool, reg Registry, tokens []TokenSnapshot, now time.Time, lead time.Duration) Report

DiagnoseLifecycle extends Diagnose with expiry, revocation, and overlapping-token classification. A nil tokens slice means inventory was not supplied and leaves Lifecycle empty; a non-nil empty slice is a successful empty inventory and classifies configured roles as unverified. lead of 0 uses DefaultRotationLead. now zero uses time.Now in UTC.

Diagnostics still carry names, dates, and token IDs only — never secret values. Runtime authentication failures stay ErrAuthFailed and never fall back to a different credential.

type Request

type Request struct {
	Job Job
	// Registry is the trusted allowlist. The zero value means built-in
	// roles only (existing installations).
	Registry Registry
	// Present reports whether each named CI/CD variable is non-empty.
	Present map[string]bool
	// FailedSecret is a secret *name* that already failed authentication
	// during this job. When set, Resolve refuses to select any other
	// identity.
	FailedSecret string
}

Request is the input to Resolve. Present maps secret/variable names to whether they are non-empty; it must never contain secret values.

type Role

type Role string

Role is a GitLab responsibility identity. Built-in and custom registered roles share this type; there is no closed enum.

const (
	RolePoller  Role = "poller"
	RoleAnalyst Role = "analyst"
	RoleCoder   Role = "coder"
)

func BuiltinRoles

func BuiltinRoles() []Role

BuiltinRoles returns Poller, Analyst, and Coder in stable order.

type RoleKind

type RoleKind string

RoleKind distinguishes built-in roles from administrator-registered custom roles. Both kinds are first-class Registry entries.

const (
	RoleKindBuiltin RoleKind = "builtin"
	RoleKindCustom  RoleKind = "custom"
)

type RoleReport

type RoleReport struct {
	Name       Role
	Kind       RoleKind
	SecretName string
	TokenName  string
	ReuseOf    Role
	State      RoleState
	// Lifecycle is presence plus expiry/revocation. Empty when no
	// token inventory was supplied to DiagnoseLifecycle.
	Lifecycle   LifecycleState
	ExpiresAt   string
	TokenIDs    []int
	Overlapping bool
}

RoleReport is the status of one registered role for Diagnose.

type RoleState

type RoleState string

RoleState is the configured/unconfigured status of one role secret. Presence is boolean. Expiry, revocation, and overlapping tokens are reported by DiagnoseLifecycle as LifecycleState on RoleReport.

const (
	RoleStateUnconfigured RoleState = "unconfigured"
	RoleStateConfigured   RoleState = "configured"
)

type Selection

type Selection struct {
	Job          Job
	Source       Source
	Registration Registration
	Registry     Registry
	Present      map[string]bool
}

Selection is the dispatch-time result of loading the trusted registry and secret-presence map, then resolving a job to a credential. Diagnostics and Error values carry secret *names* only.

func Select

func Select(job Job, getenv func(string) string) (Selection, error)

Select loads LoadRegistry and PresenceFrom via getenv (nil means os.Getenv), then resolves job. It does not read Migration state is not read. An unmapped agent name is always rejected with ValidateAgent before Resolve so unregistered custom agents fail closed rather than guessing an identity.

func SelectAgent

func SelectAgent(agentName, harnessRole string, getenv func(string) string) (Selection, error)

SelectAgent maps a running agent onto a registered identity and selects its credential. The agent name is preferred when it is a registered mapping (custom-role agents); otherwise the harness role: value is used so a custom agent may *reference* a registered identity without being listed in the registry document.

func (Selection) Diagnostics

func (s Selection) Diagnostics() []string

Diagnostics returns human-readable identity lines with names only.

func (Selection) IdentitySource

func (Selection) IdentitySource() string

IdentitySource is a non-secret label for how the credential was chosen. Runtime selection is role-only, so this is always "role".

func (Selection) Token

func (s Selection) Token(getenv func(string) string) (string, error)

Token reads the selected CI/CD variable via getenv. Values are returned to the caller for authentication and must never be logged.

type Source

type Source struct {
	Role       Role
	Kind       RoleKind
	SecretName string
	Reused     bool
	Reason     string
}

Source is the credential Resolve selected. SecretName is a CI/CD variable name, not a token value.

func Resolve

func Resolve(req Request) (Source, error)

Resolve selects the CI/CD variable a job should authenticate with. Built-in and custom registered roles use the same lookup: the job name is resolved through the registry, then the registration's credential reference is selected.

Rules:

  • The registered role secret is always required. There is no shared-token path. Request.Mode is not consulted. Unconfigured is distinct from unregistered and from authentication failure.
  • FailedSecret set: fail closed with ErrAuthFailed. Never switch identities after a runtime authentication failure.

type TokenSnapshot

type TokenSnapshot struct {
	ID        int
	Name      string
	Active    bool
	ExpiresAt string
	Revoked   bool
}

TokenSnapshot is non-secret metadata for one GitLab project access token. Token values must never be stored here.

Jump to

Keyboard shortcuts

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