db

package
v0.18.1 Latest Latest
Warning

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

Go to latest
Published: Oct 25, 2026 License: AGPL-3.0 Imports: 20 Imported by: 0

Documentation

Overview

Package db provides database access and management for the k8Shell Identity service. It provides persistence for users and methods for managing them.

Index

Constants

View Source
const DefaultOrganizationName = "default"

DefaultOrganizationName is the built-in organization every k8Shell deployment is seeded with (see db/migrations/000001_schema.up.sql), and the only organization whose models.Organization.ReadOnly is true — it can never be updated or deleted, since it's the fallback organization the system itself depends on existing.

View Source
const OrganizationAdminUsernamesExpr = `` /* 164-byte string literal not displayed */

OrganizationAdminUsernamesExpr computes an organization's org-admin usernames as a self-contained correlated subquery, independent of any join/GROUP BY in the enclosing query — the same shape as UserBlueprintsExpr above, and for the same reason: array_agg(...) FILTER (...) is an aggregate tied to the enclosing query's own GROUP BY, so it can only be referenced in that query's own SELECT list, never repeated inside a WHERE or HAVING filter condition. A correlated subquery has no such restriction, so it's reused as-is by both ListOrganizations/ ListOrganizationsQuery's SELECT list and organizationsQueryFieldMap's adminUsernames filter. Every query using this must bind orgAdminRoleName as its first ($1) parameter, and every query selecting from identity.organizations must alias the table as "o" for this to resolve.

View Source
const UserBlueprintsExpr = `` /* 268-byte string literal not displayed */

UserBlueprintsExpr computes a user's effective blueprint set as the union of blueprints granted by every role in u.roles: an org-scoped identity.role_blueprints entry for the user's own organization, or any globally-scoped (org IS NULL) entry — the same org-scoped-or-global resolution ListRoles already uses. If any granted role contributes the "*" (all) blueprint, the effective set collapses to just ["*"] rather than listing it alongside the other, now-redundant, blueprints. Every query selecting from identity.users must alias the table as "u" for this to resolve.

Variables

View Source
var ErrAnnouncementNotFound = errors.New("announcement not found")

ErrAnnouncementNotFound is returned when no announcement with the given id exists.

View Source
var ErrAuthKeyExists = errors.New("auth key already exists")

ErrAuthKeyExists is returned by AddUserAuthKeys when one of the given keys is already registered for the user.

View Source
var ErrCredentialExists = errors.New("credential already exists")

ErrCredentialExists is returned by AddKubernetesUserCredential, AddGitUserCredential, and AddRegistryUserCredential when a credential already exists for the same uniqueness key.

View Source
var ErrEmailExists = errors.New("email already exists")

ErrEmailExists is returned by CreateUser when the email is already in use by another user.

View Source
var ErrEnvVarExists = errors.New("environment variable already exists")

ErrEnvVarExists is returned by AddOrganizationEnvVar/AddUserEnvVar when a variable with the same key already exists in that scope.

View Source
var ErrEnvVarNotFound = errors.New("environment variable not found")

ErrEnvVarNotFound is returned when no environment variable with the given key exists in the requested scope (organization, user override, or the effective view for a user).

View Source
var ErrOnboardRuleExists = errors.New("onboard rule already exists")

ErrOnboardRuleExists is returned by CreateOnboardRule when a rule with the same (idp, username_pattern, org) already exists, see onboard_rules_uniq in db/migrations/000001_schema.up.sql.

View Source
var ErrOnboardRuleNotFound = errors.New("onboard rule not found")

ErrOnboardRuleNotFound is returned when no onboard rule with the given id exists, or (for ApproveWaitlistEntry/RejectWaitlistEntry) when the rule exists but is no longer in the waitlist action.

View Source
var ErrOrganizationExists = errors.New("organization already exists")

ErrOrganizationExists is returned by CreateOrganization when an organization with the same name already exists.

View Source
var ErrOrganizationInUse = errors.New("organization is still referenced by at least one user")

ErrOrganizationInUse is returned by DeleteOrganization when at least one user still belongs to the organization. Org-scoped roles no longer block deletion — DeleteOrganization cascades those itself.

View Source
var ErrOrganizationNotFound = errors.New("organization not found")

ErrOrganizationNotFound is returned by DeleteOrganization when no organization with the given name exists.

View Source
var ErrOrganizationReadOnly = errors.New("organization is read-only and cannot be modified")

ErrOrganizationReadOnly is returned by UpdateOrganization and DeleteOrganization when called against DefaultOrganizationName.

View Source
var ErrProtectedCredential = errors.New("credential was created by the onboarding process; only active can be updated")

ErrProtectedCredential is returned by UpdateUserCredential when the targeted credential was provisioned by the onboarding flow (credential_source LIKE 'idp.k8shell.io/%') and the caller tried to change something other than active.

View Source
var ErrRoleExists = errors.New("role already exists")

ErrRoleExists is returned by CreateRole when a role with the same name already exists.

View Source
var ErrRoleInUse = errors.New("role is still assigned to at least one user")

ErrRoleInUse is returned by DeleteRole when at least one user still holds the role.

View Source
var ErrRoleIsGlobal = errors.New("role is global and cannot be modified through this org-scoped call")

ErrRoleIsGlobal is returned by UpdateRole, DeleteRole, AddRoleBlueprints, and RemoveRoleBlueprints when name matches a registered role, but only as a global role (org IS NULL) — not one scoped to the org the caller passed. Global roles are managed independently of any org and are not mutable through these org-scoped calls; without this distinction such calls would be indistinguishable from the name not being registered at all.

View Source
var ErrRoleNotFound = errors.New("role not found")

ErrRoleNotFound is returned by DeleteRole when no role with the given name exists.

View Source
var ErrUIDExists = errors.New("uid already exists")

ErrUIDExists is returned by CreateUser when the uid is already in use by another user.

View Source
var ErrUIDRangeExhausted = errors.New("no available uid in local user range")

ErrUIDRangeExhausted is returned by NextAvailableUID when every UID in [localUserUIDFloor, localUserUIDCeiling] is already taken.

View Source
var ErrUsernameExists = errors.New("username already exists")

ErrUsernameExists is returned by CreateUser when the username is already taken.

Functions

This section is empty.

Types

type AnnouncementEmailCandidate added in v0.17.0

type AnnouncementEmailCandidate struct {
	Username string
	Email    string
}

AnnouncementEmailCandidate is a user eligible, by targeting alone, to be emailed a given announcement — see ListAnnouncementEmailCandidates. It deliberately carries only what the mailer needs to send and doesn't duplicate the full User model.

type DB

type DB struct {
	db.DB
	// contains filtered or unexported fields
}

DB wraps the shared database implementation for the identity service.

func NewDB

func NewDB(config db.DBConfig) (*DB, error)

NewDB creates a new DB for the identity service.

func (*DB) AddGitUserCredential added in v0.16.0

func (d *DB) AddGitUserCredential(username, scope, subject, secret string) (*models.UserCredential, error)

AddGitUserCredential stores a Git credential for a user. scope maps to service_scope and subject maps to subject; credential_source is always "stored" and secret is persisted as given. A user may have at most one credential per (service_name, scope), regardless of subject.

func (*DB) AddKubernetesUserCredential added in v0.16.0

func (d *DB) AddKubernetesUserCredential(username, namespace, serviceAccount string) (*models.UserCredential, error)

AddKubernetesUserCredential provisions a Kubernetes service-account credential for a user. namespace maps to service_scope and serviceAccount maps to subject; the secret is left NULL since kubernetes credentials are resolved on demand via the TokenRequest API.

func (*DB) AddOrganizationEnvVar added in v0.16.0

func (d *DB) AddOrganizationEnvVar(org, key, value string, isSecret bool) (*models.EnvVar, error)

AddOrganizationEnvVar creates a new environment variable on org. Returns ErrEnvVarExists if key is already defined for org, or models.ErrInvalidParameters if key is not a valid POSIX name or org does not exist.

func (*DB) AddRegistryUserCredential added in v0.16.0

func (d *DB) AddRegistryUserCredential(username, scope, subject, secret string) (*models.UserCredential, error)

AddRegistryUserCredential stores a container registry credential for a user. scope maps to service_scope and subject maps to subject; credential_source is always "stored" and secret is persisted as given. A user may have at most one credential per (service_name, scope), regardless of subject.

func (*DB) AddRoleBlueprints added in v0.16.0

func (d *DB) AddRoleBlueprints(name, org string, blueprints []string) (*models.RoleInfo, error)

AddRoleBlueprints grants a role one or more blueprints, skipping duplicates. org must match exactly (empty means the global role). Returns ErrRoleNotFound when no role by that name is registered at all, or ErrRoleIsGlobal when it is registered but only as a global role.

func (*DB) AddUserAuthKeys added in v0.16.0

func (d *DB) AddUserAuthKeys(username string, authKeys []string) (*models.User, error)

AddUserAuthKeys appends the given SSH public keys to the user, preserving the existing order, then returns the updated user. It returns ErrAuthKeyExists without making any change if any of the given keys is already registered for the user (including duplicates within authKeys itself).

func (*DB) AddUserEnvVar added in v0.16.0

func (d *DB) AddUserEnvVar(username, key, value string, isSecret bool) (*models.EnvVar, error)

AddUserEnvVar creates a new environment variable owned by username, overriding any organization value with the same key. Returns ErrEnvVarExists if username already has an override for key, or models.ErrInvalidParameters if key is not a valid POSIX name or username does not exist.

func (*DB) AddUserRoles added in v0.16.0

func (d *DB) AddUserRoles(username string, roles []string) (*models.User, error)

AddUserRoles appends the given roles to the user, skipping duplicates.

func (*DB) ApproveWaitlistEntry added in v0.16.0

func (d *DB) ApproveWaitlistEntry(id int32, decidedBy string) (*models.OnboardRule, error)

ApproveWaitlistEntry flips a pending onboard rule's action to 'allow' and status to 'approved', and records who decided it. Status moves to 'onboarded' separately, by MarkOnboarded, once the user actually logs in — approval alone does not onboard them. Returns ErrOnboardRuleNotFound when no rule with that id is currently in the waitlist action (already decided, or never requested).

func (*DB) ClaimAnnouncementEmailSend added in v0.17.0

func (d *DB) ClaimAnnouncementEmailSend(announcementID int32, username string) (claimed bool, err error)

ClaimAnnouncementEmailSend atomically claims the right to send announcementID's email to username by inserting into identity.announcement_email_sends. Returns claimed=false when a row already exists — this or another replica/tick already sent it (or is mid-send) — which the caller must treat as "do not send". The insert's PRIMARY KEY is what makes this safe under concurrent ticks/replicas without any additional locking. Callers that fail to actually send after claiming must call UnclaimAnnouncementEmailSend so a later tick retries.

func (*DB) CountMailSendsSince added in v0.17.0

func (d *DB) CountMailSendsSince(since time.Time) (int, error)

CountMailSendsSince returns the number of identity.mail_sends rows with sent_at after since, across every mail kind — the rolling-window count MailRateLimitConfig.DailyRecipientCap is checked against.

func (*DB) CreateAccessToken

func (d *DB) CreateAccessToken(username, name string, scopes []string, expiresAt *time.Time, active bool) (int64, string, error)

CreateAccessToken generates a new PAT for username, stores its hash, and returns the raw token (shown to the caller once) along with the new record's ID.

func (*DB) CreateAnnouncement added in v0.16.0

func (d *DB) CreateAnnouncement(a *models.Announcement) (*models.Announcement, error)

CreateAnnouncement creates a new announcement with its translations (at least one is required). It is global when a.Orgs is empty, otherwise scoped to the listed organizations — each of which must already exist (see validateAnnouncementOrgs) — and further scoped to a.Roles when non-empty (each of which must be valid for a.Orgs, see validateAnnouncementRoles). Returns models.ErrInvalidParameters if a.Name is empty, a.Translations is empty or has an incomplete entry, any named org/role doesn't exist, or a.StartsAt is after a.EndsAt.

func (*DB) CreateOnboardRule added in v0.16.0

func (d *DB) CreateOnboardRule(rule *models.OnboardRule) (*models.OnboardRule, error)

CreateOnboardRule registers a new onboard rule. Callers are responsible for validating rule.Roles against rule.Org first (see MissingRolesForOrg) — the DB layer only enforces the org FK and the action CHECK constraint.

func (*DB) CreateOrganization added in v0.16.0

func (d *DB) CreateOrganization(name, description string) (*models.Organization, error)

CreateOrganization registers a new organization.

func (*DB) CreateRole added in v0.16.0

func (d *DB) CreateRole(name, description, org string) (*models.RoleInfo, error)

CreateRole registers a new assignable role. org may be empty, meaning the role is global (assignable regardless of a user's organization). The same name may be registered independently by different organizations — only (name, org) together must be unique, enforced by idx_roles_org_name and, for global roles, idx_roles_global_name_uniq.

func (*DB) CreateUser

func (d *DB) CreateUser(user *models.User) error

CreateUser inserts a new user record into the database. The insert fails if the user's organization does not already exist.

func (*DB) DeleteAccessToken added in v0.16.0

func (d *DB) DeleteAccessToken(id int64) error

DeleteAccessToken permanently removes an access token by ID, regardless of owner or active state. Returns models.ErrUserNotFound if no such token exists.

func (*DB) DeleteAnnouncement added in v0.16.0

func (d *DB) DeleteAnnouncement(id int32) error

DeleteAnnouncement permanently removes an announcement, cascading its translations and read tracking. Returns ErrAnnouncementNotFound when no announcement with that id exists.

func (*DB) DeleteExpiredAccessTokens added in v0.16.0

func (d *DB) DeleteExpiredAccessTokens(cutoff time.Time) (int64, error)

DeleteExpiredAccessTokens permanently removes access tokens whose expiry is before cutoff. Tokens that never expire (expires_at IS NULL) are untouched. The delete is guarded by a transaction-scoped Postgres advisory lock, so if another instance is already running the same cleanup, this call is a no-op and returns (0, nil) instead of racing it.

func (*DB) DeleteOnboardRule added in v0.16.0

func (d *DB) DeleteOnboardRule(id int32) error

DeleteOnboardRule removes an onboard rule by id. Returns ErrOnboardRuleNotFound when no rule with that id exists.

func (*DB) DeleteOrganization added in v0.16.0

func (d *DB) DeleteOrganization(name string) error

DeleteOrganization removes an organization from the registry, cascading its org-scoped roles and their role_blueprints — mirroring DeleteRole's own role_blueprints cleanup, just applied in bulk to every role scoped to this org instead of one at a time, since a role (and its granted blueprints) has no meaning once the org it's scoped to is gone. Its onboard_rules are cascaded for the same reason: org there is a NOT NULL destination, not an optional scope, so a rule naming this org has nothing left to place users into once it's gone.

Any user still belonging to the org is deliberately not cascaded: identity.users.organization carries a NOT NULL foreign key to identity.organizations(name) with no ON DELETE CASCADE, so Postgres itself refuses the delete while any user remains — that FK violation is translated to ErrOrganizationInUse. Deleting user accounts (and their credentials, access tokens, POSIX identity) is a much more destructive decision than pruning role definitions, and this method does not make it on the caller's behalf; the caller must reassign or delete those users first.

Returns ErrOrganizationReadOnly for DefaultOrganizationName without touching the database — it can never be deleted.

func (*DB) DeleteOrganizationEnvVar added in v0.16.0

func (d *DB) DeleteOrganizationEnvVar(org, key string) error

DeleteOrganizationEnvVar removes an environment variable from org. Returns ErrEnvVarNotFound when no such key exists.

func (*DB) DeleteRole added in v0.16.0

func (d *DB) DeleteRole(name, org string) error

DeleteRole removes a role from the registry, refusing to do so while any user still holds it — a silent privilege change (cascading the role off every user that has it) is worse than a failed call. org must match exactly (empty means the global role, not "any org"); the in-use check itself is by name only, since identity.users.roles stores plain names without an org qualifier. Returns ErrRoleNotFound when no role by that name is registered at all, or ErrRoleIsGlobal when it is registered but only as a global role.

func (*DB) DeleteUser

func (d *DB) DeleteUser(username string) error

DeleteUser permanently removes a user record from the database by username. Credentials and access tokens owned by the user are removed along with it (ON DELETE CASCADE).

func (*DB) DeleteUserCredential

func (d *DB) DeleteUserCredential(id uint32) error

DeleteUserCredential removes a user credential by its ID.

func (*DB) DeleteUserEnvVar added in v0.16.0

func (d *DB) DeleteUserEnvVar(username, key string) error

DeleteUserEnvVar removes username's override for key, restoring org's value (if any) as the effective value. Returns ErrEnvVarNotFound when username has no override for key.

func (*DB) FindUser

func (d *DB) FindUser(username string, source string) (*models.User, error)

FindUser retrieves a user by username. If source is empty, the search is not filtered by source.

func (*DB) FindUserByEmail added in v0.16.0

func (d *DB) FindUserByEmail(email string) (*models.User, error)

FindUserByEmail retrieves a user by exact email match. Returns models.ErrUserNotFound when no user has that email, or when email is empty.

func (*DB) FindUserByUsernameAndSource

func (d *DB) FindUserByUsernameAndSource(ctx context.Context, username string, source string) (*models.User, error)

FindUserByUsernameAndSource retrieves a user by username and source.

func (*DB) GetAccessTokenByName added in v0.16.0

func (d *DB) GetAccessTokenByName(username, name string) (*models.AccessToken, error)

GetAccessTokenByName looks up the token owned by username with the given name, active or not — (username, name) is unique, so at most one row can match. Returns models.ErrUserNotFound if no such token exists.

func (*DB) GetAnnouncement added in v0.16.0

func (d *DB) GetAnnouncement(id int32) (*models.Announcement, error)

GetAnnouncement retrieves a single announcement by id, with ReadCount populated (the number of distinct users who have read it). Returns ErrAnnouncementNotFound when no announcement with that id exists.

func (*DB) GetEffectiveUserEnvVar added in v0.16.0

func (d *DB) GetEffectiveUserEnvVar(username, org, key string) (*models.EnvVar, error)

GetEffectiveUserEnvVar retrieves the effective value of key for a user in org: the user's own override when present (Origin "user"), otherwise org's value (Origin "org"). Returns ErrEnvVarNotFound when neither exists.

func (*DB) GetOnboardRule added in v0.16.0

func (d *DB) GetOnboardRule(id int32) (*models.OnboardRule, error)

GetOnboardRule retrieves a single onboard rule by id. Returns ErrOnboardRuleNotFound when no rule with that id exists. Used by UpdateOnboardRule's caller to look up the rule's (immutable) org before validating role assignability against it.

func (*DB) GetOrganization added in v0.16.0

func (d *DB) GetOrganization(name string) (*models.Organization, error)

GetOrganization retrieves a single organization by name, with the same computed AdminUsernames/UserCount fields as ListOrganizations. Returns ErrOrganizationNotFound when no organization with that name exists.

func (*DB) GetOrganizationEnvVar added in v0.16.0

func (d *DB) GetOrganizationEnvVar(org, key string) (*models.EnvVar, error)

GetOrganizationEnvVar retrieves a single environment variable defined directly on org. Returns ErrEnvVarNotFound when no such key exists.

func (*DB) GetUserCredential

func (d *DB) GetUserCredential(username, serviceName, serviceScope string) (*models.UserCredential, error)

GetUserCredential retrieves a single credential for the given user, service_name and service_scope. Returns models.ErrUserNotFound when no matching active credential exists.

func (*DB) GetUserSettings added in v0.16.2

func (d *DB) GetUserSettings(username string) (*models.UserSettings, error)

GetUserSettings returns username's settings row. A missing row is not an error — it returns the zero-value *models.UserSettings (Version 0, empty Data, zero UpdatedAt), matching GetUserSettingsResponse's own no-NotFound contract.

func (*DB) GlobalRoles added in v0.16.0

func (d *DB) GlobalRoles(names []string) ([]string, error)

GlobalRoles reports which of the given role names are registered as global (org IS NULL) roles in identity.roles, preserving names as given (deduplicated). Used by UpdateUser to decide which of a user's roles survive an organization change: an org-scoped role has no meaning outside the org it belonged to, but a global role (e.g. the seeded "admin" role) is assignable regardless of org, so it should be carried over rather than stripped along with the rest.

func (*DB) InvalidateUser

func (d *DB) InvalidateUser(username string) error

InvalidateUser marks a user account as invalid (is_valid=false) without deleting it.

func (*DB) ListAccessTokens

func (d *DB) ListAccessTokens(username string) ([]*models.AccessToken, error)

ListAccessTokens returns all access token metadata for a user (no hashes).

func (*DB) ListAnnouncementEmailCandidates added in v0.17.0

func (d *DB) ListAnnouncementEmailCandidates(announcementID int32, orgs, roles []string) ([]*AnnouncementEmailCandidate, error)

ListAnnouncementEmailCandidates returns users matching an announcement's org/role targeting (same empty-means-everyone semantics as ListUnreadAnnouncements) who have an on-file email, are not disabled (is_valid), and have not already been sent this announcement's email (see identity.announcement_email_sends). It does not check the recipient's own announcementsByEmail opt-in or resolve a translation for their language — both live in the opaque user_settings blob and are checked by the caller per candidate (see Server.sendAnnouncementEmailToCandidate) rather than parsed in SQL.

func (*DB) ListAnnouncements added in v0.16.0

func (d *DB) ListAnnouncements(org string, limit, offset int) ([]*models.Announcement, error)

ListAnnouncements returns announcements for administration, newest first: every announcement when org is empty, otherwise only those that apply to org (global ones plus any scoped to it). Each entry's ReadCount is populated. Unlike ListUnreadAnnouncements/ListUserAnnouncements this is not scoped to a requesting user's roles, not filtered by active or validity period — an admin managing announcements needs to see (and toggle) inactive/out-of-period ones too.

func (*DB) ListEffectiveUserEnvVars added in v0.16.0

func (d *DB) ListEffectiveUserEnvVars(username, org string) ([]*models.EnvVar, error)

ListEffectiveUserEnvVars returns the effective environment variables for a user in org: every organization_env_vars entry for org (Origin "org"), with any user_env_vars entry for username overriding it by key (Origin "user"). Merged here rather than via a DB view/join, per the comment on identity.user_env_vars in db/migrations/000002_env_vars.up.sql.

func (*DB) ListEmailEligibleAnnouncements added in v0.17.0

func (d *DB) ListEmailEligibleAnnouncements() ([]*models.Announcement, error)

ListEmailEligibleAnnouncements returns announcements currently eligible to be emailed: active, email_enabled, and within their validity period (starts_at/ends_at, same bounds as ListUnreadAnnouncements). Ordered by activation order (starts_at, falling back to created_at when starts_at is unset) so that, when a daily recipient cap holds back some candidates, the oldest-activated announcements are processed first, tick after tick. Callers are still responsible for their own day/send-hour gating (see Server.sendEligibleAnnouncementEmails) — this only filters on what's stored, not on today's date.

func (*DB) ListGlobalRoles added in v0.16.0

func (d *DB) ListGlobalRoles() ([]*models.RoleInfo, error)

ListGlobalRoles returns the roles assignable across every organization (org IS NULL), ordered by name, with UserCount reflecting every user holding the role worldwide (there is no single requesting org to scope it to — see rolesBaseQuery).

func (*DB) ListOrganizationEnvVars added in v0.16.0

func (d *DB) ListOrganizationEnvVars(org string) ([]*models.EnvVar, error)

ListOrganizationEnvVars returns every environment variable defined directly on org, ordered by key.

func (*DB) ListOrganizations added in v0.16.0

func (d *DB) ListOrganizations() ([]*models.Organization, error)

ListOrganizations returns every registered organization, ordered by name. AdminUsernames and UserCount are computed rather than stored: AdminUsernames lists the org's users holding orgAdminRoleName (there may be zero, one, or many; see OrganizationAdminUsernamesExpr), and UserCount is the total number of users in the org, computed via a join/aggregate in a single query rather than N+1 per-org lookups.

func (*DB) ListOrganizationsQuery added in v0.16.0

func (d *DB) ListOrganizationsQuery(desc *queryv1.Descriptor, fm pkgquery.FieldMap, payload *queryv1.Payload,
	obligationOrg string) ([]*models.Organization, error)

ListOrganizationsQuery returns organizations matching a generic query.v1.Payload, built against desc/fm via common/pkg/query. Callers must have already run query.Validate(desc, payload) — ListOrganizationsQuery trusts the payload has been checked and only translates it to SQL.

query.BuildQuery can't be used directly here: it appends WHERE immediately after the supplied "SELECT ... FROM ..." header, but organizationsQueryDescriptor includes userCount, a COUNT(u.username) aggregate — Postgres only allows aggregates to be filtered in a HAVING clause, evaluated after GROUP BY, never in WHERE. So every condition (not just userCount's) is applied as a single HAVING instead: query.BuildWhere/query.BuildOrderBy build the fragments, which are then spliced in after an explicit GROUP BY rather than before it. This is valid for the other fields too: name/description/ createdAt are each also a GROUP BY key, so referencing one bare in HAVING is functionally dependent and unambiguous per group; adminUsernames resolves to OrganizationAdminUsernamesExpr, a correlated subquery that only reads o.name (itself a GROUP BY key) and has no aggregation tied to this query's own GROUP BY, so it's likewise safe to reference from HAVING — unlike ListUsersQuery, which has no aggregation at all and uses query.BuildQuery as-is with a normal WHERE.

obligationOrg is parsed by the caller from the payload's authz obligations (see common/pkg/authz.ParseOrgObligation) and is enforced as a mandatory AND onto the Filters-derived HAVING, regardless of the client's own Filters.op — an obligation must never be diluted by a client-chosen OR.

func (*DB) ListRoles added in v0.16.0

func (d *DB) ListRoles(org string) ([]*models.RoleInfo, error)

ListRoles returns the roles assignable within org, ordered by name: those scoped to org plus all global roles (org IS NULL) — an org-scoped caller must still see the global roles it may assign. UserCount is scoped to org's users (see rolesOrgScopedQuery), so a global role's count reflects only how many of org's users hold it. org must be non-empty; use ListGlobalRoles to list global roles (and their worldwide UserCount) on their own.

func (*DB) ListUnreadAnnouncements added in v0.16.0

func (d *DB) ListUnreadAnnouncements(username, org string, roles []string) ([]*models.Announcement, error)

ListUnreadAnnouncements returns announcements that are active, apply to org (global or scoped to it) and to at least one of roles (or apply to every role, when the announcement's own roles is empty), currently fall within their validity period, and that username has not yet read (see identity.announcement_reads). An inactive announcement, or one outside its validity period, is excluded here even when unread — use ListUserAnnouncements to retrieve it regardless.

func (*DB) ListUserAnnouncements added in v0.16.0

func (d *DB) ListUserAnnouncements(username, org string, roles []string) ([]*models.Announcement, error)

ListUserAnnouncements returns every active announcement that applies to org (global or scoped to it) and to at least one of roles (or every role), regardless of validity period or read status, with IsRead/ReadAt populated per announcement from identity.announcement_reads — unlike ListUnreadAnnouncements, this includes announcements already read or outside their validity period, but still excludes inactive ones (see ListAnnouncements for those).

func (*DB) ListUserAuthKeys added in v0.16.0

func (d *DB) ListUserAuthKeys(username string) ([]string, error)

ListUserAuthKeys returns the SSH public keys stored for a user, in the stable order relied on by index-based removal (RemoveUserAuthKey).

func (*DB) ListUserCredentials

func (d *DB) ListUserCredentials(username string, id uint32) ([]*models.UserCredential, error)

ListUserCredentials retrieves all credentials for the given username. If id is non-zero, the result is filtered to the credential with that ID.

func (*DB) ListUsers

func (d *DB) ListUsers(limit, offset int, roles, blueprints []string, org string) ([]*models.User, error)

ListUsers returns a paginated list of users ordered by username, optionally restricted to users matching the given filters. roles and blueprints match when the user has at least one of the listed values; org matches when the user belongs to that organization. An empty/nil filter imposes no restriction on that dimension.

func (*DB) ListUsersQuery added in v0.16.0

func (d *DB) ListUsersQuery(desc *queryv1.Descriptor, fm pkgquery.FieldMap, payload *queryv1.Payload,
	obligationRoles, obligationBlueprints []string, obligationOrg string) ([]*models.User, error)

ListUsersQuery returns a paginated list of users matching a generic query.v1.Payload, built against desc/fm via common/pkg/query. Callers must have already run query.Validate(desc, payload) — ListUsersQuery trusts the payload has been checked and only translates it to SQL.

obligationRoles/obligationBlueprints/obligationOrg are parsed by the caller from the payload's authz obligations (see common/pkg/authz Parse{Roles,Blueprints,Org}Obligation) and are enforced as a mandatory AND onto the Filters-derived WHERE, regardless of the client's own Filters.op — an obligation must never be diluted by a client-chosen OR.

func (*DB) MarkAnnouncementRead added in v0.16.0

func (d *DB) MarkAnnouncementRead(id int32, username string) error

MarkAnnouncementRead records that username has read announcement id. Idempotent — marking an already-read announcement again leaves its original read_at unchanged. Returns ErrAnnouncementNotFound when no announcement with that id exists, or models.ErrInvalidParameters when username does not exist.

func (*DB) MarkOnboarded added in v0.16.0

func (d *DB) MarkOnboarded(idp, username, org string, roles []string, sudo bool, fullname, email string) error

MarkOnboarded records a successful onboarding as a concrete (exact-username) row with action='allow', status='onboarded'. Called only after the user has actually been created in identity.users — status is the outcome of a confirmed onboarding, not an optimistic projection. If a waitlist row already exists for this (idp, username) (the common approval path), it's updated in place; otherwise a new row is inserted, e.g. for a user who onboarded directly via a pattern rule with no prior waitlist entry.

func (*DB) MarkRejectedByRule added in v0.16.0

func (d *DB) MarkRejectedByRule(idp, username, org string, roles []string, sudo bool, fullname, email string) error

MarkRejectedByRule records a rule-driven (non-admin) rejection as a concrete (exact-username) row with action='reject', status='rejected' — distinct from RejectWaitlistEntry, which is an admin rejecting a previously-waitlisted request. Called when ResolveOnboardDecision resolves to OnboardActionReject via an actual matched rule (org is always non-empty in that case; the fail-closed "nothing matched at all" case has no org to record against and is not persisted here). Idempotent via upsert: a repeat attempt against an already-rejected row just refreshes updated_at.

func (*DB) MissingRoles added in v0.16.0

func (d *DB) MissingRoles(names []string) ([]string, error)

MissingRoles reports which of the given role names are not registered in identity.roles, preserving names as given (deduplicated). Used to validate role assignment in bulk so a single error can name every offending role at once rather than failing one at a time.

func (*DB) MissingRolesForOrg added in v0.16.0

func (d *DB) MissingRolesForOrg(names []string, org string) ([]string, error)

MissingRolesForOrg reports which of the given role names are not assignable within org, preserving names as given (deduplicated). Unlike MissingRoles (which accepts any registered role regardless of org), this only accepts roles scoped to org plus global roles — the same org-scoped-or-global resolution ListRoles(org) uses. Used to validate OnboardRule.Roles: a rule places users into a specific org, so its roles must actually be assignable there.

func (*DB) MoveOnboardRuleOrg added in v0.16.0

func (d *DB) MoveOnboardRuleOrg(idp, username, oldOrg, newOrg string) error

MoveOnboardRuleOrg updates a concrete (exact-username) onboard rule's org to follow the user it tracks after an admin moves that user to a different organization — otherwise the tracking row would keep pointing at an org the user no longer belongs to, and a later onboarding attempt resolving through this row (e.g. after the account is deleted and would re-onboard) would place them back into the org they were moved out of. roles is cleared at the same time: identity.onboard_rules.roles is only validated against the rule's own org at the application layer (see MissingRolesForOrg), so nothing on the old role list can be assumed valid once the rule belongs to a different org — mirrors the same drop UpdateUser applies to the user's own role list on an org change. It's a no-op (not an error) if there is no matching row at all — a user onboarded without going through the onboard_rules flow (e.g. created directly via CreateUser) has no tracking row to move.

func (*DB) NextAvailableUID added in v0.16.0

func (d *DB) NextAvailableUID() (uint32, error)

NextAvailableUID returns the next unused UID in [localUserUIDFloor, localUserUIDCeiling], for assigning to users created via CreateUser that don't specify one. Because it only considers UIDs already taken within that bounded range, it stays collision-free and compact regardless of what UIDs providers have used elsewhere.

func (*DB) PutUserSettings added in v0.16.2

func (d *DB) PutUserSettings(username string, data []byte) (*models.UserSettings, error)

PutUserSettings replaces username's settings row (UPSERT, last-write-wins) and returns the new version and updated_at. version is not compared against any existing value — there is no optimistic-concurrency check. Returns models.ErrInvalidParameters if username does not exist.

func (*DB) QueryAnnouncements added in v0.16.0

func (d *DB) QueryAnnouncements(desc *queryv1.Descriptor, fm pkgquery.FieldMap,
	payload *queryv1.Payload) ([]*models.Announcement, error)

QueryAnnouncements returns announcements matching a generic query.v1.Payload, built against desc/fm via common/pkg/query. Callers must have already run query.Validate(desc, payload) — QueryAnnouncements trusts the payload has been checked and only translates it to SQL. Like ListAnnouncements this is the administration-facing view: not scoped to a requesting user's roles, not filtered by active or validity period.

func (*DB) QueryOnboardRules added in v0.16.0

func (d *DB) QueryOnboardRules(desc *queryv1.Descriptor, fm pkgquery.FieldMap,
	payload *queryv1.Payload) ([]*models.OnboardRule, error)

QueryOnboardRules returns onboard rules matching a generic query.v1.Payload, built against desc/fm via common/pkg/query. Callers must have already run query.Validate(desc, payload). A frontend renders the pending approval queue by filtering action = 'waitlist', and manages standing rules with any other filter — there's no separate "list waitlist" query.

func (*DB) RecordMailSend added in v0.17.0

func (d *DB) RecordMailSend(kind, recipient string) error

RecordMailSend appends a row to identity.mail_sends, the rolling-24h recipient-rate ledger shared by every outbound mail path (password-reset and announcement). Callers must only call this after a send has actually succeeded — a failed attempt never consumed the relay's quota and must not be counted (see CountMailSendsSince).

func (*DB) RejectWaitlistEntry added in v0.16.0

func (d *DB) RejectWaitlistEntry(id int32, decidedBy, note string) (*models.OnboardRule, error)

RejectWaitlistEntry flips a pending onboard rule's action to 'reject' so the same user can't immediately re-trigger a fresh waitlist entry by retrying onboarding. An empty note leaves the row's existing note unchanged. Returns ErrOnboardRuleNotFound when no rule with that id is currently in the waitlist action.

func (*DB) RemoveRoleBlueprints added in v0.16.0

func (d *DB) RemoveRoleBlueprints(name, org string, blueprints []string) (*models.RoleInfo, error)

RemoveRoleBlueprints revokes one or more blueprints from a role. org must match exactly (empty means the global role). Returns ErrRoleNotFound when no role by that name is registered at all, or ErrRoleIsGlobal when it is registered but only as a global role (both via the getRole lookup below).

func (*DB) RemoveUserAuthKey added in v0.16.0

func (d *DB) RemoveUserAuthKey(username string, index uint32) (*models.User, error)

RemoveUserAuthKey removes the SSH public key at the given index, as returned by ListUserAuthKeys, and returns the updated user. It returns models.ErrInvalidParameters if the index is out of range.

func (*DB) RemoveUserCredential added in v0.16.0

func (d *DB) RemoveUserCredential(username string, id uint32) error

RemoveUserCredential removes a single credential owned by username, identified by id. Returns models.ErrUserNotFound when no matching credential exists for that user.

func (*DB) RemoveUserRoles added in v0.16.0

func (d *DB) RemoveUserRoles(username string, roles []string) (*models.User, error)

RemoveUserRoles removes the given roles from the user.

func (*DB) RenewAccessToken added in v0.16.0

func (d *DB) RenewAccessToken(id int64, scopes []string, expiresAt *time.Time) (string, error)

RenewAccessToken rotates the raw token of an existing access token record in place, applying the given scopes and expiry, and returns the new raw token (shown once). The token is reactivated (is_active = TRUE) regardless of its prior state, since renewing a revoked token is how its name is brought back into use.

func (*DB) ResolveAccessToken

func (d *DB) ResolveAccessToken(raw string) (*models.AccessToken, error)

ResolveAccessToken looks up a token by its raw value, verifies it is active and not expired, updates last_used_at, and returns the token record.

func (*DB) ResolveOnboardDecision added in v0.16.0

func (d *DB) ResolveOnboardDecision(idp, username, hintOrg string) (*OnboardDecision, error)

ResolveOnboardDecision resolves whether username may onboard via idp, and what it should get if so, by matching identity.onboard_rules. hintOrg is the identity provider's own onboarding hint (models.OnboardUserRule.Organization); when non-empty, matching is scoped to that org, same as before. When empty (the provider reported no org of its own), every org is searched and the winning row's own org decides placement — see the onboard_rules.org comment in db/migrations/000001_schema.up.sql: the rule is the source of truth for destination org, not a value the provider must already agree with (see Server.refreshUser). username_pattern is one of: '*' (matches any username), a comma-delimited list of usernames (matches username against each entry exactly, e.g. 'alice,bob,carol'), or a single exact username. Ranking is by specificity, in this order: a literal single-username match always outranks a comma-delimited list match, which always outranks a '*' wildcard match, regardless of priority; within any one tier the row with the lowest priority wins (ties broken by the lower row id, for determinism) — this also decides between two orgs' rules when hintOrg is empty and both match, so an admin relying on the empty-hint fallback should give their intended default a lower priority than any other org's rule for the same idp. The literal-beats-list-beats-wildcard ordering matters beyond the initial decision: once a comma-list or wildcard rule first resolves a user to waitlist/allow/reject, Server.refreshUser records that outcome as a concrete single-username row (see UpsertWaitlistEntry/MarkOnboarded/MarkRejectedByRule) — a literal match on username. Every later login by that same user must keep matching that concrete row, not the broader rule that produced it, or an admin's approval (or edits to a still-pending request) would be silently overwritten the next time the user logs in and the original list/wildcard rule wins the tie-break again. When nothing matches at all — not even a catch-all (username_pattern='*') row for the idp (within hintOrg, or across every org when hintOrg is empty) — this fails closed and returns OnboardActionReject: a real deployment is expected to always define at least a catch-all rule per idp it uses, so reaching this path signals a missing rule, not an intentional "allow everyone" default.

func (*DB) RevokeAccessToken

func (d *DB) RevokeAccessToken(id int64, username string) error

RevokeAccessToken soft-deletes a token by ID, enforcing that it belongs to username. Returns models.ErrUserNotFound when no matching active token is found.

func (*DB) RevokeOnboardRule added in v0.16.0

func (d *DB) RevokeOnboardRule(idp, username, org string) error

RevokeOnboardRule reverts a concrete (exact-username) row after the user it tracked has been deleted from identity.users: action is set back to 'reject' and status to 'none', so deleting an account doesn't leave a standing 'allow' rule quietly letting the same identity back in on their next login — re-admitting them again requires an explicit decision (e.g. UpdateOnboardRule, or a fresh admin-authored rule). It's a no-op (not an error) if there is no matching row at all — deleting a user has no obligation to have one (e.g. one created directly via CreateUser, bypassing onboarding entirely).

func (*DB) SeedOnboardRule added in v0.16.0

func (d *DB) SeedOnboardRule(rule *models.OnboardRule) (bool, error)

SeedOnboardRule inserts a default onboard rule (e.g. from config.yaml's onboardRules, see Server.seedOnboardRules) unless a row for the same (idp, username_pattern, org) already exists — from a prior seed, an admin-authored rule, or a system-inserted waitlist/rejection row. ON CONFLICT DO NOTHING makes this safe to call concurrently from multiple service instances at startup

func (*DB) SetUserAuthKeys added in v0.16.0

func (d *DB) SetUserAuthKeys(username string, authKeys []string) error

SetUserAuthKeys replaces all SSH public keys stored for a user.

func (*DB) SetUserPassword added in v0.16.0

func (d *DB) SetUserPassword(username, hash string) (*models.User, error)

SetUserPassword sets a user's stored password hash. Pass an empty hash to clear it (NULL), which disables password auth for the user.

func (*DB) TouchUserCredentialLastUsed added in v0.16.0

func (d *DB) TouchUserCredentialLastUsed(id uint32) error

TouchUserCredentialLastUsed sets last_used_at to the current time for the credential identified by id. Called after a credential's secret has actually been resolved for use (see Server.ResolveCredential) — not from existence checks such as provisionGitCredential.

func (*DB) UnclaimAnnouncementEmailSend added in v0.17.0

func (d *DB) UnclaimAnnouncementEmailSend(announcementID int32, username string) error

UnclaimAnnouncementEmailSend removes a claim taken by ClaimAnnouncementEmailSend after the send itself failed, so a later tick retries this (announcement, user) pair instead of silently skipping it forever. Best-effort: called from an already-failed-send path, so a failure here is logged by the caller rather than propagated further.

func (*DB) UpdateAccessToken added in v0.16.0

func (d *DB) UpdateAccessToken(id int64, username string, active *bool, scopes *[]string) (*models.AccessToken, error)

UpdateAccessToken partially updates an access token's active state and/or scopes, enforcing that it belongs to username. Only non-nil fields are applied. Returns models.ErrUserNotFound if no matching token owned by username exists.

func (*DB) UpdateAnnouncement added in v0.16.0

func (d *DB) UpdateAnnouncement(id int32, name *string, translations []models.AnnouncementTranslation,
	orgs []string, clearOrgs bool, roles []string, clearRoles bool, active *bool,
	startsAt *time.Time, clearStartsAt bool, endsAt *time.Time, clearEndsAt bool,
	emailEnabled *bool) (*models.Announcement, error)

UpdateAnnouncement partially updates an announcement identified by id — a nil name/active leaves that field unchanged. translations, when non-empty, replaces the announcement's entire translation set (validated the same as on create) — pass nil/empty to leave the existing translations unchanged; the set can never be replaced with an empty one, since every announcement must keep at least one language. Because a nil orgs/roles/startsAt/endsAt is ambiguous between "leave unchanged" and "clear", clearOrgs/clearRoles/clearStartsAt/clearEndsAt make the intent explicit: clearOrgs makes the announcement global (orgs must be empty when set), clearRoles makes it apply to every role (roles must be empty when set), clearStartsAt/clearEndsAt remove that bound (open-ended) — set at most one of a value and its own clear flag. When roles changes but orgs does not, roles is validated against the announcement's current orgs. emailEnabled, when non-nil, marks the announcement eligible (or ineligible) to be sent by email. Returns ErrAnnouncementNotFound when no announcement with that id exists, or models.ErrInvalidParameters if translations/orgs/roles are invalid or the resulting period is invalid.

func (*DB) UpdateOnboardRule added in v0.16.0

func (d *DB) UpdateOnboardRule(id int32, usernamePattern string, action models.OnboardAction, priority int32,
	roles []string, sudo bool, note, fullname, email string) (*models.OnboardRule, error)

UpdateOnboardRule fully replaces the mutable fields of an onboard rule, including username_pattern. idp/org are immutable — delete and recreate the rule to change them. Returns ErrOnboardRuleNotFound when no rule with that id exists, or ErrOnboardRuleExists when the new username_pattern collides with another row already sharing this rule's (idp, org) — see onboard_rules_uniq.

func (*DB) UpdateOrganization added in v0.16.0

func (d *DB) UpdateOrganization(name string, description *string) (*models.Organization, error)

UpdateOrganization updates an organization's description. The name is immutable and used only to identify the organization; pass a nil description to leave it unchanged. Returns ErrOrganizationNotFound when no organization with that name exists, or ErrOrganizationReadOnly for DefaultOrganizationName.

func (*DB) UpdateOrganizationEnvVar added in v0.16.0

func (d *DB) UpdateOrganizationEnvVar(org, key string, value *string, isSecret *bool) (*models.EnvVar, error)

UpdateOrganizationEnvVar partially updates an existing organization environment variable — a nil value/isSecret leaves that field unchanged. Returns ErrEnvVarNotFound when no such key exists on org.

func (*DB) UpdateRole added in v0.16.0

func (d *DB) UpdateRole(name, org string, description *string) (*models.RoleInfo, error)

UpdateRole updates a role's description. Name and org together identify the role and are immutable; pass a nil description to leave it unchanged. org must match exactly (empty means the global role, not "any org"). Returns ErrRoleNotFound when no role by that name is registered at all, or ErrRoleIsGlobal when it is registered but only as a global role.

func (*DB) UpdateUser

func (d *DB) UpdateUser(user *models.User) error

UpdateUser updates an existing user's fields, identified by username.

func (*DB) UpdateUserCredential

func (d *DB) UpdateUserCredential(id uint32, scope, subject, secret *string, active *bool) (*models.UserCredential, error)

UpdateUserCredential updates an existing user credential record. For dynamic credentials (kubernetes, dynamic git) Secret is ignored — the secret column stays NULL and is resolved live at request time. UpdateUserCredential partially updates a credential identified by id. Nil arguments leave the corresponding column unchanged. Credentials whose credential_source matches "idp.k8shell.io/*" — provisioned by the onboarding flow (CompleteUserWebFlow / CompleteUserDeviceFlow) — may only have active updated; attempting to change scope, subject, or secret returns ErrProtectedCredential. Returns models.ErrUserNotFound when no credential with that id exists.

func (*DB) UpdateUserEnvVar added in v0.16.0

func (d *DB) UpdateUserEnvVar(username, key string, value *string, isSecret *bool) (*models.EnvVar, error)

UpdateUserEnvVar partially updates an existing user-owned environment variable override — a nil value/isSecret leaves that field unchanged. Returns ErrEnvVarNotFound when username has no override for key; AddUserEnvVar must be used to create one first.

func (*DB) UpsertDynamicGitCredential

func (d *DB) UpsertDynamicGitCredential(username, providerName, serviceScope string) error

UpsertDynamicGitCredential inserts a dynamic git credential row for a user if one does not already exist for the given provider. serviceScope must be the provider address (URL) so that the git credentials helper can match credentials by URL. providerName is stored as credential_source so that ResolveCredential can route directly to the right IDP by name. The secret is NULL — the live token is fetched on demand from the provider via GetUserGitToken.

func (*DB) UpsertWaitlistEntry added in v0.16.0

func (d *DB) UpsertWaitlistEntry(idp, username, org string, roles []string, sudo bool, fullname, email string) error

UpsertWaitlistEntry records a pending onboarding attempt as a concrete (exact-username) row with action='waitlist', status='pending', carrying over the org/roles/sudo the matched rule already resolved to. This must be an upsert rather than a plain insert-if-new: the matched rule itself can already be this exact (idp, username_pattern) row — e.g. an admin-authored one-off "waitlist this specific user" rule, not a wildcard pattern — in which case "inserting" a new row always conflicts with itself, and previously used ON CONFLICT DO NOTHING, which silently left status stuck at whatever it was (typically 'none') and never advanced it to 'pending'. DO UPDATE fixes that while still behaving correctly on a genuine repeat attempt while already pending: action/ status/roles/sudo/fullname/email are refreshed to the latest resolved values (harmless no-ops when unchanged), and requested_at is preserved via COALESCE rather than reset to now() on every retry.

type OnboardDecision added in v0.16.0

type OnboardDecision struct {
	Action models.OnboardAction
	Org    string
	Roles  []string
	Sudo   bool
	RuleID int32

	// Fullname, when non-empty, overrides the display fullname recorded
	// against the onboard_rules row this decision is persisted to (see
	// Server.applyOnboardHint) — otherwise the provider's FindUser-reported
	// fullname is used, as before.
	Fullname string
}

OnboardDecision is the outcome of resolving a username's onboarding attempt against identity.onboard_rules: whether it's allowed at all, the org it should be placed into, and the roles/sudo it should be granted when allowed. RuleID identifies the row the decision came from (used to upsert a waitlist entry keyed off the same table, and for logging).

Jump to

Keyboard shortcuts

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