auth

package
v0.0.0-...-27e7fae Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2026 License: GPL-3.0 Imports: 68 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

Overview

Package auth implements the application service for the auth bounded context — orchestrates pkg/domain/auth entities and cross-cutting concerns (audit, notifications, RBAC).

Index

Constants

View Source
const (
	DiscoverNextPassword = "password"
	DiscoverNextSSO      = "sso"
)

Discovery next steps.

View Source
const (
	LinkProofLinkStart   = "link_start"
	LinkProofPendingLink = "pending_link"
	LinkProofUnlink      = "unlink"
)

Purposes of a sign-in method change, recorded in the audit event.

View Source
const (
	SAMLMetadataReasonEmpty         = "empty"
	SAMLMetadataReasonTooLarge      = "too_large"
	SAMLMetadataReasonDoctype       = "doctype"
	SAMLMetadataReasonMalformed     = "malformed"
	SAMLMetadataReasonNotMetadata   = "not_metadata"
	SAMLMetadataReasonNoIdP         = "no_idp"
	SAMLMetadataReasonNoEntityID    = "no_entity_id"
	SAMLMetadataReasonNoSSOURL      = "no_sso_url"
	SAMLMetadataReasonNoSigningCert = "no_signing_certificate"
	SAMLMetadataReasonInvalidCert   = "invalid_certificate"
	SAMLMetadataReasonCertExpired   = "certificate_expired"
	SAMLMetadataReasonTooManyCerts  = "too_many_certificates"
	SAMLMetadataReasonBadURL        = "invalid_url"
	SAMLMetadataReasonURLBlocked    = "url_blocked"
	SAMLMetadataReasonUnreachable   = "unreachable"
	SAMLMetadataReasonOneSource     = "one_source"
)

Reasons an IdP metadata import is refused (SAMLMetadataError.Reason). They are stable codes the console translates.

View Source
const (
	StepUpReasonInvalidCode     = "invalid_code"
	StepUpReasonReplayedCode    = "replayed_code"
	StepUpReasonInvalidPassword = "invalid_password"
	StepUpReasonAccountLocked   = "account_locked"
	StepUpReasonNoTOTPFactor    = "no_totp_factor"
	StepUpReasonDecryptError    = "decrypt_error"
	StepUpReasonRateLimited     = "rate_limited"
)

Reasons recorded in the metadata of a failed step-up audit event (auth.step_up_failed, key "reason"). The code itself is never recorded.

View Source
const CodeOwnSignInRequired apierror.Code = "OWN_SIGN_IN_REQUIRED"

CodeOwnSignInRequired is the API error code of ErrOwnSignInRequired.

View Source
const DefaultMFAIssuer = brand.DefaultName

DefaultMFAIssuer is the issuer label shown by authenticator apps.

View Source
const (
	// MaxIdPMetadataBytes caps an IdP metadata document, fetched or uploaded.
	MaxIdPMetadataBytes = 1 << 20
)
View Source
const ResendVerificationCooldown = 2 * time.Minute

ResendVerificationCooldown is the least time between two verification emails to one address: the per-address cap of POST /auth/resend-verification.

View Source
const SSOChangeReviewPath = "/settings/sso-approvals"

SSOChangeReviewPath is the web page where an owner reviews pending changes.

View Source
const StepUpFreshSession = 10 * time.Minute

StepUpFreshSession is how recent a sign-in must be for an SSO-only account without TOTP to pass step-up.

View Source
const StepUpWindow = 10 * time.Minute

StepUpWindow is how long a sign-in or a step-up unlocks sensitive actions in the same session (owner decision B7: 10 minutes, fixed, not sliding).

Variables

View Source
var (
	// ErrIdentityLinkedElsewhere: the provider account is already linked to
	// another account here.
	ErrIdentityLinkedElsewhere = errors.New("this provider account is already linked to another account")
	// ErrProviderAlreadyLinked: the account already has another account of
	// this provider linked; unlink it first.
	ErrProviderAlreadyLinked = errors.New("another account of this provider is already linked; unlink it first")
	// ErrLastSignInMethod: unlinking would leave the account with no way to
	// sign in.
	ErrLastSignInMethod = errors.New("this is the account's only sign-in method")
	// ErrIdentityNotUnlinkable: the identity belongs to an organization's
	// single sign-on and is managed there.
	ErrIdentityNotUnlinkable = errors.New("this sign-in method is managed by your organization")
	// ErrIdentityNotFound: the account has no identity with that id.
	ErrIdentityNotFound = errors.New("sign-in method not found")
)

Linking errors.

View Source
var (
	// ErrLinkProofRequired: the request carried no proof of the kind the
	// account needs (a password for an account with TOTP is not one).
	ErrLinkProofRequired = errors.New("confirm with your authenticator code or password to change sign-in methods")
	// ErrLinkProofFailed: the code or password was wrong, reused, or a
	// recovery code. Counts towards the lockout.
	ErrLinkProofFailed = errors.New("the code or password is not correct")
	// ErrLinkProofUnavailable: the account has neither TOTP nor a password
	// (or the session is not usable), so nothing can prove it here.
	ErrLinkProofUnavailable = errors.New("turn on two-factor authentication to change sign-in methods")
)

Proof errors.

View Source
var (
	// ErrMFAChallengeInvalid: the challenge token is unknown, expired, used,
	// burned by too many attempts, or for a different step.
	ErrMFAChallengeInvalid = errors.New("invalid or expired two-factor verification")
	// ErrMFACodeInvalid: the code (TOTP or recovery) was wrong or already used.
	ErrMFACodeInvalid = errors.New("invalid verification code")
	// ErrMFANotEnabled: the operation needs 2FA to be on.
	ErrMFANotEnabled = errors.New("two-factor authentication is not enabled")
	// ErrMFAAlreadyEnabled: setup was requested while 2FA is already on.
	ErrMFAAlreadyEnabled = errors.New("two-factor authentication is already enabled")
	// ErrMFANoPendingSetup: enable was called without a setup first.
	ErrMFANoPendingSetup = errors.New("start two-factor setup first")
	// ErrMFANotSupported: the account signs in through an identity provider,
	// which owns the second factor.
	ErrMFANotSupported = errors.New("two-factor authentication is managed by your identity provider")
	// ErrMFAEnrollmentRequired: an organization requires 2FA and this session
	// has not been through it: a password session whose user has not enrolled,
	// or a federated session not issued by that organization's own IdP.
	ErrMFAEnrollmentRequired = errors.New("this organization requires two-factor authentication")
	// ErrSSOMFAEvidenceRequired: the organization requires its identity
	// provider to prove a second factor and this sign-in carried no proof.
	// It is an ErrMFAEnrollmentRequired, so callers that only know that
	// error still refuse the token.
	ErrSSOMFAEvidenceRequired = fmt.Errorf("%w: the identity provider did not confirm a second factor", ErrMFAEnrollmentRequired)
	// ErrMFAUnavailable: the server was started without 2FA storage.
	ErrMFAUnavailable = errors.New("two-factor authentication is not available")
	// ErrMFAFederatedSession: a session from a social or identity-provider
	// sign-in cannot start our own second-factor step from an invitation.
	ErrMFAFederatedSession = errors.New("this session was started through an identity provider; sign in with your password to set up two-factor authentication")
	// ErrReauthRequired: an enrollment challenge was asked for with a session
	// that was not signed in recently. Binding a first authenticator is
	// account takeover if a stolen refresh token alone could do it, so the
	// person signs in again with the password (as EnableMFA requires).
	ErrReauthRequired = errors.New("sign in again to set up two-factor authentication")
)
View Source
var (
	// ErrMFAResetSelf: the caller targeted their own membership.
	ErrMFAResetSelf = fmt.Errorf("%w: you cannot reset your own two-factor authentication here; turn it off from your account security settings", shared.ErrValidation)
	// ErrMFAResetOwnerRequired: an owner or administrator target needs an owner.
	ErrMFAResetOwnerRequired = fmt.Errorf("%w: only the organization owner can reset the two-factor authentication of an owner or administrator", shared.ErrForbidden)
	// ErrMFAResetOtherOrganization: the target belongs to another organization
	// where the caller lacks the same authority.
	ErrMFAResetOtherOrganization = fmt.Errorf("%w: this user also belongs to another organization where you cannot manage them; ask an administrator of that organization", shared.ErrForbidden)
)
View Source
var (
	ErrOAuthDisabled       = errors.New("OAuth is disabled")
	ErrProviderDisabled    = errors.New("OAuth provider is disabled")
	ErrInvalidProvider     = errors.New("invalid OAuth provider")
	ErrInvalidState        = errors.New("invalid OAuth state")
	ErrOAuthExchangeFailed = errors.New("failed to exchange OAuth code")
	ErrOAuthUserInfoFailed = errors.New("failed to get user info from OAuth provider")
	// ErrOAuthAccountExists: the provider's email names an account that signs
	// in another way (a password, or another provider) and this provider
	// identity is not linked to it. Nothing was written. The person signs in
	// the usual way and links the provider from their account settings.
	ErrOAuthAccountExists = errors.New("an account with this email already exists; sign in to it and link this provider")
	// ErrOAuthUseOrgSSO: the provider identity is one an organization's single
	// sign-on created and manages. The social button never signs it in: the
	// person never confirmed that route. Nothing was written, no session opens.
	ErrOAuthUseOrgSSO = errors.New("this account signs in through your organization; use your organization's sign-in")
	// ErrOAuthNoEmail: the provider returned no email address.
	ErrOAuthNoEmail = errors.New("the OAuth provider did not return an email address")
)

OAuth errors.

View Source
var (
	ErrSAMLTenantNotFound = ErrSSOTenantNotFound
	ErrSAMLNotConfigured  = samldom.ErrNotFound
	ErrSAMLInvalidCert    = fmt.Errorf("%w: invalid IdP certificate (expected a PEM-encoded X.509 certificate)", shared.ErrValidation)
	ErrSAMLCertExpired    = fmt.Errorf("%w: the IdP certificate has expired; upload the IdP's current signing certificate", shared.ErrValidation)
	ErrSAMLDisabled       = fmt.Errorf("%w: SAML login is not enabled for this organization", shared.ErrValidation)
	// ErrSAMLResponseInvalid is a generic error for any assertion-validation
	// failure (signature, conditions, audience, InResponseTo). The specific
	// reason is logged server-side, never returned to the caller.
	ErrSAMLResponseInvalid = fmt.Errorf("%w: SAML response could not be validated", shared.ErrValidation)
)

SAML errors.

View Source
var (
	ErrInvalidCredentials   = errors.New("invalid email or password")
	ErrAccountLocked        = errors.New("account is locked due to too many failed attempts")
	ErrAccountSuspended     = errors.New("account is suspended")
	ErrEmailNotVerified     = errors.New("email is not verified")
	ErrRegistrationDisabled = errors.New("registration is disabled")
	// ErrSignupNotAvailable is the one refusal of every sign-up path the
	// sign-up policy does not admit (signup.Admit). The caller has written
	// nothing; the answer is the same whatever the reason.
	ErrSignupNotAvailable = errors.New("sign-up is not available")
	// ErrSignupSSORequired: the address is on a domain whose organization
	// requires its SSO; nothing was written and the person signs in there.
	ErrSignupSSORequired = errors.New("sign-up for this address goes through the organization's single sign-on")
	// ErrEmailNotAuthoritative: a social sign-in presented an e-mail address the
	// provider does not vouch for (a personal Google account on a company
	// address, a GitHub address) and the account is not bound to that provider
	// identity yet. Nothing was written.
	ErrEmailNotAuthoritative = errors.New("EMAIL_NOT_AUTHORITATIVE: this provider cannot prove ownership of this email address; sign in with your password (or ask an administrator) and link the provider afterwards")
	// ErrTeamURLNotAvailable: the organization URL (slug) cannot be used,
	// whether another organization has it or it is reserved.
	ErrTeamURLNotAvailable = fmt.Errorf("%w: this team URL is not available; choose another", shared.ErrValidation)
	// ErrTenantCreationDisabled: the admin_only sign-up policy is in force, so only the
	// platform administrator creates organizations (RFC-022).
	ErrTenantCreationDisabled   = errors.New("organization creation is reserved for the application administrator")
	ErrEmailAlreadyExists       = errors.New("email already exists")
	ErrInvalidResetToken        = errors.New("invalid or expired reset token")
	ErrInvalidVerificationToken = errors.New("invalid or expired verification token")
	ErrPasswordMismatch         = errors.New("current password is incorrect")
	ErrSessionLimitReached      = errors.New("maximum number of active sessions reached")
	ErrTenantAccessDenied       = errors.New("user does not have access to this tenant")
	ErrTenantRequired           = errors.New("tenant_id is required")
	// ErrSSORequired is returned when an SSO-enforced tenant refuses a
	// password-authenticated session at the tenant-selection / token-mint gate.
	// The tenant OWNER is exempt (break-glass), and federated (SSO/SAML) sessions
	// always pass — so the SSO login path itself is never blocked.
	ErrSSORequired = errors.New("this organization requires SSO sign-in")
)
View Source
var (
	ErrSSOTenantNotFound      = errors.New("tenant not found")
	ErrSSONoActiveProviders   = errors.New("no active SSO providers for this tenant")
	ErrSSOProviderNotFound    = errors.New("SSO provider not configured for this tenant")
	ErrSSOProviderInactive    = errors.New("SSO provider is not active")
	ErrSSOInvalidState        = errors.New("invalid SSO state token")
	ErrSSOExchangeFailed      = errors.New("failed to exchange authorization code")
	ErrSSOUserInfoFailed      = errors.New("failed to get user info from SSO provider")
	ErrSSODomainNotAllowed    = errors.New("email domain not allowed for this SSO provider")
	ErrSSODecryptionFailed    = errors.New("failed to decrypt client secret")
	ErrSSOProviderUnsupported = errors.New("unsupported SSO provider type")
	ErrSSOInvalidRedirectURI  = errors.New("invalid redirect URI")
	ErrSSOInvalidDefaultRole  = errors.New("invalid default role")
	ErrSSONoEmail             = errors.New("SSO provider did not return an email address")
	ErrSSOInvalidIDToken      = errors.New("SSO id_token failed validation")
	// ErrSSOProviderMisconfigured: an organization's Entra ID provider names
	// no single directory (empty, common, organizations, consumers or a
	// domain name instead of the directory id). Such a provider would accept
	// accounts of any Microsoft directory, or could never match the token's
	// tid, so sign-in through it is refused until the directory id is set.
	ErrSSOProviderMisconfigured = errors.New("SSO provider is misconfigured")
	// ErrSSONotAMember is returned when a federated login resolves to a user who
	// is not a member of the target tenant and does not qualify for JIT
	// auto-provisioning (FIX 2). The caller surfaces a generic "contact your
	// admin" outcome.
	ErrSSONotAMember = errors.New("not a member of this organization")
	// ErrSSORegistrationDisabled is returned when the sign-up policy is
	// false and an SSO/social login would create a brand-new user (FIX 4).
	ErrSSORegistrationDisabled = errors.New("registration is disabled")
	// ErrAccountLinkRequiresVerification is the proof-before-link refusal: a
	// federated (SSO/OAuth) login whose email matches a PRE-EXISTING account is
	// never silently adopted. It is returned when a real password-backed local
	// account exists (Case 1 — the user must sign in with their existing password
	// first, then link the IdP from an authenticated session) AND when a claimable
	// passwordless account cannot prove ownership (Case 2 — unverified email or a
	// tenant domain that is not DNS-verified). Fail-closed: matching an email is
	// never, on its own, enough to bind a federated identity.
	ErrAccountLinkRequiresVerification = errors.New(
		"an account with this email already exists; sign in with your existing credentials first, then link this identity provider")
	// ErrSSODifferentMethod: the email belongs to an account that signs in
	// another way (another identity provider, or another subject at this one).
	// The person is told to use the method they signed up with.
	ErrSSODifferentMethod = errors.New("this email is registered with a different sign-in method")
	// ErrEmailUnverifiedAtIDP: the identity provider did not vouch for the
	// email address, so no account is matched or created on it.
	ErrEmailUnverifiedAtIDP = errors.New("the identity provider did not verify the email address")
	// ErrUseAdminConsole: a platform administrator signs in on the admin
	// console only. Raised after the provider authenticated the person.
	ErrUseAdminConsole = errors.New("platform administrators sign in on the admin console")
)

SSO errors.

View Source
var (
	ErrStepUpRequired = errors.New("step-up re-authentication required")
	ErrStepUpFailed   = errors.New("step-up re-authentication failed")
	// ErrStepUpCodeReused is an authenticator code from a time step that was
	// already used (it signed the person in, or confirmed an earlier action).
	// It is an ErrStepUpFailed, so every caller that refuses a wrong code
	// refuses it the same way; the step-up endpoint tells the person to wait
	// for the next code instead of calling it wrong.
	ErrStepUpCodeReused = fmt.Errorf("%w: code already used", ErrStepUpFailed)
	// ErrStepUpNoFactor: the account was asked for a code but its
	// authenticator was removed meanwhile. Ask again (ErrStepUpRequired).
	ErrStepUpNoFactor = fmt.Errorf("%w: no authenticator", ErrStepUpRequired)
	// ErrStepUpSecretUnreadable: the stored authenticator secret could not be
	// decrypted. A server fault, never reported as a wrong code and not
	// counted towards the lockout.
	ErrStepUpSecretUnreadable = errors.New("step-up re-authentication unavailable: authenticator secret unreadable")
)

Step-up errors. ErrStepUpRequired carries no detail on purpose: the caller answers with the method the account needs (StepUpMethodFor).

View Source
var ErrAccountTokenHasOrganization = errors.New("the account belongs to an organization; exchange the token for it")

ErrAccountTokenHasOrganization: the account can open an organization, so it exchanges its refresh token for that organization's token instead.

View Source
var ErrFederatedIdentityConflict = errors.New("this email is registered with a different account at this identity provider")

ErrFederatedIdentityConflict refuses a login whose email names an account already bound to a different subject at the same identity provider.

View Source
var ErrLogoutTokenInvalid = errors.New("invalid logout_token")

ErrLogoutTokenInvalid is the single generic error returned for ANY logout_token validation failure. The endpoint maps it to a 400 with no detail so a caller cannot probe which check failed (and thus cannot learn which sids/issuers exist).

View Source
var ErrMFARequiredByPolicy = errors.New("two-factor authentication is required for your account")

ErrMFARequiredByPolicy: two-factor cannot be turned off because an organization or the platform floor requires it for this person. The error returned is an *MFARequiredError naming who requires it.

View Source
var ErrOwnSignInRequired = errors.New("this organization needs a sign-in with your own account")

ErrOwnSignInRequired refuses a token for an organization other than the one whose identity provider issued the session, when the account has its own sign-in that the provider skipped.

View Source
var ErrPendingLinkInvalid = errors.New("there is no sign-in method waiting to be linked to this account")

ErrPendingLinkInvalid: there is no pending link for this secret and this account (expired, spent, made for another account, or never made). One answer for every case.

View Source
var ErrPendingLinkNeedsSignIn = errors.New("sign in to the account again to link this sign-in method")

ErrPendingLinkNeedsSignIn: the session did not sign in (or step up) after the pending link was made.

View Source
var ErrPersonalAccountsBlocked = errors.New("this organization does not accept personal email accounts")

ErrPersonalAccountsBlocked refuses a token for a personal account in an organization that blocks personal accounts.

View Source
var ErrSSOAwaitingApproval = errors.New("access to this organization awaits an administrator's approval")

ErrSSOAwaitingApproval: the organization admitted the person through SSO, and an administrator has not approved them yet.

View Source
var ErrSSOBreakGlassNeedsMFA = fmt.Errorf("%w: owner break-glass needs the owner's second factor", ErrSSORequired)

ErrSSOBreakGlassNeedsMFA: the owner's password is not enough to enter an organization that requires SSO; the owner's second factor must have been verified at sign-in too.

View Source
var ErrSSOFederatedDomainUnverified = errors.New("federated login not permitted: email domain is not verified for this organization")

ErrSSOFederatedDomainUnverified is returned when a federated login matches an existing account whose email domain the organization has not DNS-verified: the organization's IdP cannot vouch for an identity on a domain it does not own.

View Source
var ErrSSOFederatedNotMember = errors.New("federated login not permitted: user is not a member of this organization")

ErrSSOFederatedNotMember is returned when a federated login matches an existing global user who is not a member of the target tenant — blocking a malicious tenant from forging an assertion for another tenant's user.

View Source
var ErrSSOFederatedTakeover = errors.New("email is registered with a password; federated login not allowed")

ErrSSOFederatedTakeover is returned when a federated (e.g. SAML) login resolves to an existing password-backed local account — logging into it from an external assertion would be account takeover.

View Source
var ErrStepUpUnavailable = errors.New("step-up re-authentication unavailable for this session")

ErrStepUpUnavailable means this session cannot step up here: the account has neither TOTP nor a password (SSO-only: sign in again instead), or the session is not an active session of the user.

View Source
var (
	// ErrTOTPNotEnrolled: the account has no authenticator app (or the
	// platform has two-factor authentication turned off).
	ErrTOTPNotEnrolled = errors.New("no authenticator app is enrolled for this account")
)

Fresh authenticator code errors.

Functions

func CertificateFingerprint

func CertificateFingerprint(cert string) string

CertificateFingerprint is the SHA-256 (hex) of a PEM/base64 certificate's normalized text, for showing which certificate a change installs without repeating it.

func CertificateNotAfter

func CertificateNotAfter(certPEM string) time.Time

CertificateNotAfter is the expiry of a stored IdP certificate (zero when it does not parse).

func DescribeSSOChange

func DescribeSSOChange(c *ssochange.Change) string

DescribeSSOChange is a one-line, secret-free description of a change.

func JITRaises

func JITRaises(oldOn bool, oldRole string, on bool, role string) bool

JITRaises reports whether moving from (oldOn, oldRole) to (on, role) admits more people or gives them more.

func MFAIssuer

func MFAIssuer(name, appURL string) string

MFAIssuer is the issuer label of a new authenticator entry: the product name and the host people sign in to, e.g. "OpenCTEM (app.example.com)". A person with an account on two installations (a staging and a production one) then sees two entries they can tell apart; with the name alone both entries look the same and the code of the other one is refused. Only new enrolments use it: an existing entry keeps the label it was created with, and the secret is untouched. The host is the hostname only (no port: a colon would split the otpauth label).

func StepUpFailureReason

func StepUpFailureReason(err error, method StepUpMethod) string

StepUpFailureReason names a VerifyStepUp error for the audit trail, or "" for an error that is not a refused proof (nothing given, an SSO session, an infrastructure error).

func TokenEndpoint

func TokenEndpoint(provider OAuthProvider) string

TokenEndpoint is the fixed token endpoint of a social provider ("" for an unknown one). Nothing a request or a setting says changes it.

func WithClientInfo

func WithClientInfo(ctx context.Context, ip, userAgent string) context.Context

WithClientInfo returns ctx carrying the signing-in browser's address and user agent, for the federated sign-ins (SSO, SAML, social OAuth) whose service calls take no request.

Types

type APIKeyRevoker

type APIKeyRevoker interface {
	// RevokeAllForUser revokes every active key the user owns, in every
	// organization, and returns how many.
	RevokeAllForUser(ctx context.Context, userID shared.ID) (int, error)
	// CountActiveForUser counts the active keys the user owns.
	CountActiveForUser(ctx context.Context, userID shared.ID) (int, error)
}

APIKeyRevoker revokes the API keys a person owns (apikey.Service). It is optional: called only when the request asks for it.

type AcceptInvitationWithRefreshTokenInput

type AcceptInvitationWithRefreshTokenInput struct {
	RefreshToken    string `json:"refresh_token" validate:"required"`
	InvitationToken string `json:"invitation_token" validate:"required"`
}

AcceptInvitationWithRefreshTokenInput represents the input for accepting an invitation.

type AcceptInvitationWithRefreshTokenResult

type AcceptInvitationWithRefreshTokenResult struct {
	AccessToken  string               `json:"access_token"`
	RefreshToken string               `json:"refresh_token"` // Rotated refresh token
	ExpiresAt    time.Time            `json:"expires_at"`
	Tenant       TenantMembershipInfo `json:"tenant"`
	Role         string               `json:"role"`
}

AcceptInvitationWithRefreshTokenResult represents the result of accepting an invitation.

type AccountTokenResult

type AccountTokenResult struct {
	AccessToken  string
	RefreshToken string
	ExpiresAt    time.Time
}

AccountTokenResult is an access token with no tenant and the rotated refresh token (for the httpOnly cookie only).

type AddressHolder

type AddressHolder interface {
	HeldBy(ctx context.Context, tenantID shared.ID, email string) (bool, error)
}

AddressHolder answers whether an organization has verified the domain of an e-mail address (the rule that lets an organization create accounts directly).

type AuthService

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

AuthService handles authentication operations.

func NewAuthService

func NewAuthService(
	userRepo userdom.Repository,
	sessionRepo sessiondom.Repository,
	refreshTokenRepo sessiondom.RefreshTokenRepository,
	tenantRepo tenantdom.Repository,
	auditService *auditapp.AuditService,
	cfg config.AuthConfig,
	log *logger.Logger,
) *AuthService

NewAuthService creates a new AuthService.

func (*AuthService) AcceptInvitationWithRefreshToken

AcceptInvitationWithRefreshToken accepts an invitation using a refresh token. This endpoint is for users who were invited but don't have a tenant yet, so they only have a refresh token (no access token).

func (*AuthService) AccountActive

func (s *AuthService) AccountActive(ctx context.Context, userID shared.ID) (bool, error)

AccountActive reports whether the user can still sign in (active and not locked). The admin console checks it on every request.

func (*AuthService) AccountToken

func (s *AuthService) AccountToken(ctx context.Context, refreshToken string) (*AccountTokenResult, error)

AccountToken mints an access token without a tenant claim for an account that has no organization it can open (none at all, or every one is suspended or closed). That token reaches only the account allow-list (middleware/tenantless.go); every other route refuses it. The refresh token is checked exactly as for an organization token (replay detection, active session and account) and is rotated in the same family. An account that can open an organization is refused, so a member never holds a token that skips the organization's sign-in policies (SSO, 2FA, verified email).

func (*AuthService) AddSessionsRevokedHook

func (s *AuthService) AddSessionsRevokedHook(h SessionsRevokedHook)

AddSessionsRevokedHook appends a hook run after the account's sessions were revoked.

func (*AuthService) AuditStepUpRateLimited

func (s *AuthService) AuditStepUpRateLimited(ctx context.Context, actx auditapp.AuditContext, userID string)

AuditStepUpRateLimited records a step-up refused by the rate limit before any proof was checked (reason rate_limited). The caller limits how often it is called per user, so a flood of refused requests is not a flood of rows.

func (*AuthService) BeginMFAEnrollmentFromChallenge

func (s *AuthService) BeginMFAEnrollmentFromChallenge(ctx context.Context, token string) (*MFASetup, error)

BeginMFAEnrollmentFromChallenge issues a secret to a user who was sent to enrollment by their organization's policy. The challenge stays open until CompleteMFAEnrollmentFromChallenge.

func (*AuthService) BeginMFAReplacement

func (s *AuthService) BeginMFAReplacement(ctx context.Context, userID, currentPassword, code string) (*MFASetup, error)

BeginMFAReplacement starts moving the user's second factor to a new authenticator. It needs the current password and a code from the current authenticator or an unused recovery code, so a hijacked session alone cannot bind an attacker's device; a person who lost their phone uses a recovery code. The current authenticator keeps working until ConfirmMFAReplacement, so the account is never without a second factor.

func (*AuthService) BeginMFASetup

func (s *AuthService) BeginMFASetup(ctx context.Context, userID string) (*MFASetup, error)

BeginMFASetup generates a new secret for the signed-in user. It does not change anything that authenticates until EnableMFA confirms a code.

func (*AuthService) ChangePassword

func (s *AuthService) ChangePassword(ctx context.Context, userID string, input ChangePasswordInput) error

ChangePassword changes a user's password (requires authentication).

func (*AuthService) CheckCredentialFactor

func (s *AuthService) CheckCredentialFactor(ctx context.Context, userID, tenantID, sessionID string) error

CheckCredentialFactor gates creating a credential (API key, sensor enrolment, integration secret): when the organization or the platform floor covers the user, they must already hold a second factor, even while their grace period for sign-in has not ended. The sign-in rules apply as at token mint: a session from the organization's own identity provider counts unless the organization requires that provider to prove 2FA, a social or foreign provider session never counts. A caller with no platform session (an external OIDC token, whose provider owns 2FA) is not asked. It returns ErrMFAEnrollmentRequired or ErrSSOMFAEvidenceRequired.

func (*AuthService) CheckEntry

func (s *AuthService) CheckEntry(ctx context.Context, sessionID, userID, tenantID string) error

CheckEntry re-applies, for the organization tenantID, the requirements that token issuance applies: the verified-email rule, SSO enforcement, the identity provider binding (another organization's IdP does not stand in for the account's own sign-in), the organization's two-factor rule, its personal-account policy and the outside-member privilege rule. It runs on every request of a route that names the organization in the URL (/api/v1/tenants/{tenant}/...): such a route accepts a token minted for another organization, and the requirements of the organization in the URL must hold there too. The session is the token's own session, so a social or other federated sign-in is judged exactly as it would be at token issuance. A refusal is an *EntryRefusal; any other error is a failure to decide and the caller must refuse the request.

func (*AuthService) CompleteMFAEnrollmentFromChallenge

func (s *AuthService) CompleteMFAEnrollmentFromChallenge(ctx context.Context, input CompleteMFAEnrollmentInput) (*LoginResult, []string, error)

CompleteMFAEnrollmentFromChallenge confirms the enrollment with a code, turns 2FA on and signs the user in. The recovery codes are returned once.

func (*AuthService) ConfirmMFAReplacement

func (s *AuthService) ConfirmMFAReplacement(ctx context.Context, actx auditapp.AuditContext, userID, code string) ([]string, error)

ConfirmMFAReplacement proves the new authenticator with one of its codes, makes it the only one, replaces every recovery code and signs out every other session of the user (a session opened with the old device must not outlive it). The new recovery codes are returned once.

func (*AuthService) CreateFirstTeam

func (s *AuthService) CreateFirstTeam(ctx context.Context, input CreateFirstTeamInput) (*CreateFirstTeamResult, error)

CreateFirstTeam creates the first team for a user who has no tenants. This endpoint uses refresh_token for authentication since user has no access_token yet.

func (*AuthService) CreateInvitedAccount

func (s *AuthService) CreateInvitedAccount(ctx context.Context, email, name string, ttl time.Duration) (*InvitedAccount, error)

CreateInvitedAccount creates a verified local account with no password for a new platform administrator (RFC-022) and a single-use set-password token valid for ttl. Nobody learns a password for the account: the administrator chooses one with the emailed link. It refuses an email that already has an account (ErrEmailAlreadyExists): with self-registration an attacker can pre-register an administrator's email, so linking an existing account would hand them the administrator.

func (*AuthService) DisableMFA

func (s *AuthService) DisableMFA(ctx context.Context, actx auditapp.AuditContext, userID, currentPassword, code string) error

DisableMFA turns 2FA off. It needs the current password and a valid code (TOTP or an unused recovery code), so a hijacked session alone cannot strip the second factor. It is refused with an *MFARequiredError while an organization or the platform floor requires the factor (the person replaces their authenticator instead, BeginMFAReplacement). Turning it off signs out every other session of the user.

func (*AuthService) EnableMFA

func (s *AuthService) EnableMFA(ctx context.Context, actx auditapp.AuditContext, userID, currentPassword, code string) ([]string, error)

EnableMFA confirms the pending secret with a code and turns 2FA on. It needs the current password: enabling signs out every other session, so with a stolen session alone an attacker could otherwise bind their own authenticator and lock the real user out (settings audit A-M1). Every other session of the user is signed out, so a session opened with a stolen password before 2FA was turned on does not survive it. The recovery codes are returned once and only their hashes are kept.

func (*AuthService) ExchangeToken

func (s *AuthService) ExchangeToken(ctx context.Context, input ExchangeTokenInput) (*ExchangeTokenResult, error)

ExchangeToken exchanges a global refresh token for a tenant-scoped access token. This is the main method for getting access tokens after login.

func (*AuthService) ForgotPassword

func (s *AuthService) ForgotPassword(ctx context.Context, input ForgotPasswordInput) (*ForgotPasswordResult, error)

ForgotPassword initiates a password reset.

func (*AuthService) GetMFAStatus

func (s *AuthService) GetMFAStatus(ctx context.Context, userID string) (*MFAStatus, error)

GetMFAStatus returns the user's 2FA state.

func (*AuthService) GetStepUpState

func (s *AuthService) GetStepUpState(ctx context.Context, userID, sessionID string) (*StepUpState, error)

GetStepUpState reports the method the account needs and the open window.

func (*AuthService) IdentifyRefreshSession

func (s *AuthService) IdentifyRefreshSession(ctx context.Context, refreshToken string) (*RefreshSessionIdentity, error)

IdentifyRefreshSession validates a refresh token the same way ExchangeToken does (signature, stored and unused, family replay detection, active session) and returns who is signed in, without issuing or rotating any token. The platform admin console uses it to start its own session from the normal /login sign-in (RFC-022 rev. 2).

func (*AuthService) LinkProofMethod

func (s *AuthService) LinkProofMethod(ctx context.Context, userID string) (StepUpMethod, error)

LinkProofMethod returns StepUpTOTP or StepUpPassword, or "" for an account that has neither.

func (*AuthService) LinkedSignInChallenge

func (s *AuthService) LinkedSignInChallenge(ctx context.Context, u *userdom.User, ip, ua string) (*MFAChallengeInfo, error)

LinkedSignInChallenge is the second step of a sign-in to a password account through a linked provider: exactly what its password sign-in would ask (loginMFAChallenge), nil when nothing is needed.

func (*AuthService) LogSessionRevoked

func (s *AuthService) LogSessionRevoked(ctx context.Context, actx auditapp.AuditContext, sessionID string, allOthers bool)

LogSessionRevoked audits a user signing out one (or all other) sessions.

func (*AuthService) Login

func (s *AuthService) Login(ctx context.Context, input LoginInput) (result *LoginResult, err error)

Login authenticates a user and creates a session. Returns a global refresh token and list of tenant memberships. Client should call ExchangeToken to get a tenant-scoped access token.

func (*AuthService) Logout

func (s *AuthService) Logout(ctx context.Context, sessionID string) error

Logout revokes a session.

func (*AuthService) LogoutByRefreshToken

func (s *AuthService) LogoutByRefreshToken(ctx context.Context, refreshToken string) error

LogoutByRefreshToken ends the session a refresh token belongs to. Signing out must not depend on the 15-minute access token: a user who idles past it and then signs out holds only the refresh token, and the session (with its refresh chain) used to stay valid for days after the browser dropped its cookies. The token's signature is checked and the stored row names the session; a token that is unknown, expired or forged ends nothing and is not an error the caller can act on, so it returns nil.

func (*AuthService) OwnSignInRequired

func (s *AuthService) OwnSignInRequired(ctx context.Context, userID, sessionID string) (bool, error)

OwnSignInRequired reports whether an action on the account itself (not on one organization) must be refused for this session: the session was issued by an organization's identity provider and the account has a sign-in of its own. Deleting the account or signing it out everywhere reaches every organization the person belongs to, so no single organization's IdP may do it in the account's name; the person signs in with their own account. An account the IdP created (no sign-in of its own) is not refused.

func (*AuthService) RecentAuthAt

func (s *AuthService) RecentAuthAt(ctx context.Context, userID, sessionID string) (time.Time, error)

RecentAuthAt returns when userID last authenticated in sessionID (sign-in or step-up). ErrStepUpUnavailable when the session cannot be used.

func (*AuthService) RecordConsolePasswordFailure

func (s *AuthService) RecordConsolePasswordFailure(ctx context.Context, userID shared.ID)

RecordConsolePasswordFailure counts a refused console sign-in (a correct password the console still turned away) toward the account's lockout.

func (*AuthService) RecordConsolePasswordSuccess

func (s *AuthService) RecordConsolePasswordSuccess(ctx context.Context, userID shared.ID)

RecordConsolePasswordSuccess resets the failed-sign-in counter of an account the console has accepted as an active, unlocked administrator.

func (*AuthService) RefreshToken

func (s *AuthService) RefreshToken(ctx context.Context, input RefreshTokenInput) (*RefreshTokenResult, error)

RefreshToken rotates the refresh token and issues new tenant-scoped access token. This implements token rotation for security while providing tenant-scoped access.

func (*AuthService) RegenerateRecoveryCodes

func (s *AuthService) RegenerateRecoveryCodes(ctx context.Context, actx auditapp.AuditContext, userID, code string) ([]string, error)

RegenerateRecoveryCodes replaces every recovery code. It needs a current TOTP code (not a recovery code) so it proves possession of the device.

func (*AuthService) Register

func (s *AuthService) Register(ctx context.Context, input RegisterInput) (*RegisterResult, error)

Register creates a new local user account. Security note: To prevent email enumeration attacks, this method returns a success result even if the email already exists. The caller should always display a generic "check your email" message regardless of the result.

func (*AuthService) ResendVerification

func (s *AuthService) ResendVerification(ctx context.Context, email string) (*ResendVerificationResult, error)

ResendVerification issues a new verification token for the account with email when it is a local, active, still unverified account and no verification email left in the last ResendVerificationCooldown (the issue time is the stored expiry minus the verification lifetime). The previous link stops working. Every other case returns (nil, nil).

func (*AuthService) ResetMemberMFA

func (s *AuthService) ResetMemberMFA(ctx context.Context, actx auditapp.AuditContext, tenantID, membershipID string) error

ResetMemberMFA turns off the second factor of the member with membershipID in tenantID, on behalf of actx.ActorID. See the file comment for the rules.

func (*AuthService) ResetPassword

func (s *AuthService) ResetPassword(ctx context.Context, input ResetPasswordInput) error

ResetPassword resets a user's password using the reset token.

func (*AuthService) ResetUserMFAByConsole

func (s *AuthService) ResetUserMFAByConsole(ctx context.Context, id shared.ID, ip string) error

ResetUserMFAByConsole turns off the second factor of the local account id and signs it out everywhere. The next sign-in is a password sign-in, and enrolls again where an organization requires it. ErrMFANotEnabled when the account has no active factor.

func (*AuthService) SessionMFAChallenge

func (s *AuthService) SessionMFAChallenge(ctx context.Context, refreshToken, ip, ua string) (*MFAChallengeInfo, error)

SessionMFAChallenge issues the second-factor challenge for a signed-in person whose session cannot open an organization (ErrMFAEnrollmentRequired), for example right after accepting an invitation or when a token refresh is refused. The caller proves the session with its refresh token, exactly as AcceptInvitationWithRefreshToken does; the token is not spent. A user without an enabled factor gets an enrollment challenge, a user who has one gets a verify challenge. Enrollment needs a recent sign-in (sessionEnrollFreshness, else ErrReauthRequired); a verify challenge does not. Federated sessions are refused: they cannot complete our second step here.

func (*AuthService) SessionsRevoked

func (s *AuthService) SessionsRevoked() *SessionsRevokedHooks

SessionsRevoked returns the shared hook list, for services that revoke sessions outside AuthService (SessionService).

func (*AuthService) SetAPIKeyRevoker

func (s *AuthService) SetAPIKeyRevoker(k APIKeyRevoker)

SetAPIKeyRevoker wires the optional API key revocation.

func (*AuthService) SetAddressHolder

func (s *AuthService) SetAddressHolder(h AddressHolder)

SetAddressHolder wires the domain-holder check used to decide whether an invitation may vouch for the address it names.

func (*AuthService) SetBreakGlassGate

func (s *AuthService) SetBreakGlassGate(g BreakGlassGate)

SetBreakGlassGate wires the main-site refusal of break-glass accounts (password, refresh-token and exchange paths).

func (*AuthService) SetBreakGlassNotifier

func (s *AuthService) SetBreakGlassNotifier(n BreakGlassNotifier)

SetBreakGlassNotifier wires the notice sent when an owner uses break-glass.

func (*AuthService) SetHomeRealm

func (s *AuthService) SetHomeRealm(trusts TrustLookup, owners HomeDomainOwnerLookup)

SetHomeRealm wires home-realm sign-in for external members. Without it a session counts only for the organization whose identity provider issued it.

func (*AuthService) SetInvitationAcceptor

func (s *AuthService) SetInvitationAcceptor(a InvitationAcceptor)

SetInvitationAcceptor wires invitation acceptance for the refresh-token path.

func (*AuthService) SetLapsedDomainChecker

func (s *AuthService) SetLapsedDomainChecker(c LapsedDomainChecker)

SetLapsedDomainChecker wires the lapsed-domain rule for password resets.

func (*AuthService) SetMFA

func (s *AuthService) SetMFA(repo mfa.Repository, encryptor crypto.Encryptor, issuer string)

SetMFA enables two-factor authentication. Without it Login never asks for a second step and the /users/me/2fa endpoints report ErrMFAUnavailable.

func (*AuthService) SetMFAFloor

func (s *AuthService) SetMFAFloor(floor MFAFloorSource, priv PrivilegeSource)

SetMFAFloor wires the platform floor and the privilege lookup. Without a floor source only the organizations' own requirements apply; without a privilege source "administrator" means the owner and admin roles.

func (*AuthService) SetOrganizationGate

func (s *AuthService) SetOrganizationGate(g tenantdom.AccessGate)

SetOrganizationGate wires the organization access gate: no tenant-scoped token is minted or refreshed for a suspended organization.

func (*AuthService) SetPermissionVersionService

func (s *AuthService) SetPermissionVersionService(svc *accesscontrol.PermissionVersionService)

SetPermissionVersionService wires the permission version service so issued tenant-scoped access tokens carry the user's current permission version. Without it, tokens carry version 0 and the stale-permission check in the permission-sync middleware never fires (AUTHZ-3).

func (*AuthService) SetRoleService

func (s *AuthService) SetRoleService(roleService *accesscontrol.RoleService)

SetRoleService sets the role service for database-driven permissions. When set, the auth service will fetch permissions from the database instead of using hardcoded role-permission mappings.

func (*AuthService) SetSMTPChecker

func (s *AuthService) SetSMTPChecker(checker SMTPAvailabilityCheck)

SetSMTPChecker injects the SMTP availability checker used for smart email verification (auto mode). If not set, the service falls back to the global RequireEmailVerification flag from config.

func (*AuthService) SetSecurityNotifier

func (s *AuthService) SetSecurityNotifier(n SecurityNotifier)

SetSecurityNotifier wires the account security e-mails.

func (*AuthService) SetSelfServiceLimits

func (s *AuthService) SetSelfServiceLimits(l SelfServiceLimits)

SetSelfServiceLimits wires the self-service default limits.

func (*AuthService) SetSessionRevocationStore

func (s *AuthService) SetSessionRevocationStore(store SessionRevocationStore)

SetSessionRevocationStore wires immediate access-token revocation.

func (*AuthService) SetSignInHook

func (s *AuthService) SetSignInHook(h SignInHook)

SetSignInHook wires the hook run after a password sign-in.

func (*AuthService) SetSignupDomainPolicy

func (s *AuthService) SetSignupDomainPolicy(src signupdom.DomainPolicySource)

SetSignupDomainPolicy wires the per-domain sign-up policy of claimed domains.

func (*AuthService) SetSignupPolicy

func (s *AuthService) SetSignupPolicy(p signupdom.PolicySource)

SetSignupPolicy wires the platform sign-up policy (the console setting).

func (*AuthService) SetSignupRecorder

func (s *AuthService) SetSignupRecorder(r signupevent.Recorder)

SetSignupRecorder wires the sign-up event recorder.

func (*AuthService) StepUp

func (s *AuthService) StepUp(ctx context.Context, actx auditapp.AuditContext, userID, sessionID string, proof StepUpProof) (time.Time, error)

StepUp verifies proof for the signed-in user and opens a new window on the session that made the request. It returns when the window closes.

An SSO-only account without TOTP has nothing to verify here: it gets ErrStepUpUnavailable and must sign in again (a fresh session is inside the window). That path never stamps the session, so a session cannot extend its own window without a new proof.

func (*AuthService) StepUpMethodFor

func (s *AuthService) StepUpMethodFor(ctx context.Context, userID string) (StepUpMethod, error)

StepUpMethodFor returns what userID must present.

func (*AuthService) ValidateAccessToken

func (s *AuthService) ValidateAccessToken(tokenString string) (*jwt.Claims, error)

ValidateAccessToken validates an access token and returns the claims.

func (*AuthService) VerifyConsolePassword

func (s *AuthService) VerifyConsolePassword(ctx context.Context, email, password, ipAddress, userAgent string) (*userdom.User, error)

VerifyConsolePassword is the platform console's own first factor (RFC-022 revision 20): the account's password, checked like a sign-in (lockout, enumeration-safe), without opening a /login session or asking the account's own second factor; the console asks its own next. It does not reset the failed-sign-in counter: the caller does that with RecordConsolePasswordSuccess only once the account is known to be an active, unlocked administrator, so a tenant password cannot clear the lockout through the console.

func (*AuthService) VerifyEmail

func (s *AuthService) VerifyEmail(ctx context.Context, token string) error

VerifyEmail verifies a user's email with the verification token.

func (*AuthService) VerifyFreshTOTP

func (s *AuthService) VerifyFreshTOTP(ctx context.Context, userID, code string) error

VerifyFreshTOTP checks a code from userID's authenticator app for an action that needs proof of presence with the second factor itself, not only a recent sign-in (an owner approving their own scope entry). A password does not do; a code is accepted once (the factor's step advances), and a wrong code counts towards the account lockout. It answers ErrTOTPNotEnrolled, ErrAccountLocked or ErrStepUpFailed.

func (*AuthService) VerifyLinkProof

func (s *AuthService) VerifyLinkProof(ctx context.Context, actx auditapp.AuditContext, userID, sessionID string, proof StepUpProof, purpose string) (StepUpMethod, error)

VerifyLinkProof checks the proof typed for one sign-in method change. It never stamps the session: the next change needs a new proof.

func (*AuthService) VerifyMFALogin

func (s *AuthService) VerifyMFALogin(ctx context.Context, input VerifyMFAInput) (*LoginResult, error)

VerifyMFALogin completes a login that needed a second factor. On success it returns the same result a password-only login would have.

func (*AuthService) VerifyStepUp

func (s *AuthService) VerifyStepUp(ctx context.Context, userID, sessionID string, proof StepUpProof) error

VerifyStepUp checks proof for userID signed in with sessionID. It returns nil on success, ErrStepUpRequired when nothing usable was given (or the SSO session is too old) and ErrStepUpFailed for a wrong code or password, which also counts towards the lockout (ErrStepUpCodeReused, an ErrStepUpFailed, for a code from a step already used). ErrStepUpSecretUnreadable is a server fault and counts for nothing.

type AuthorizationURLInput

type AuthorizationURLInput struct {
	Provider      OAuthProvider
	RedirectURI   string // Frontend callback URL
	FinalRedirect string // Where to redirect after successful auth
}

AuthorizationURLInput represents input for getting authorization URL.

type AuthorizationURLResult

type AuthorizationURLResult struct {
	AuthorizationURL string `json:"authorization_url"`
	State            string `json:"state"`
	// BrowserBinding is a one-time secret for the browser that started the
	// flow, returned with the callback to prove the state is its own.
	BrowserBinding string `json:"browser_binding"`
}

AuthorizationURLResult represents the result of getting authorization URL.

type BreakGlassGate

type BreakGlassGate interface {
	IsBreakGlass(ctx context.Context, userID shared.ID) bool
}

BreakGlassGate answers whether a users-table account is linked to a break-glass administrator. A regular platform administrator signs in on the main site like any user (RFC-134); a break-glass account is sealed for emergencies and signs in on the admin console only, where its use raises the break-glass alert and audit. The main site never opens a session for it.

type BreakGlassNotifier

type BreakGlassNotifier interface {
	NotifyAdmins(ctx context.Context, tenantID shared.ID, title, body, severity string)
}

BreakGlassNotifier tells an organization's administrators about an owner break-glass sign-in (TenantService.NotifyAdmins).

type CallbackInput

type CallbackInput struct {
	Provider    OAuthProvider
	Code        string
	State       string
	RedirectURI string
	// BrowserBinding is the secret the authorize call returned to this browser.
	BrowserBinding string
}

CallbackInput represents the OAuth callback input.

type CallbackResult

type CallbackResult struct {
	AccessToken  string        `json:"access_token"`
	RefreshToken string        `json:"refresh_token"`
	ExpiresIn    int64         `json:"expires_in"`
	TokenType    string        `json:"token_type"`
	User         *userdom.User `json:"user"`
	// MFAChallenge is set when the account is a password account with a
	// second factor (or an organization requires one): no session was
	// issued, and the challenge opens the same second step a password
	// sign-in takes (POST /auth/mfa/verify or the enrollment steps).
	MFAChallenge *MFAChallengeInfo `json:"-"`
}

CallbackResult represents the OAuth callback result.

type ChangePasswordInput

type ChangePasswordInput struct {
	CurrentPassword string `json:"current_password" validate:"required"`
	NewPassword     string `json:"new_password" validate:"required,min=8,max=128"`
	// CurrentSessionID, when set, is the session making the change: it stays
	// signed in while every other session is revoked. Empty revokes all.
	CurrentSessionID string `json:"-"`
	// RevokeAPIKeys also revokes every API key the person owns.
	RevokeAPIKeys bool   `json:"-"`
	IPAddress     string `json:"-"`
	UserAgent     string `json:"-"`
}

ChangePasswordInput represents the input for changing password.

type ClaimMembershipSource

type ClaimMembershipSource interface {
	GetUserMembershipsWithStatus(ctx context.Context, userID shared.ID) (*tenantdom.UserMembershipsByStatus, error)
}

ClaimMembershipSource lists an account's organization memberships, active and suspended (the tenant repository satisfies it).

type ClientInfo

type ClientInfo struct {
	IP        string
	UserAgent string
}

ClientInfo is the browser that signs in: its address (resolved by the handler through the trusted-proxy rules) and its user agent.

type CompleteMFAEnrollmentInput

type CompleteMFAEnrollmentInput struct {
	Token     string
	Code      string
	IPAddress string
	UserAgent string
}

CompleteMFAEnrollmentInput confirms an enrollment started from a login enrollment challenge.

type ConfirmPendingLinkInput

type ConfirmPendingLinkInput struct {
	UserID    string
	SessionID string
	Token     string
	// Proof is the code or password typed in the confirm dialog
	// (link_proof.go). The sign-in that just happened does not count.
	Proof StepUpProof
}

ConfirmPendingLinkInput confirms a pending link from the signed-in account.

type CreateFirstTeamInput

type CreateFirstTeamInput struct {
	RefreshToken string `json:"refresh_token" validate:"required"`
	TeamName     string `json:"team_name" validate:"required,min=2,max=100"`
	TeamSlug     string `json:"team_slug" validate:"required,min=3,max=50"`
	// IPAddress and UserAgent are recorded in the tenant.created audit event.
	IPAddress string `json:"-"`
	UserAgent string `json:"-"`
}

CreateFirstTeamInput represents the input for creating first team.

type CreateFirstTeamResult

type CreateFirstTeamResult struct {
	AccessToken  string               `json:"access_token"`
	RefreshToken string               `json:"refresh_token"` // Rotated refresh token
	ExpiresAt    time.Time            `json:"expires_at"`
	Tenant       TenantMembershipInfo `json:"tenant"`
}

CreateFirstTeamResult represents the result of creating first team.

type CreateProviderInput

type CreateProviderInput struct {
	TenantID         string
	Provider         string
	DisplayName      string
	ClientID         string
	ClientSecret     string // Plaintext - will be encrypted
	IssuerURL        string
	TenantIdentifier string
	Scopes           []string
	AllowedDomains   []string
	AutoProvision    bool
	DefaultRole      string
	CreatedBy        string
}

CreateProviderInput is the input for creating an identity provider config.

type DiscoverResult

type DiscoverResult struct {
	// Next is "sso" when the email's domain signs in through an
	// organization's SSO, else "password" (password or social sign-in).
	Next string `json:"next"`
	// Org is an opaque, expiring reference to the organization whose SSO to
	// start ("" for password). It is accepted wherever an organization slug
	// is (the providers list and the authorize start), so discovery never
	// hands out an organization's slug.
	Org string `json:"org"`
}

DiscoverResult is the answer to an email: the same fields always.

type DomainJITPayload

type DomainJITPayload struct {
	Domain     string `json:"domain"`
	JITEnabled bool   `json:"jit_enabled"`
	JITRole    string `json:"jit_role"`
}

DomainJITPayload is a proposed per-domain provisioning.

type DomainJITPolicy

type DomainJITPolicy interface {
	DomainJITPolicy(ctx context.Context, tenantID, emailDomain string) (enabled bool, role string, err error)
}

DomainJITPolicy is the per-domain just-in-time provisioning a domain verifier may offer (domainverify.Service.DomainJITPolicy).

type DomainJITStore

type DomainJITStore interface {
	GetDomain(ctx context.Context, tenantID, id shared.ID) (*verifieddomain.VerifiedDomain, error)
	ChangeJIT(ctx context.Context, tenantID, id shared.ID, enabled bool, role string) (*verifieddomain.VerifiedDomain, error)
}

DomainJITStore reads and changes a verified domain's provisioning.

type DomainOwnerLookup

type DomainOwnerLookup interface {
	OwnerOfDomain(ctx context.Context, domain string) (shared.ID, bool, error)
}

DomainOwnerLookup answers which organization holds an email domain verified for SSO (domainverify.Service.OwnerOfDomain).

type DomainVerifier

type DomainVerifier interface {
	IsVerifiedDomain(ctx context.Context, tenantID, emailDomain string) (bool, error)
}

DomainVerifier answers whether an email domain is DNS-verified for a tenant. It is the trust boundary that authorizes SSO JIT auto-provisioning: an IdP proves WHO a user is, a DNS-proven domain proves the tenant may CLAIM that domain's users.

type EmailLocaleResolver

type EmailLocaleResolver interface {
	// LocaleForEmail resolves for a recipient known by address: the
	// recipient's own language, else the organization default of tenantID
	// (when not empty), else "en".
	LocaleForEmail(ctx context.Context, recipientEmail, tenantID string) string
	// LocaleForUser is the same for a recipient known by user id.
	LocaleForUser(ctx context.Context, userID, tenantID string) string
}

EmailLocaleResolver picks the language an e-mail is written in. Both methods always return a supported locale ("en" or "vi"): a failed lookup is "en", never an error, so e-mail is never blocked on it.

type EmailService

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

EmailService handles sending emails for various application events. Supports per-tenant SMTP via TenantSMTPResolver: if a tenant has a custom email integration configured, it uses that SMTP server instead of the system default.

func NewEmailService

func NewEmailService(sender emaildom.Sender, cfg config.SMTPConfig, appName string, log *logger.Logger) *EmailService

NewEmailService creates a new EmailService.

func (*EmailService) AccountSetupURL

func (s *EmailService) AccountSetupURL(token string) string

AccountSetupURL is the UI page that consumes a one-time set-password token.

func (*EmailService) CanDeliverSystem

func (s *EmailService) CanDeliverSystem() bool

CanDeliverSystem reports whether the system SMTP sender can send mail.

func (*EmailService) CanDeliverTo

func (s *EmailService) CanDeliverTo(_ context.Context, _ string) bool

CanDeliverTo reports whether account security mail (set-password links) can be sent for tenantID: only the platform relay carries it, so this is true when the platform relay is configured, whatever the organization's own relay.

func (*EmailService) HasSystemSMTP

func (s *EmailService) HasSystemSMTP() bool

HasSystemSMTP implements SMTPAvailabilityCheck. Returns true if the system-wide SMTP sender is configured.

func (*EmailService) HasTenantSMTP

func (s *EmailService) HasTenantSMTP(_ context.Context, _ string) bool

HasTenantSMTP implements SMTPAvailabilityCheck. It is always false: verification, password reset and the other account security mail are sent through the platform relay only (an organization's relay is organization-controlled infrastructure and must never carry another organization's member's account mail), so an organization relay does not make account verification possible.

func (*EmailService) IsConfigured

func (s *EmailService) IsConfigured() bool

IsConfigured returns true if email service is properly configured.

func (*EmailService) NotifyEmailRelayStopped

func (s *EmailService) NotifyEmailRelayStopped(ctx context.Context, ownerEmail, ownerName, subject, message string)

NotifyEmailRelayStopped tells an organization owner that an e-mail channel was stopped because its mail server no longer meets the service rules. It goes through the platform relay, never the organization's.

func (*EmailService) NotifyIdentityLinked

func (s *EmailService) NotifyIdentityLinked(ctx context.Context, userEmail, userName, ipAddress, provider string)

NotifyIdentityLinked tells the user a social sign-in method was linked.

func (*EmailService) NotifyIdentityUnlinked

func (s *EmailService) NotifyIdentityUnlinked(ctx context.Context, userEmail, userName, ipAddress, provider string)

NotifyIdentityUnlinked tells the user a social sign-in method was removed.

func (*EmailService) NotifyMFADisabled

func (s *EmailService) NotifyMFADisabled(ctx context.Context, userEmail, userName, ipAddress string)

NotifyMFADisabled tells the user 2FA was turned off on their account.

func (*EmailService) NotifyOwnershipTransfer

func (s *EmailService) NotifyOwnershipTransfer(ctx context.Context, email, name, subject, message string)

NotifyOwnershipTransfer tells one of the two people in an ownership transfer what happened (requested, canceled, declined, accepted).

func (*EmailService) NotifyPasswordChanged

func (s *EmailService) NotifyPasswordChanged(ctx context.Context, userEmail, userName, ipAddress string)

NotifyPasswordChanged sends the existing password-changed email.

func (*EmailService) NotifyRecoveryCodeUsed

func (s *EmailService) NotifyRecoveryCodeUsed(ctx context.Context, userEmail, userName, ipAddress string, remaining int)

NotifyRecoveryCodeUsed tells the user a recovery code was used to sign in.

func (*EmailService) NotifySAMLCertificateExpiry

func (s *EmailService) NotifySAMLCertificateExpiry(ctx context.Context, ownerEmail, ownerName, subject, message string)

NotifySAMLCertificateExpiry tells an organization owner that the SAML identity provider's signing certificate expires soon or has expired.

func (*EmailService) NotifySSOChangePending

func (s *EmailService) NotifySSOChangePending(ctx context.Context, ownerEmail, ownerName, orgName, summary string)

NotifySSOChangePending tells an organization owner that a platform administrator proposed an SSO change that waits for their approval. summary never contains a secret.

func (*EmailService) NotifySupportAccess

func (s *EmailService) NotifySupportAccess(ctx context.Context, email, name, subject, message string)

NotifySupportAccess tells an organization owner about support access: a grant, a revocation, a support session opened or ended.

func (*EmailService) SendAccountSetupEmail

func (s *EmailService) SendAccountSetupEmail(ctx context.Context, tenantID, recipientEmail, recipientName, teamName, token string, expiresIn time.Duration) error

SendAccountSetupEmail sends the one-time set-password link for an account an administrator created. Unlike the best-effort notifications it returns an error when no sender is configured, so the caller can fall back to showing the link to the administrator instead of silently dropping it. The link is a credential: it goes through the platform relay only, never an organization relay (tenantID is only for the log line).

func (*EmailService) SendAdminInvitationEmail

func (s *EmailService) SendAdminInvitationEmail(ctx context.Context, recipientEmail, recipientName, token string, expiresIn time.Duration) error

SendAdminInvitationEmail sends a new platform administrator the one-time link where they choose their password. It uses the system sender only and returns an error when none is configured or the send fails, so the caller never reports an invitation that was not sent.

func (*EmailService) SendDomainManagedEmail

func (s *EmailService) SendDomainManagedEmail(ctx context.Context, userEmail, domain string) error

SendDomainManagedEmail tells an account that the organization which verified its email domain now manages accounts on it: the next sign-in may go through that organization's single sign-on, or new organizations may be blocked. Nothing is moved: the account's other organizations stay its own. The message names only the domain.

func (*EmailService) SendMemberReactivatedEmail

func (s *EmailService) SendMemberReactivatedEmail(
	ctx context.Context,
	recipientEmail, recipientName, teamName, actorName, tenantID string,
) error

SendMemberReactivatedEmail notifies a user that their access has been restored. Same best-effort semantics as SendMemberSuspendedEmail.

func (*EmailService) SendMemberSuspendedEmail

func (s *EmailService) SendMemberSuspendedEmail(
	ctx context.Context,
	recipientEmail, recipientName, teamName, actorName, tenantID string,
) error

SendMemberSuspendedEmail notifies a user that their tenant access has been suspended. Uses per-tenant SMTP if configured. Best-effort: returns nil and logs a warning if email is not configured for the tenant — the suspend operation should succeed even when the user can't be notified.

func (*EmailService) SendOwnershipInvitation

func (s *EmailService) SendOwnershipInvitation(ctx context.Context, email, name, organizationName string, expiresAt time.Time)

SendOwnershipInvitation tells an existing account that a platform administrator created organizationName for it and invites it to be the owner. The message links to the page where the person accepts or declines after signing in; it carries no token (the invitation is bound to the account).

func (*EmailService) SendPasswordChangedEmail

func (s *EmailService) SendPasswordChangedEmail(ctx context.Context, userEmail, userName, ipAddress string) error

SendPasswordChangedEmail sends a notification that the password was changed.

func (*EmailService) SendPasswordResetEmail

func (s *EmailService) SendPasswordResetEmail(ctx context.Context, userEmail, userName, token string, expiresIn time.Duration, ipAddress string) error

SendPasswordResetEmail sends a password reset link to a user.

func (*EmailService) SendReport

func (s *EmailService) SendReport(ctx context.Context, tenantID string, to []string, subject, htmlBody string) error

SendReport emails an already-rendered HTML report (organization content) to explicit recipients. With a tenantID it goes through the organization's own relay when one is active; if the organization chose a relay that cannot be used now, the report is NOT sent through the platform relay (the organization may have chosen its relay for data-handling reasons): the error is returned. Without an organization relay (mode off, none set) and with an empty tenantID it uses the platform relay. No-op (returns nil) when there are no recipients; errors if no SMTP sender is configured.

func (*EmailService) SendTeamInvitationEmail

func (s *EmailService) SendTeamInvitationEmail(ctx context.Context, recipientEmail, inviterName, teamName, token string, expiresIn time.Duration, tenantID ...string) error

SendTeamInvitationEmail sends a team invitation email. Uses per-tenant SMTP if configured, otherwise falls back to system SMTP.

func (*EmailService) SendVerificationEmail

func (s *EmailService) SendVerificationEmail(ctx context.Context, userEmail, userName, token string, expiresIn time.Duration) error

SendVerificationEmail sends an email verification link to a user.

func (*EmailService) SendWelcomeEmail

func (s *EmailService) SendWelcomeEmail(ctx context.Context, userEmail, userName string) error

SendWelcomeEmail sends a welcome email to a new user.

func (*EmailService) SetBranding

func (s *EmailService) SetBranding(b emaildom.Branding)

SetBranding sets the brand's email footer line and "Powered by" credit, added to every email this service sends.

func (*EmailService) SetLocaleResolver

func (s *EmailService) SetLocaleResolver(r EmailLocaleResolver)

SetLocaleResolver sets how the language of each e-mail is chosen. Without one every e-mail is English.

func (*EmailService) SetTenantSMTPResolver

func (s *EmailService) SetTenantSMTPResolver(resolver TenantSMTPResolver)

SetTenantSMTPResolver sets the per-tenant SMTP resolver.

type EntryRefusal

type EntryRefusal struct {
	Status  int
	Code    apierror.Code
	Message string
	// contains filtered or unexported fields
}

EntryRefusal is the answer of CheckEntry when an organization's entry requirements are not met. The HTTP layer renders Status, Code and Message.

func (*EntryRefusal) Error

func (e *EntryRefusal) Error() string

func (*EntryRefusal) ErrorCode

func (e *EntryRefusal) ErrorCode() string

func (*EntryRefusal) HTTPStatus

func (e *EntryRefusal) HTTPStatus() int

HTTPStatus, ErrorCode and PublicMessage let the middleware render the refusal without importing this package.

func (*EntryRefusal) PublicMessage

func (e *EntryRefusal) PublicMessage() string

func (*EntryRefusal) Unwrap

func (e *EntryRefusal) Unwrap() error

type ExchangeTokenInput

type ExchangeTokenInput struct {
	RefreshToken string `json:"refresh_token" validate:"required"`
	TenantID     string `json:"tenant_id" validate:"required"`
}

ExchangeTokenInput represents the input for token exchange.

type ExchangeTokenResult

type ExchangeTokenResult struct {
	AccessToken  string
	RefreshToken string
	TenantID     string
	TenantSlug   string
	Role         string
	ExpiresAt    time.Time
}

ExchangeTokenResult represents the result of token exchange.

RefreshToken is the NEW refresh token issued during rotation (S-3-rotate). Caller is expected to overwrite the old refresh_token cookie with this value — failing to do so means the next ExchangeToken call will fail (the old token is now marked used).

type ForgotPasswordInput

type ForgotPasswordInput struct {
	Email string `json:"email" validate:"required,email"`
}

ForgotPasswordInput represents the input for password reset request.

type ForgotPasswordResult

type ForgotPasswordResult struct {
	Token string // Reset token (should be sent via email in production)
}

ForgotPasswordResult represents the result of password reset request.

type HomeDomainOwnerLookup

type HomeDomainOwnerLookup interface {
	OwnerOfDomain(ctx context.Context, domain string) (shared.ID, bool, error)
}

HomeDomainOwnerLookup answers which organization holds an email domain verified for SSO.

type IdPCreatePayload

type IdPCreatePayload struct {
	Provider         string   `json:"provider"`
	DisplayName      string   `json:"display_name"`
	ClientID         string   `json:"client_id"`
	ClientSecretSet  bool     `json:"client_secret_set"`
	IssuerURL        string   `json:"issuer_url,omitempty"`
	TenantIdentifier string   `json:"tenant_identifier,omitempty"`
	Scopes           []string `json:"scopes,omitempty"`
	AllowedDomains   []string `json:"allowed_domains,omitempty"`
	AutoProvision    bool     `json:"auto_provision"`
	DefaultRole      string   `json:"default_role,omitempty"`
}

IdPCreatePayload is a proposed new OIDC identity provider.

type IdPMetadata

type IdPMetadata struct {
	EntityID     string
	SSOURL       string
	SSOBinding   string
	Certificates []IdPMetadataCertificate
}

IdPMetadata is the IdP side of a SAML configuration read from metadata.

func ParseIdPMetadata

func ParseIdPMetadata(raw []byte, now time.Time) (*IdPMetadata, error)

ParseIdPMetadata reads the IdP side of SAML 2.0 metadata. now decides which certificates have expired. Every refusal is a *SAMLMetadataError.

func (*IdPMetadata) CertificatesPEM

func (m *IdPMetadata) CertificatesPEM() string

CertificatesPEM joins the certificates as the SAML configuration stores them (concatenated PEM blocks).

type IdPMetadataCertificate

type IdPMetadataCertificate struct {
	PEM      string
	Subject  string
	NotAfter time.Time
	SHA256   string
}

IdPMetadataCertificate is one unexpired signing certificate of the IdP.

type IdPMetadataImportInput

type IdPMetadataImportInput struct {
	URL string
	XML string
}

IdPMetadataImportInput names the metadata source: exactly one of URL and XML.

type IdPUpdatePayload

type IdPUpdatePayload struct {
	DisplayName         *string  `json:"display_name,omitempty"`
	ClientID            *string  `json:"client_id,omitempty"`
	ClientSecretChanged bool     `json:"client_secret_changed"`
	IssuerURL           *string  `json:"issuer_url,omitempty"`
	TenantIdentifier    *string  `json:"tenant_identifier,omitempty"`
	Scopes              []string `json:"scopes,omitempty"`
	AllowedDomains      []string `json:"allowed_domains,omitempty"`
	AutoProvision       *bool    `json:"auto_provision,omitempty"`
	DefaultRole         *string  `json:"default_role,omitempty"`
	IsActive            *bool    `json:"is_active,omitempty"`
	// TargetProvider and TargetName identify the provider being changed in
	// the change summary (read at proposal time; the name is the one the
	// change sets when it renames the provider).
	TargetProvider string `json:"target_provider,omitempty"`
	TargetName     string `json:"target_name,omitempty"`
}

IdPUpdatePayload is a proposed change to an OIDC identity provider; only the set fields change.

type IdentityNotifier

type IdentityNotifier interface {
	NotifyIdentityLinked(ctx context.Context, email, name, ipAddress, provider string)
	NotifyIdentityUnlinked(ctx context.Context, email, name, ipAddress, provider string)
}

IdentityNotifier tells the account's mailbox that a sign-in method was linked or unlinked (EmailService). Sends in the background.

type IntegrationSMTPResolver

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

IntegrationSMTPResolver resolves an organization's relay from its e-mail notification integration.

func NewIntegrationSMTPResolver

func NewIntegrationSMTPResolver(repo integration.Repository, decrypt func(string) (string, error), mode RelayModeSource, domains SenderDomains, log *logger.Logger) *IntegrationSMTPResolver

NewIntegrationSMTPResolver creates the resolver. decrypt reads the integration's encrypted login; mode and domains may be nil, which turns the organization relay off (fail closed).

func (*IntegrationSMTPResolver) GetTenantSMTPConfig

func (r *IntegrationSMTPResolver) GetTenantSMTPConfig(ctx context.Context, tenantID string) (*emaildom.Config, error)

GetTenantSMTPConfig returns the relay to use for the organization's own mail. It returns (nil, nil) when none applies (mode off, no integration with org_mail): the platform relay is then the configured sender. It returns an error wrapping emaildom.ErrTenantRelayUnusable when the organization chose a relay that cannot be used now: the caller decides whether the mail may fall back to the platform relay.

type InvitationAcceptor

type InvitationAcceptor interface {
	AcceptInvitation(ctx context.Context, token string, userID shared.ID, userEmail string, actx auditapp.AuditContext) (*tenantdom.Membership, error)
}

InvitationAcceptor accepts an invitation for a signed-in user and returns the new membership (TenantService.AcceptInvitation): who may be invited, the invitee's classification, the inviter's authority now, seats, the role grant and the audit.

type InvitationLookup

type InvitationLookup interface {
	HasPendingInvitationForEmail(ctx context.Context, email string) (bool, error)
}

InvitationLookup answers whether any organization has a pending invitation for an email. Implemented by the tenant repository.

type InvitedAccount

type InvitedAccount struct {
	User *userdom.User
	// SetupToken is the raw single-use set-password token; only its hash is
	// stored. The caller delivers it to the new administrator's mailbox.
	SetupToken string
	// ExpiresAt is when the token stops working.
	ExpiresAt time.Time
}

InvitedAccount is a user account prepared for a platform administrator who has not chosen a password yet.

type JITApprovalNotifier

type JITApprovalNotifier interface {
	NotifyAdmins(ctx context.Context, tenantID shared.ID, title, body, severity string)
}

JITApprovalNotifier tells an organization's administrators that someone waits for their approval (TenantService.NotifyAdmins).

type LapsedDomainChecker

type LapsedDomainChecker interface {
	IsLapsedSSODomain(ctx context.Context, domain string) (bool, error)
}

LapsedDomainChecker reports whether an email domain was verified for SSO by an organization that lost it and nobody holds it now.

type LinkCompleteInput

type LinkCompleteInput struct {
	UserID      string
	SessionID   string
	Provider    OAuthProvider
	Code        string
	State       string
	RedirectURI string
	// BrowserBinding is the secret StartLink returned to this browser.
	BrowserBinding string
}

LinkCompleteInput finishes a link started by StartLink.

type LinkProofVerifier

type LinkProofVerifier interface {
	// LinkProofMethod is what the account must present: StepUpTOTP,
	// StepUpPassword, or "" when it has neither.
	LinkProofMethod(ctx context.Context, userID string) (StepUpMethod, error)
	// VerifyLinkProof checks proof for userID in sessionID and returns the
	// factor that was verified.
	VerifyLinkProof(ctx context.Context, actx auditapp.AuditContext, userID, sessionID string, proof StepUpProof, purpose string) (StepUpMethod, error)
}

LinkProofVerifier checks the proof for a sign-in method change (implemented by AuthService).

type LinkStartInput

type LinkStartInput struct {
	UserID      string
	SessionID   string
	Provider    OAuthProvider
	RedirectURI string
	// Proof is the code or password typed in the confirm dialog
	// (link_proof.go).
	Proof StepUpProof
}

LinkStartInput starts linking a provider to the signed-in account.

type LoginInput

type LoginInput struct {
	Email     string `json:"email" validate:"required,email"`
	Password  string `json:"password" validate:"required"`
	IPAddress string `json:"-"`
	UserAgent string `json:"-"`
}

LoginInput represents the input for login.

type LoginResult

type LoginResult struct {
	User         *userdom.User
	RefreshToken string // Global refresh token (no tenant context)
	ExpiresAt    time.Time
	SessionID    string
	Tenants      []TenantMembershipInfo // Active tenants user can access
	// SuspendedTenants lists tenants where this user has a suspended
	// membership. The user has zero access to these tenants — the field
	// exists purely so the UI can show "your access to {name} is
	// suspended" instead of bouncing the user to /onboarding/create-team
	// when they have no active memberships.
	SuspendedTenants []TenantMembershipInfo
	// MFAChallenge is set (and every other field except User is empty) when
	// the password was correct but a second step is required: no session or
	// refresh token exists yet. See VerifyMFALogin and the enrollment steps.
	MFAChallenge *MFAChallengeInfo
}

LoginResult represents the result of login. Returns a global refresh token and list of tenant memberships. Client must call ExchangeToken to get a tenant-scoped access token.

type MFAChallengeInfo

type MFAChallengeInfo struct {
	Token     string
	Purpose   mfa.Purpose
	ExpiresAt time.Time
	// Organizations names the organizations that require the second factor
	// from this user (set for enrollment challenges).
	Organizations []string
}

MFAChallengeInfo is returned by Login (inside LoginResult) when the password was right but a second step is needed. Token is shown to the client once.

type MFAFloorSource

type MFAFloorSource interface {
	Policy(ctx context.Context) (platformmfa.Policy, error)
}

MFAFloorSource gives the platform floor policy (platformmfa.Service).

type MFAPolicyHolders

type MFAPolicyHolders struct {
	// Organizations whose own settings require it (everyone, administrators,
	// personal-address or privileged outside members), by name. The person is
	// a member of each, so the names are theirs to see.
	Organizations []string `json:"organizations"`
	// Platform: the platform's two-factor floor covers the person in at least
	// one organization, during its grace period too.
	Platform bool `json:"platform"`
}

MFAPolicyHolders says who requires the person's second factor.

func (MFAPolicyHolders) Any

func (h MFAPolicyHolders) Any() bool

Any reports whether anybody requires the factor.

type MFARequiredError

type MFARequiredError struct {
	Holders MFAPolicyHolders
}

MFARequiredError refuses turning two-factor off and names who requires it.

func (*MFARequiredError) Error

func (e *MFARequiredError) Error() string

func (*MFARequiredError) Unwrap

func (e *MFARequiredError) Unwrap() error

Unwrap lets errors.Is(err, ErrMFARequiredByPolicy) match.

type MFASetup

type MFASetup struct {
	Secret     string `json:"secret"`
	OTPAuthURI string `json:"otpauth_uri"`
}

MFASetup is a freshly generated secret awaiting confirmation.

type MFAStatus

type MFAStatus struct {
	// Supported is false for federated accounts (2FA is the IdP's job).
	Supported              bool       `json:"supported"`
	Enabled                bool       `json:"enabled"`
	EnabledAt              *time.Time `json:"enabled_at,omitempty"`
	RecoveryCodesRemaining int        `json:"recovery_codes_remaining"`
	// RequiredByOrganization is true when any organization the user belongs
	// to requires 2FA.
	RequiredByOrganization bool `json:"required_by_organization"`
	// GraceDueAt is set while the platform's two-factor floor covers the
	// user but their grace period has not ended: the date from which they
	// are gated at sign-in. They can set up 2FA now; creating credentials
	// already needs it.
	GraceDueAt *time.Time `json:"grace_due_at,omitempty"`
	// RequiredBy names who requires the factor (organizations by name, the
	// platform floor), in force or still in its grace period.
	RequiredBy MFAPolicyHolders `json:"required_by"`
	// CanTurnOff is false while anybody requires the factor or that could not
	// be read: POST /users/me/2fa/disable would refuse.
	CanTurnOff bool `json:"can_turn_off"`
}

MFAStatus describes a user's 2FA state for their account page.

type MemoryPKCEStore

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

MemoryPKCEStore is an in-process PKCEVerifierStore. It is correct only for a single API replica; production wires the Redis store.

func NewMemoryPKCEStore

func NewMemoryPKCEStore() *MemoryPKCEStore

NewMemoryPKCEStore creates an empty in-process store.

func (*MemoryPKCEStore) GetDel

func (m *MemoryPKCEStore) GetDel(_ context.Context, key string) (string, bool, error)

GetDel returns and removes the verifier stored under key.

func (*MemoryPKCEStore) Set

func (m *MemoryPKCEStore) Set(_ context.Context, key, verifier string, ttl time.Duration) error

Set stores verifier under key until ttl elapses.

type OAuthProvider

type OAuthProvider string

OAuthProvider represents a supported OAuth provider.

const (
	OAuthProviderGoogle    OAuthProvider = "google"
	OAuthProviderGitHub    OAuthProvider = "github"
	OAuthProviderMicrosoft OAuthProvider = "microsoft"
)

func (OAuthProvider) IsValid

func (p OAuthProvider) IsValid() bool

IsValid checks if the provider is valid.

func (OAuthProvider) ToAuthProvider

func (p OAuthProvider) ToAuthProvider() userdom.AuthProvider

ToAuthProvider converts OAuthProvider to userdom.AuthProvider.

type OAuthService

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

OAuthService handles OAuth authentication.

func NewOAuthService

func NewOAuthService(
	userRepo userdom.Repository,
	sessionRepo sessiondom.Repository,
	refreshTokenRepo sessiondom.RefreshTokenRepository,
	oauthCfg config.OAuthConfig,
	authCfg config.AuthConfig,
	log *logger.Logger,
) *OAuthService

NewOAuthService creates a new OAuthService.

func (s *OAuthService) CancelPendingLink(ctx context.Context, userID, token string)

CancelPendingLink drops a pending link ("not now"). Always succeeds.

func (s *OAuthService) CompleteLink(ctx context.Context, in LinkCompleteInput) (*SignInMethod, error)

CompleteLink binds the provider identity to the signed-in account. The state must be a link state minted for this account and this session.

func (s *OAuthService) ConfirmPendingLink(ctx context.Context, in ConfirmPendingLinkInput) (*SignInMethod, error)

ConfirmPendingLink links the pending provider identity to the signed-in account. It needs the proof typed in the confirm dialog, checked before the pending link is taken (a mistyped code leaves it for another try), and a session that authenticated after the pending link was made.

func (s *OAuthService) DescribePendingLink(ctx context.Context, userID, token string) (*PendingLinkInfo, error)

DescribePendingLink tells the signed-in account which provider account is waiting to be linked to it. It does not spend the pending link, except when another account presents it.

func (*OAuthService) GetAuthorizationURL

func (s *OAuthService) GetAuthorizationURL(ctx context.Context, input AuthorizationURLInput) (*AuthorizationURLResult, error)

GetAuthorizationURL returns the OAuth authorization URL for the specified provider.

func (*OAuthService) GetAvailableProviders

func (s *OAuthService) GetAvailableProviders() []ProviderInfo

GetAvailableProviders returns a list of available OAuth providers.

func (*OAuthService) HandleCallback

func (s *OAuthService) HandleCallback(ctx context.Context, input CallbackInput) (*CallbackResult, error)

HandleCallback handles the OAuth callback.

func (*OAuthService) ListSignInMethods

func (s *OAuthService) ListSignInMethods(ctx context.Context, userID string) (*SignInMethods, error)

ListSignInMethods returns the account's sign-in methods. Only the caller's own account is ever read (userID comes from the session).

func (*OAuthService) SetAuditService

func (s *OAuthService) SetAuditService(a *auditapp.AuditService)

SetSignupPolicy wires the platform sign-up policy (the console setting). SetAuditService wires the auth.login event for social sign-ins.

func (*OAuthService) SetBreakGlassGate

func (s *OAuthService) SetBreakGlassGate(g BreakGlassGate)

SetBreakGlassGate wires the same refusal on the social sign-in path.

func (*OAuthService) SetClaimGuard

func (s *OAuthService) SetClaimGuard(members ClaimMembershipSource, domains DomainVerifier)

SetClaimGuard wires the check that runs before a social sign-in adopts a claimable account (local, no password yet). Without it no such account is adopted (fail-closed).

func (*OAuthService) SetIdentityNotifier

func (s *OAuthService) SetIdentityNotifier(n IdentityNotifier)

SetIdentityNotifier wires the link and unlink e-mails.

func (*OAuthService) SetIdentityRepo

func (s *OAuthService) SetIdentityRepo(repo useridentity.Repository)

SetIdentityRepo wires the federated identity store.

func (*OAuthService) SetInvitationLookup

func (s *OAuthService) SetInvitationLookup(l InvitationLookup)

SetInvitationLookup wires the pending-invitation check.

func (*OAuthService) SetLinkProofVerifier

func (s *OAuthService) SetLinkProofVerifier(v LinkProofVerifier)

SetLinkProofVerifier wires the proof every link and unlink needs (link_proof.go). Without it every link and unlink is refused.

func (*OAuthService) SetPKCEStore

func (s *OAuthService) SetPKCEStore(store PKCEVerifierStore)

SetPKCEStore replaces the PKCE verifier store. Production wires the Redis store so a login started on one replica can finish on another; the default is in-process.

func (*OAuthService) SetProviderSource

func (s *OAuthService) SetProviderSource(src ProviderSource)

SetProviderSource makes the providers live: they are read from src on every authorize and callback instead of the start-up configuration.

func (*OAuthService) SetSecondFactorGate

func (s *OAuthService) SetSecondFactorGate(g SecondFactorGate)

SetSecondFactorGate wires the second step for linked password accounts. Without it a password account is never signed in through a provider.

func (*OAuthService) SetSessionRevoker

func (s *OAuthService) SetSessionRevoker(r SessionRevoker)

SetSessionRevoker wires the session revocation every link and unlink needs: the account's other sessions end. Without it CompleteLink and Unlink are refused.

func (*OAuthService) SetSignInHook

func (s *OAuthService) SetSignInHook(h SignInHook)

SetSignInHook wires the hook run after a social sign-in.

func (*OAuthService) SetSignupDomainPolicy

func (s *OAuthService) SetSignupDomainPolicy(src signupdom.DomainPolicySource)

SetSignupDomainPolicy wires the per-domain sign-up policy of claimed domains.

func (*OAuthService) SetSignupPolicy

func (s *OAuthService) SetSignupPolicy(p signupdom.PolicySource)

func (*OAuthService) SetSignupRecorder

func (s *OAuthService) SetSignupRecorder(r signupevent.Recorder)

SetSignupRecorder wires the sign-up event recorder.

StartLink returns the provider's authorization URL for a link after checking the proof typed for it. The factor is kept with the link's PKCE verifier, so CompleteLink audits it and refuses a link whose start was never proved.

func (s *OAuthService) Unlink(ctx context.Context, in UnlinkInput) error

Unlink removes a social identity from the signed-in account after checking the proof typed for it. The account's last sign-in method is never removed.

type OAuthUserInfo

type OAuthUserInfo struct {
	ID        string
	Email     string
	Name      string
	AvatarURL string
	// Issuer + Subject are the provider's immutable user id: from the verified
	// id_token for Microsoft (keyed on oid), from the provider API for Google
	// (sub) and GitHub (numeric id). The account is found by this pair first;
	// the email is a mutable attribute (federated_identity.go).
	Issuer  string
	Subject string
	// HD is the Google Workspace (hosted) domain claim of the id_token; empty
	// for a consumer Google account.
	HD string
	// LegacySubject is the subject the identity was bound under before
	// (Microsoft: sub); a binding found under it is re-keyed to Subject.
	LegacySubject string
	// Login is the provider account's handle where it has one (GitHub);
	// empty otherwise. Shown when the person confirms a pending link.
	Login string
}

OAuthUserInfo represents user information from OAuth provider.

type PKCEVerifierStore

type PKCEVerifierStore interface {
	Set(ctx context.Context, key, verifier string, ttl time.Duration) error
	GetDel(ctx context.Context, key string) (verifier string, ok bool, err error)
}

PKCEVerifierStore keeps an OAuth PKCE code_verifier on the server between the authorize redirect and the callback, keyed by the state it was issued with. GetDel is single use: it returns and deletes the entry, so a state (and its verifier) can complete at most one login.

The verifier must never travel in the state: the state goes through the browser, the identity provider and any log or Referer on the way, so whoever intercepts the authorization code would hold the verifier as well and PKCE would protect nothing.

The method set matches internal/infra/redis.Client, which production wires directly (keys carry a TTL and GETDEL is atomic across replicas).

type PendingLinkError

type PendingLinkError struct {
	// Token is the secret of the pending link. Only its hash is stored.
	Token    string
	Provider OAuthProvider
}

PendingLinkError is ErrOAuthAccountExists with a pending link the web server keeps for the browser (an HttpOnly cookie). errors.Is(err, ErrOAuthAccountExists) holds.

func (*PendingLinkError) Error

func (e *PendingLinkError) Error() string

func (*PendingLinkError) Unwrap

func (e *PendingLinkError) Unwrap() error

Unwrap makes errors.Is(err, ErrOAuthAccountExists) hold.

type PendingLinkInfo

type PendingLinkInfo struct {
	Provider string `json:"provider"`
	// Email is the provider account's address (the account's own address:
	// the pending link was made because they are the same).
	Email string `json:"email"`
	// Login is the provider account's handle (GitHub), Name its display name
	// and AvatarURL its picture (an https URL on a known avatar host, or
	// empty): what the person checks before confirming. Display only.
	Login     string    `json:"login,omitempty"`
	Name      string    `json:"name,omitempty"`
	AvatarURL string    `json:"avatar_url,omitempty"`
	ExpiresAt time.Time `json:"expires_at"`
	// Proof is what confirming asks for: totp, password, or "" when the
	// account has neither (it must turn on two-factor authentication first).
	Proof string `json:"proof"`
}

PendingLinkInfo describes a pending link to the account it was made for.

type PrivilegeSource

type PrivilegeSource interface {
	GetUserPermissions(ctx context.Context, tenantID, userID string) ([]string, error)
	HasFullDataAccess(ctx context.Context, tenantID, userID string) (bool, error)
}

PrivilegeSource tells what a member can do in an organization through all grants (accesscontrol.RoleService).

type ProviderInfo

type ProviderInfo struct {
	ID      string `json:"id"`
	Name    string `json:"name"`
	Enabled bool   `json:"enabled"`
}

ProviderInfo represents information about an OAuth provider.

type ProviderSource

type ProviderSource interface {
	OAuthProvider(ctx context.Context, provider string) config.OAuthProviderConfig
}

ProviderSource answers which configuration a social provider has right now. Implemented by the console's social login setting.

type RefreshSessionIdentity

type RefreshSessionIdentity struct {
	User       *userdom.User
	AuthMethod sessiondom.AuthMethod
	SessionID  shared.ID
}

RefreshSessionIdentity is the signed-in user behind a refresh token and how that session was authenticated.

type RefreshTokenInput

type RefreshTokenInput struct {
	RefreshToken string `json:"refresh_token" validate:"required"`
	TenantID     string `json:"tenant_id" validate:"required"`
	IPAddress    string `json:"-"`
	UserAgent    string `json:"-"`
}

RefreshTokenInput represents the input for token refresh. Requires tenant_id to generate tenant-scoped access token.

type RefreshTokenResult

type RefreshTokenResult struct {
	AccessToken      string    // Tenant-scoped access token
	RefreshToken     string    // New global refresh token (rotated)
	TenantID         string    // Tenant ID the access token is scoped to
	TenantSlug       string    // Tenant slug
	Role             string    // User's role in this tenant
	ExpiresAt        time.Time // Access token expiration
	RefreshExpiresAt time.Time // Refresh token expiration (for cookie)
}

RefreshTokenResult represents the result of token refresh. Returns a new global refresh token and tenant-scoped access token.

type RegisterInput

type RegisterInput struct {
	Email    string `json:"email" validate:"required,email,max=255"`
	Password string `json:"password" validate:"required,min=8,max=128"`
	Name     string `json:"name" validate:"required,max=255"`
	// InvitationToken is optional: when a user registers via an
	// invitation link, the client passes the token here so the register
	// flow can resolve the target tenant and apply that tenant's email
	// verification rule (instead of the platform default). The token
	// itself is NOT consumed here — invitation acceptance still happens
	// in a separate POST /invitations/{token}/accept call.
	InvitationToken string `json:"invitation_token,omitempty"`
}

RegisterInput represents the input for user registration.

type RegisterResult

type RegisterResult struct {
	User                 *userdom.User
	VerificationToken    string // Only returned if email verification is required
	RequiresVerification bool
	EmailExisted         bool // Set to true if email already exists (for anti-enumeration)
	// ExistingUnverified: the email belongs to a password account that never
	// verified its address. The caller emails that address a set-password
	// link (forgot-password), which verifies the address and replaces any
	// password chosen before, so whoever registered first cannot keep the
	// account (pre-hijacking). Never set for a new email.
	ExistingUnverified bool
}

RegisterResult represents the result of registration.

type RelayModeSource

type RelayModeSource interface {
	RelayMode(ctx context.Context) emaildom.RelayMode
}

RelayModeSource is the platform setting email.tenant_relay.

type RepoEmailLocaleResolver

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

RepoEmailLocaleResolver resolves from the user and tenant repositories.

Tenant safety: the organization default is read only for the tenant id the e-mail is already being sent for. The address is looked up only among accounts (an account is global, one address is one account); it is never used to search organizations.

func NewRepoEmailLocaleResolver

func NewRepoEmailLocaleResolver(users localeUserReader, tenants localeTenantReader, log *logger.Logger) *RepoEmailLocaleResolver

NewRepoEmailLocaleResolver builds the resolver. Either repository may be nil.

func (*RepoEmailLocaleResolver) LocaleForEmail

func (r *RepoEmailLocaleResolver) LocaleForEmail(ctx context.Context, recipientEmail, tenantID string) string

LocaleForEmail implements EmailLocaleResolver.

func (*RepoEmailLocaleResolver) LocaleForUser

func (r *RepoEmailLocaleResolver) LocaleForUser(ctx context.Context, userID, tenantID string) string

LocaleForUser implements EmailLocaleResolver.

type ResendVerificationResult

type ResendVerificationResult struct {
	Token    string
	UserName string
}

ResendVerificationResult is a fresh verification token to email. A nil result means nothing is to be sent; callers answer the same either way, so the response never says whether the address has an account.

type ResetPasswordInput

type ResetPasswordInput struct {
	// RevokeAPIKeys also revokes every API key the person owns, in every
	// organization. Connected applications (MCP grants) are always revoked.
	RevokeAPIKeys bool   `json:"-"`
	Token         string `json:"token" validate:"required"`
	NewPassword   string `json:"new_password" validate:"required,min=8,max=128"`
	IPAddress     string `json:"-"`
	UserAgent     string `json:"-"`
}

ResetPasswordInput represents the input for password reset.

type SAMLCertExpiryMailer

type SAMLCertExpiryMailer interface {
	NotifySAMLCertificateExpiry(ctx context.Context, ownerEmail, ownerName, subject, message string)
}

SAMLCertExpiryMailer emails an owner about an expiring IdP certificate.

type SAMLCertOwners

type SAMLCertOwners interface {
	ListActiveOwners(ctx context.Context, tenantID shared.ID) ([]ssochange.OwnerContact, error)
}

SAMLCertOwners lists an organization's active owners.

type SAMLChangePayload

type SAMLChangePayload struct {
	IDPEntityID    string   `json:"idp_entity_id"`
	IDPSSOURL      string   `json:"idp_sso_url"`
	IDPCertificate string   `json:"idp_certificate"`
	AllowedDomains []string `json:"allowed_domains"`
	DefaultRole    string   `json:"default_role"`
	AutoProvision  bool     `json:"auto_provision"`
	Enabled        bool     `json:"enabled"`
}

SAMLChangePayload is a proposed SAML configuration.

type SAMLConfigInput

type SAMLConfigInput struct {
	IDPEntityID    string
	IDPSSOURL      string
	IDPCertificate string // PEM
	AllowedDomains []string
	DefaultRole    string
	AutoProvision  bool
	Enabled        bool
}

SAMLConfigInput is an admin create/update of a tenant's SAML config.

type SAMLMetadataError

type SAMLMetadataError struct{ Reason string }

SAMLMetadataError refuses an IdP metadata import. Reason is one of the SAMLMetadataReason codes; the error never carries the document or the URL.

func (*SAMLMetadataError) Error

func (e *SAMLMetadataError) Error() string

func (*SAMLMetadataError) Unwrap

func (e *SAMLMetadataError) Unwrap() error

Unwrap makes every refusal a validation error, except an unreachable URL.

type SAMLReplayStore

type SAMLReplayStore interface {
	SetNX(ctx context.Context, key, value string, ttl time.Duration) (bool, error)
}

SAMLReplayStore records an assertion ID once. SetNX reports true only for the first caller; the Redis client satisfies it.

type SAMLService

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

SAMLService implements the SAML 2.0 Service Provider flow (RFC-009 9d/9e). Phase 9d (this iteration): per-tenant config + SP metadata + the federated-login seam (via SSOService.CompleteFederatedLogin). The login/ACS flow (9e) builds on buildServiceProvider + the stored IdP certificate.

The SP URLs (entity id / ACS / metadata) are derived from the request host so they always match the deployment.

func NewSAMLService

func NewSAMLService(repo samldom.Repository, tenantRepo tenantdom.Repository, sso *SSOService, log *logger.Logger) *SAMLService

NewSAMLService wires the service. sso supplies the shared session/provisioning tail (CompleteFederatedLogin).

func (*SAMLService) ACS

func (s *SAMLService) ACS(ctx context.Context, orgSlug, baseURL string, r *http.Request, possibleRequestIDs []string,
	forcedAuthn bool) (*SSOCallbackResult, error)

ACS validates an IdP SAML response and completes the federated login. The caller supplies possibleRequestIDs (from the request-tracking cookie) so the assertion's InResponseTo is bound to a request this SP actually initiated.

forcedAuthn says the request asked for ForceAuthn: an assertion whose AuthnInstant is older than a few minutes is then refused.

func (*SAMLService) BuildConfig

func (s *SAMLService) BuildConfig(ctx context.Context, tenantID shared.ID, in SAMLConfigInput) (*samldom.SAMLProvider, error)

BuildConfig validates in and returns the SAML config it describes, keeping the id of the tenant's existing config, without storing it. An SSO change that waits for an owner's approval is validated with it when submitted and rebuilt with it when approved.

func (*SAMLService) DeleteConfig

func (s *SAMLService) DeleteConfig(ctx context.Context, tenantID shared.ID) error

DeleteConfig removes the tenant's SAML config.

func (*SAMLService) GetConfig

func (s *SAMLService) GetConfig(ctx context.Context, tenantID shared.ID) (*samldom.SAMLProvider, error)

GetConfig returns the tenant's SAML config (samldom.ErrNotFound when absent).

func (*SAMLService) ImportIdPMetadata

func (s *SAMLService) ImportIdPMetadata(ctx context.Context, in IdPMetadataImportInput) (*IdPMetadata, error)

ImportIdPMetadata reads the IdP side of a SAML configuration from the IdP's metadata URL or an uploaded metadata document. It stores nothing.

func (*SAMLService) Login

func (s *SAMLService) Login(ctx context.Context, orgSlug, baseURL string, forceAuthn bool) (redirectURL, requestID string, err error)

Login starts an SP-initiated SAML login (RFC-009 9e). It returns the IdP redirect URL (carrying the deflate+base64 AuthnRequest) and the request ID, which the caller stores in a short-lived cookie so the ACS can bind the response's InResponseTo (replay/CSRF protection).

forceAuthn asks the IdP to authenticate the user again (step-up re-authentication); the ACS then refuses an assertion whose AuthnInstant is not fresh.

func (*SAMLService) Metadata

func (s *SAMLService) Metadata(_ context.Context, orgSlug, baseURL string) (string, error)

Metadata returns the SP metadata XML for a tenant (org slug), which the admin registers with their IdP. baseURL is the deployment origin (scheme://host).

The metadata is built from the slug and the deployment URL only, so it is served for any well-formed slug, known or not: answering 404 for an unknown organization would tell an unauthenticated caller which organizations exist.

func (*SAMLService) SPMetadataForTenant

func (s *SAMLService) SPMetadataForTenant(ctx context.Context, tenantID shared.ID, baseURL string) (xmlDoc, slug string, err error)

SPMetadataForTenant returns the SP metadata XML of an organization (by id) and its slug, built on the configured public origin. It is the platform admin console's download of the file to upload in the IdP's SAML application; the public metadata URL serves the same document.

func (*SAMLService) SetCertExpiryAlerts

func (s *SAMLService) SetCertExpiryAlerts(store samldom.CertificateExpiryStore, owners SAMLCertOwners, inApp SSOChangeInAppNotifier)

SetCertExpiryAlerts wires the certificate-expiry sweep: the store it reads and marks, the owner list and the in-app notifier.

func (*SAMLService) SetCertExpiryMailer

func (s *SAMLService) SetCertExpiryMailer(m SAMLCertExpiryMailer)

SetCertExpiryMailer also emails the owners (system SMTP).

func (*SAMLService) SetReplayStore

func (s *SAMLService) SetReplayStore(store SAMLReplayStore)

SetReplayStore wires the shared store (Redis) that refuses a second use of an assertion across every API replica. Without it the service keeps the IDs in process, which protects a single replica only.

func (*SAMLService) SweepCertificateExpiry

func (s *SAMLService) SweepCertificateExpiry(ctx context.Context, now time.Time) (int, error)

SweepCertificateExpiry alerts the owners of every organization whose enabled SAML IdP certificate reaches a new notice level (30, 7, 1 days, expired), once per level per certificate. It returns how many organizations were alerted. Without the alerts wired it does nothing.

func (*SAMLService) UpsertConfig

func (s *SAMLService) UpsertConfig(ctx context.Context, tenantID shared.ID, in SAMLConfigInput) (*samldom.SAMLProvider, error)

UpsertConfig validates and stores the tenant's SAML config.

type SMTPAvailabilityCheck

type SMTPAvailabilityCheck interface {
	// HasSystemSMTP returns true if the platform has system-wide SMTP configured.
	HasSystemSMTP() bool
	// HasTenantSMTP returns true if the given tenant has a custom SMTP integration.
	// tenantID may be empty for self-registration (no tenant context yet).
	HasTenantSMTP(ctx context.Context, tenantID string) bool
}

SMTPAvailabilityCheck reports whether outbound email is available, either via the system SMTP config or for a specific tenant. Used by smart email verification to skip verification when no email channel exists.

type SSOAuthorizeInput

type SSOAuthorizeInput struct {
	OrgSlug     string
	Provider    string
	RedirectURI string // Frontend callback URL
	// ForceReauth asks the provider to authenticate the user again (step-up
	// re-authentication): prompt=login and max_age=0, and the callback
	// refuses an id_token whose auth_time is not fresh.
	ForceReauth bool
}

SSOAuthorizeInput is the input for generating an SSO authorization URL.

type SSOAuthorizeResult

type SSOAuthorizeResult struct {
	AuthorizationURL string `json:"authorization_url"`
	State            string `json:"state"`
	// BrowserBinding is a one-time secret for the browser that started the
	// flow. The caller keeps it in an HttpOnly cookie and sends it back with
	// the callback; the API refuses a callback without it. Never log it.
	BrowserBinding string `json:"browser_binding"`
}

SSOAuthorizeResult is the result of generating an SSO authorization URL.

type SSOCallbackInput

type SSOCallbackInput struct {
	Provider    string
	Code        string
	State       string
	RedirectURI string
	// BrowserBinding is the secret returned by the authorize call to the
	// browser that started this flow.
	BrowserBinding string
}

SSOCallbackInput is the input for handling an SSO callback.

type SSOCallbackResult

type SSOCallbackResult struct {
	AccessToken  string        `json:"access_token"`
	RefreshToken string        `json:"refresh_token"`
	ExpiresIn    int64         `json:"expires_in"`
	TokenType    string        `json:"token_type"`
	User         *userdom.User `json:"user"`
	TenantID     string        `json:"tenant_id"`
	TenantSlug   string        `json:"tenant_slug"`
}

SSOCallbackResult is the result of a successful SSO callback.

type SSOChangeInAppNotifier

type SSOChangeInAppNotifier interface {
	Notify(ctx context.Context, params notificationdom.NotificationParams) error
}

SSOChangeInAppNotifier delivers an in-app notification.

type SSOChangeMailer

type SSOChangeMailer interface {
	NotifySSOChangePending(ctx context.Context, ownerEmail, ownerName, orgName, summary string)
}

SSOChangeMailer emails an owner about a change that waits for them.

type SSOChangeOwners

type SSOChangeOwners interface {
	OwnerPresence(ctx context.Context, tenantID shared.ID) (tenantdom.OwnerPresence, error)
	ListActiveOwners(ctx context.Context, tenantID shared.ID) ([]ssochange.OwnerContact, error)
	IsActiveOwner(ctx context.Context, tenantID, userID shared.ID) (bool, error)
}

SSOChangeOwners answers who owns an organization.

type SSOChangeRequester

type SSOChangeRequester struct {
	AdminID shared.ID
	Email   string
}

SSOChangeRequester is the platform administrator submitting a change.

type SSOChangeResult

type SSOChangeResult struct {
	Applied bool
	Change  *ssochange.Change
}

SSOChangeResult is the outcome of a submission: either applied directly (organization without an owner) or stored as a pending change.

type SSOChangeService

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

SSOChangeService stores, lists and decides pending SSO changes.

func NewSSOChangeService

func NewSSOChangeService(repo ssochange.Repository, saml *SAMLService, sso *SSOService, owners SSOChangeOwners, tenants tenantdom.Repository, log *logger.Logger) *SSOChangeService

NewSSOChangeService wires the service.

func (*SSOChangeService) Approve

func (s *SSOChangeService) Approve(ctx context.Context, tenantID, changeID, approverID shared.ID) (*ssochange.Change, error)

Approve applies a pending change. approverID must be an active owner of the organization (checked in the database, not taken from the caller's token). The change and the live write commit together.

func (*SSOChangeService) List

func (s *SSOChangeService) List(ctx context.Context, tenantID shared.ID, pendingOnly bool) ([]*ssochange.Change, error)

List returns the organization's SSO changes, newest first.

func (*SSOChangeService) Reject

func (s *SSOChangeService) Reject(ctx context.Context, tenantID, changeID, approverID shared.ID) (*ssochange.Change, error)

Reject discards a pending change.

func (*SSOChangeService) SetDomainJITStore

func (s *SSOChangeService) SetDomainJITStore(d DomainJITStore)

SetDomainJITStore wires the verified domains (domainverify.Service).

func (*SSOChangeService) SetMailer

func (s *SSOChangeService) SetMailer(m SSOChangeMailer)

SetMailer emails the owners (system SMTP).

func (*SSOChangeService) SetNotificationService

func (s *SSOChangeService) SetNotificationService(n SSOChangeInAppNotifier)

SetNotificationService delivers the in-app notification to the owners.

func (*SSOChangeService) SubmitCreateProvider

SubmitCreateProvider proposes a new OIDC identity provider.

func (*SSOChangeService) SubmitDomainJIT

func (s *SSOChangeService) SubmitDomainJIT(ctx context.Context, tenantID, id shared.ID, enabled bool, role string, by SSOChangeRequester) (*SSOChangeResult, *verifieddomain.VerifiedDomain, error)

SubmitDomainJIT changes a domain's provisioning: directly when it lowers it (or the organization has no owner yet), otherwise as a pending change for an owner.

func (*SSOChangeService) SubmitSAML

SubmitSAML proposes the organization's SAML configuration.

func (*SSOChangeService) SubmitUpdateProvider

SubmitUpdateProvider proposes a change to an OIDC identity provider.

type SSOLink struct {
	IdentityID string    `json:"identity_id"`
	OrgSlug    string    `json:"org_slug"`
	Provider   string    `json:"provider"`
	CreatedAt  time.Time `json:"created_at"`
}

SSOLink is an organization sign-in linked to the account.

type SSOLinkCompleteInput

type SSOLinkCompleteInput struct {
	UserID    string
	SessionID string
	Provider  string
	Code      string
	State     string
	// BrowserBinding is the secret StartSSOLink returned to this browser.
	BrowserBinding string
}

SSOLinkCompleteInput finishes a link started by StartSSOLink.

type SSOLinkOrganization

type SSOLinkOrganization struct {
	OrgSlug     string `json:"org_slug"`
	OrgName     string `json:"org_name"`
	Provider    string `json:"provider"`
	DisplayName string `json:"display_name"`
	// Identity is the account's identity at this provider, nil when the
	// organization's sign-in is not linked.
	Identity *SSOLinkedIdentity `json:"identity,omitempty"`
}

SSOLinkOrganization is one organization of the account with single sign-on, for Account > Security.

type SSOLinkStartInput

type SSOLinkStartInput struct {
	UserID      string
	SessionID   string
	OrgSlug     string
	Provider    string
	RedirectURI string
	// Proof is the code or password typed in the confirm dialog.
	Proof StepUpProof
}

SSOLinkStartInput starts linking an organization's sign-in to the signed-in account.

type SSOLinkedIdentity

type SSOLinkedIdentity struct {
	ID         string     `json:"id"`
	CreatedAt  time.Time  `json:"created_at"`
	LastUsedAt *time.Time `json:"last_used_at,omitempty"`
	// Unlinkable: the person may remove it here (an OIDC identity of an
	// account with a password, which keeps a way to sign in).
	Unlinkable bool `json:"unlinkable"`
}

SSOLinkedIdentity is an organization sign-in identity of the account.

type SSOLinks struct {
	Organizations []SSOLinkOrganization `json:"organizations"`
	// Other: organization sign-in identities not matched to an organization
	// listed above (a former organization, or SAML).
	Other []SSOLinkedIdentity `json:"other"`
	// Proof is what a link or unlink asks for: totp, password, or "" when
	// the account must turn on two-factor authentication first.
	Proof string `json:"proof"`
}

SSOLinks is the account's organization sign-in, for Account > Security.

type SSOProviderInfo

type SSOProviderInfo struct {
	ID          string `json:"id"`
	Provider    string `json:"provider"`
	DisplayName string `json:"display_name"`
}

SSOProviderInfo represents a public SSO provider for a tenant.

type SSOService

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

SSOService handles per-tenant SSO authentication.

func NewSSOService

func NewSSOService(
	ipRepo identityproviderdom.Repository,
	tenantRepo tenantdom.Repository,
	userRepo userdom.Repository,
	sessionRepo sessiondom.Repository,
	refreshTokenRepo sessiondom.RefreshTokenRepository,
	encryptor crypto.Encryptor,
	authCfg config.AuthConfig,
	log *logger.Logger,
) *SSOService

NewSSOService creates a new SSOService.

func (*SSOService) BackChannelLogout

func (s *SSOService) BackChannelLogout(ctx context.Context, logoutToken string) (int, error)

BackChannelLogout validates an OIDC Back-Channel Logout 1.0 logout_token and revokes the session(s) it targets. It is the security-critical entry point: a forged token must NEVER revoke a session. Validation order (all fail-closed):

  1. Read `iss` WITHOUT trusting the token.
  2. Resolve `iss` to a configured provider → its JWKS + acceptable client_ids. No configured provider for this issuer ⇒ reject (nothing to revoke).
  3. Verify the signature against that provider's JWKS, and that `aud` equals one of the provider's client_ids.
  4. Enforce logout-token claim rules: `iss` matches, NO `nonce`, `events` contains the back-channel-logout member, `sid` and/or `sub` present, `iat` present + recent, `exp` (if present) validated by the parser.
  5. Revoke matching sessions — issuer-scoped, so a token from provider X can only revoke sessions bound to X's issuer (no cross-provider revocation).

Returns the number of sessions revoked (0 is a success — an unknown sid must not leak via the response). Any validation failure returns ErrLogoutTokenInvalid.

func (*SSOService) BuildProvider

BuildProvider validates input and returns the identity provider it describes (client secret encrypted), without storing it.

func (*SSOService) BuildProviderUpdate

BuildProviderUpdate validates input and returns the tenant's identity provider with the update applied, without storing it.

func (*SSOService) CompleteFederatedLogin

func (s *SSOService) CompleteFederatedLogin(ctx context.Context, t *tenantdom.Tenant, email, name, defaultRole string, autoProvision bool) (*SSOCallbackResult, error)

CompleteFederatedLogin issues an OpenCTEM session for an externally authenticated identity (e.g. a validated SAML assertion). It finds-or-creates a claimable passwordless user, blocks takeover of password-backed local accounts, auto-provisions tenant membership when requested, and creates the session. Reused by the SAML SP flow so it shares the SSO session machinery.

func (s *SSOService) CompleteSSOLink(ctx context.Context, in SSOLinkCompleteInput) (*SSOLink, error)

CompleteSSOLink verifies the identity provider's answer and binds the identity to the account that started the link.

func (*SSOService) CreateProvider

CreateProvider creates a new identity provider configuration for a tenant.

func (*SSOService) DeleteProvider

func (s *SSOService) DeleteProvider(ctx context.Context, tenantID, id string) error

DeleteProvider deletes an identity provider configuration.

func (*SSOService) Discover

func (s *SSOService) Discover(ctx context.Context, email string) DiscoverResult

Discover answers where an email signs in. It never fails: any error or unknown domain answers "password". The same lookups run whatever the email, so the answer's latency does not depend on whether the domain is claimed.

func (*SSOService) GenerateAuthorizeURL

func (s *SSOService) GenerateAuthorizeURL(ctx context.Context, input SSOAuthorizeInput) (*SSOAuthorizeResult, error)

GenerateAuthorizeURL builds the OAuth authorization URL for a tenant's SSO provider.

func (*SSOService) GetProvider

func (s *SSOService) GetProvider(ctx context.Context, tenantID, id string) (*identityproviderdom.IdentityProvider, error)

GetProvider retrieves a provider configuration by ID.

func (*SSOService) GetProviderByType

func (s *SSOService) GetProviderByType(ctx context.Context, tenantID, provider string) (*identityproviderdom.IdentityProvider, error)

GetProviderByType returns the tenant's identity provider of one type (a tenant has at most one per type).

func (*SSOService) GetProvidersForTenant

func (s *SSOService) GetProvidersForTenant(ctx context.Context, orgSlug string) ([]SSOProviderInfo, error)

GetProvidersForTenant returns active SSO providers for a tenant identified by slug.

SECURITY (anti-enumeration): an unknown slug answers exactly like an organization without SSO, an empty list and no error, so the public providers endpoint does not tell whether an organization exists. The same provider query runs for an unknown slug (on a random id that matches nothing), so both answers cost the same.

func (*SSOService) HandleCallback

func (s *SSOService) HandleCallback(ctx context.Context, input SSOCallbackInput) (*SSOCallbackResult, error)

HandleCallback handles the SSO OAuth callback.

func (*SSOService) HasUsableSSOPath

func (s *SSOService) HasUsableSSOPath(ctx context.Context, orgSlug string) (bool, error)

HasUsableSSOPath reports whether the tenant has at least one way for members to sign in via SSO — an active per-tenant identity provider or the opted-in platform env fallback. It reuses the exact resolution the login page uses (GetProvidersForTenant), so "can enforce" matches "can actually sign in". Consumed by TenantService.UpdateSecuritySettings to gate enabling sso_enforced.

Note: this covers OIDC/OAuth identity providers + env fallback. SAML-only tenants are not yet counted here (follow-up); the owner break-glass at the enforcement gate still prevents any permanent lock-out.

func (*SSOService) ListProviders

func (s *SSOService) ListProviders(ctx context.Context, tenantID string) ([]*identityproviderdom.IdentityProvider, error)

ListProviders lists all identity provider configurations for a tenant.

func (s *SSOService) ListSSOLinks(ctx context.Context, userID string) (*SSOLinks, error)

ListSSOLinks lists the organizations of userID that have an OIDC single sign-on, with the account's identity at each. Only the caller's own account and its own active memberships are read.

func (*SSOService) ResolveOrg

func (s *SSOService) ResolveOrg(ctx context.Context, org string) string

ResolveOrg turns an organization reference from discovery into the organization's slug. Anything else is returned unchanged (a slug typed or linked by an organization). An invalid or expired reference resolves to "" and so matches no organization.

func (*SSOService) SetAuditService

func (s *SSOService) SetAuditService(a *auditapp.AuditService)

SetIdentityRepo wires the federated identity store. SetAuditService wires the auth.login event for SSO and SAML sign-ins.

func (*SSOService) SetBreakGlassGate

func (s *SSOService) SetBreakGlassGate(g BreakGlassGate)

SetBreakGlassGate wires the same refusal on the organization SSO/SAML path.

func (*SSOService) SetDiscoveryKey

func (s *SSOService) SetDiscoveryKey(key []byte)

SetDiscoveryKey sets the key that signs discovery references. Without it, discovery answers "password" (no reference can be made).

func (*SSOService) SetDomainOwnerLookup

func (s *SSOService) SetDomainOwnerLookup(l DomainOwnerLookup)

SetDomainOwnerLookup wires email-first discovery.

func (*SSOService) SetDomainVerifier

func (s *SSOService) SetDomainVerifier(v DomainVerifier)

SetDomainVerifier wires the verified-domain JIT gate (SSO P1). Nil-safe: when left unset, ensureTenantMembership falls back to the P0 AllowedDomains gate.

func (*SSOService) SetFeatureGate

func (s *SSOService) SetFeatureGate(g entitlement.FeatureChecker)

SetFeatureGate wires the feature check of the sign-in features: configuring a connection needs sso.connections. Unset (self-managed default wiring aside, tests): everything is allowed.

func (*SSOService) SetIdentityNotifier

func (s *SSOService) SetIdentityNotifier(n IdentityNotifier)

SetIdentityNotifier wires the link and unlink e-mails.

func (*SSOService) SetIdentityRepo

func (s *SSOService) SetIdentityRepo(repo useridentity.Repository)

func (*SSOService) SetJITApprovalNotifier

func (s *SSOService) SetJITApprovalNotifier(n JITApprovalNotifier)

SetJITApprovalNotifier wires the administrators' notification.

func (*SSOService) SetLinkProofVerifier

func (s *SSOService) SetLinkProofVerifier(v LinkProofVerifier)

SetLinkProofVerifier wires the proof every SSO link and unlink needs.

func (*SSOService) SetSSOSignInRecorder

func (s *SSOService) SetSSOSignInRecorder(r SSOSignInRecorder)

SetSSOSignInRecorder wires the recorder behind the Require SSO precondition.

func (*SSOService) SetSessionRevocationStore

func (s *SSOService) SetSessionRevocationStore(store SessionRevocationStore, ttl time.Duration)

SetSessionRevocationStore wires immediate revocation for sessions ended by an OIDC back-channel logout.

func (*SSOService) SetSessionRevoker

func (s *SSOService) SetSessionRevoker(r SessionRevoker)

SetSessionRevoker wires the revocation of the account's other sessions on every SSO link and unlink.

func (*SSOService) SetSignInHook

func (s *SSOService) SetSignInHook(h SignInHook)

SetSignInHook wires the hook run after an SSO sign-in.

func (*SSOService) SetSignupRecorder

func (s *SSOService) SetSignupRecorder(r signupevent.Recorder)

SetSignupRecorder wires the sign-up event recorder.

func (*SSOService) SetStateStore

func (s *SSOService) SetStateStore(store PKCEVerifierStore)

SetStateStore wires the shared single-use store for SSO state records. Production passes the Redis client so a state is single use across replicas.

func (*SSOService) SetTenantMemberRepo

func (s *SSOService) SetTenantMemberRepo(repo TenantMemberCreator)

SetTenantMemberRepo sets the tenant membership creator for auto-provisioning.

func (s *SSOService) StartSSOLink(ctx context.Context, in SSOLinkStartInput) (*SSOAuthorizeResult, error)

StartSSOLink checks the proof and returns the identity provider's authorization URL (with max_age=0) for a link round trip.

func (*SSOService) UnlinkSSOIdentity

func (s *SSOService) UnlinkSSOIdentity(ctx context.Context, in SSOUnlinkInput) error

UnlinkSSOIdentity removes an organization's OIDC sign-in identity from the signed-in account after checking the proof typed for it. Only an account with a password may: it keeps a way to sign in, and an account the organization's sign-on created stays managed by the organization.

func (*SSOService) UpdateProvider

UpdateProvider updates an identity provider configuration.

type SSOSignInRecorder

type SSOSignInRecorder interface {
	RecordSSOSignIn(ctx context.Context, tenantID, userID shared.ID) error
}

SSOSignInRecorder stamps a member's sign-in through an organization's own identity provider (postgres.SSOEnforcementRepository).

type SSOUnlinkInput

type SSOUnlinkInput struct {
	UserID     string
	SessionID  string
	IdentityID string
	// Proof is the code or password typed in the confirm dialog.
	Proof StepUpProof
}

SSOUnlinkInput removes an organization sign-in identity from the signed-in account.

type SSOUserInfo

type SSOUserInfo struct {
	Email     string
	Name      string
	AvatarURL string

	// Issuer + Subject are the verified id_token's federated identity, the
	// key the account is found by (federated_identity.go). Empty when the
	// provider returned no id_token to verify: the email then finds the
	// account, under the adoption guards, and nothing is bound.
	Issuer  string
	Subject string
	// LegacySubject is the subject the issuer used for this identity before
	// (Entra: `sub`, now keyed on `oid`); an identity bound under it is
	// re-keyed to Subject.
	LegacySubject string

	// EmailVerified records that the IdP proved ownership of Email (Entra
	// xms_edov==true, or the OIDC email_verified claim). Producers set it true
	// ONLY after that check passes. It gates the proof-before-link claim of a
	// pre-existing passwordless account (Case 2); its zero value (false) is
	// fail-closed, so any producer that forgets to set it refuses the claim.
	EmailVerified bool
}

SSOUserInfo represents user info from SSO provider.

type SecondFactorGate

type SecondFactorGate interface {
	LinkedSignInChallenge(ctx context.Context, u *userdom.User, ip, ua string) (*MFAChallengeInfo, error)
}

SecondFactorGate issues the second step of a sign-in to a password account (implemented by AuthService: the same rule as the password sign-in).

type SecurityNotifier

type SecurityNotifier interface {
	NotifyMFADisabled(ctx context.Context, email, name, ipAddress string)
	NotifyRecoveryCodeUsed(ctx context.Context, email, name, ipAddress string, remaining int)
	NotifyPasswordChanged(ctx context.Context, email, name, ipAddress string)
}

SecurityNotifier tells a user about security-relevant changes to their account. Implementations must not block: calls happen after the change is committed and failures are only logged.

type SelfServiceLimits

type SelfServiceLimits interface {
	SelfServiceDefaults(ctx context.Context) (limits.Limits, int, error)
	CheckOrgsPerUser(ctx context.Context, userID shared.ID) error
}

SelfServiceLimits is the slice of the entitlement service the self-service creation paths use: the limits a new organization starts with, and the per-person organization cap.

type SenderDomains

type SenderDomains interface {
	GetByTenantAndDomain(ctx context.Context, tenantID shared.ID, domain string) (*verifieddomain.VerifiedDomain, error)
}

SenderDomains answers whether a domain is DNS-verified for an organization.

type SessionInfo

type SessionInfo struct {
	ID             string `json:"id"`
	IPAddress      string `json:"ip_address,omitempty"`
	UserAgent      string `json:"user_agent,omitempty"`
	LastActivityAt string `json:"last_activity_at"`
	CreatedAt      string `json:"created_at"`
	IsCurrent      bool   `json:"is_current"`
}

SessionInfo represents session information returned to the user.

type SessionResult

type SessionResult struct {
	AccessToken  string
	RefreshToken string
}

SessionResult represents session creation result.

type SessionRevocationStore

type SessionRevocationStore interface {
	MarkSessionRevoked(ctx context.Context, sessionID string, ttl time.Duration) error
}

SessionRevocationStore records revoked session ids so the authentication middleware can refuse access tokens of a revoked session immediately instead of when they expire. ttl only needs to outlive the access tokens.

type SessionRevoker

type SessionRevoker interface {
	RevokeAllSessions(ctx context.Context, userID, exceptSessionID string) error
}

SessionRevoker revokes every session of an account (SessionService).

type SessionService

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

SessionService handles session management operations.

func NewSessionService

func NewSessionService(
	sessionRepo sessiondom.Repository,
	refreshTokenRepo sessiondom.RefreshTokenRepository,
	log *logger.Logger,
) *SessionService

NewSessionService creates a new SessionService.

func (*SessionService) ActiveAPIKeys

func (s *SessionService) ActiveAPIKeys(ctx context.Context, userID string) int

ActiveAPIKeys counts the API keys the user owns that a sign-out everywhere would revoke on request (0 when unknown).

func (*SessionService) CleanupExpiredSessions

func (s *SessionService) CleanupExpiredSessions(ctx context.Context) (int64, int64, error)

CleanupExpiredSessions removes expired sessions and tokens. This should be called periodically (e.g., by a cron job).

func (*SessionService) CountActiveSessions

func (s *SessionService) CountActiveSessions(ctx context.Context, userID string) (int, error)

CountActiveSessions returns the count of active sessions for a user.

func (*SessionService) GetSessionByAccessToken

func (s *SessionService) GetSessionByAccessToken(ctx context.Context, accessToken string) (*sessiondom.Session, error)

GetSessionByAccessToken retrieves a session by its access token.

func (*SessionService) ListUserSessions

func (s *SessionService) ListUserSessions(ctx context.Context, userID string, currentSessionID string) ([]SessionInfo, error)

ListUserSessions returns all active sessions for a user.

func (*SessionService) RevokeAllSessions

func (s *SessionService) RevokeAllSessions(ctx context.Context, userID, exceptSessionID string) error

RevokeAllSessions revokes all sessions for a user except the current one.

func (*SessionService) RevokeSession

func (s *SessionService) RevokeSession(ctx context.Context, userID, sessionID string) error

RevokeSession revokes a specific session for a user.

func (*SessionService) RevokeSessionsIssuedBy

func (s *SessionService) RevokeSessionsIssuedBy(ctx context.Context, userID, tenantID string) (int, error)

RevokeSessionsIssuedBy ends the user's sessions whose sign-in was asserted by tenantID's own identity provider (Session.IDPTenantID): that organization's assertion was the only proof of identity behind them, so they end when the organization removes the person. Every other session (password, social login, another organization's IdP) stays: the organization's own data is closed to it by the per-request membership check, and it is not this organization's to end. Returns how many sessions were revoked.

func (*SessionService) SetMFAChallengeCleanup

func (s *SessionService) SetMFAChallengeCleanup(repo mfa.Repository)

SetMFAChallengeCleanup makes CleanupExpiredSessions also delete expired 2FA login challenges.

func (*SessionService) SetPermissionServices

func (s *SessionService) SetPermissionServices(
	cacheSvc *accesscontrol.PermissionCacheService,
	versionSvc *accesscontrol.PermissionVersionService,
	tenantRepo TenantMembershipProvider,
)

SetPermissionServices sets the permission cache and version services. This enables cache invalidation when sessions are revoked.

func (*SessionService) SetRevocationStore

func (s *SessionService) SetRevocationStore(store SessionRevocationStore, ttl time.Duration)

SetRevocationStore wires immediate access-token revocation. ttl must be at least the access-token lifetime.

func (*SessionService) SetSessionsRevokedHooks

func (s *SessionService) SetSessionsRevokedHooks(h *SessionsRevokedHooks)

SetSessionsRevokedHooks wires the hook list shared with AuthService.

func (*SessionService) SignOutEverywhere

func (s *SessionService) SignOutEverywhere(ctx context.Context, userID, exceptSessionID string, revokeAPIKeys bool) (SignOutResult, error)

SignOutEverywhere revokes the user's other sessions (all when exceptSessionID is empty) and, like a password change, ends the person's connected applications in every organization. API keys go too when revokeAPIKeys is set. It acts on the one user it is given.

func (*SessionService) UpdateSessionActivity

func (s *SessionService) UpdateSessionActivity(ctx context.Context, sessionID string) error

UpdateSessionActivity updates the last activity time for a session.

func (*SessionService) ValidateSession

func (s *SessionService) ValidateSession(ctx context.Context, sessionID string) (*sessiondom.Session, error)

ValidateSession checks if a session is valid.

type SessionsRevokedHook

type SessionsRevokedHook func(ctx context.Context, userID shared.ID)

SessionsRevokedHook runs after the sessions of an account were revoked because one of its credentials changed: a password reset or change, an administrator's two-step reset, enabling two-step verification, or a sign-out of every device. Two hooks are wired in production: the platform admin console ends the console sessions of the administrator linked to the account, and the MCP service revokes the person's connected applications in every organization, so a stolen session does not outlive the credential it was opened with and a connector approved with it does not either.

A hook must touch only the one user it is given.

type SessionsRevokedHooks

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

SessionsRevokedHooks is the ordered list of hooks plus the optional API key revoker. The zero value is ready to use; wire it at start-up, before requests are served.

func (*SessionsRevokedHooks) Add

Add appends a hook (nil is ignored).

func (*SessionsRevokedHooks) CountActiveAPIKeys

func (h *SessionsRevokedHooks) CountActiveAPIKeys(ctx context.Context, userID shared.ID) int

CountActiveAPIKeys counts the user's active API keys (0 without a revoker).

func (*SessionsRevokedHooks) RevokeAPIKeysIf

func (h *SessionsRevokedHooks) RevokeAPIKeysIf(ctx context.Context, ask bool, userID shared.ID) int

RevokeAPIKeysIf revokes the user's API keys when asked and returns how many were revoked. A failure is returned as zero: the sessions are already gone, and the caller cannot undo that.

func (*SessionsRevokedHooks) Run

func (h *SessionsRevokedHooks) Run(ctx context.Context, userID shared.ID)

Run calls every hook in order. A hook has no error to return: each one logs its own failure, and one failing must not stop the others.

func (*SessionsRevokedHooks) SetAPIKeyRevoker

func (h *SessionsRevokedHooks) SetAPIKeyRevoker(k APIKeyRevoker)

SetAPIKeyRevoker wires the API key revoker (nil: none).

type SettingsStorageResolver

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

SettingsStorageResolver resolves per-tenant storage config from the settings table.

func NewSettingsStorageResolver

func NewSettingsStorageResolver(db *sql.DB, enc crypto.Encryptor, log *logger.Logger) *SettingsStorageResolver

NewSettingsStorageResolver creates a new resolver.

func (*SettingsStorageResolver) GetTenantStorageConfig

func (r *SettingsStorageResolver) GetTenantStorageConfig(ctx context.Context, tenantID string) (*attachment.StorageConfig, error)

GetTenantStorageConfig reads the storage_config setting for a tenant. Returns nil if not configured (tenant uses default provider).

func (*SettingsStorageResolver) SaveTenantStorageConfig

func (r *SettingsStorageResolver) SaveTenantStorageConfig(ctx context.Context, tenantID string, cfg attachment.StorageConfig) error

SaveTenantStorageConfig upserts the storage config for a tenant.

type SignInHook

type SignInHook func(ctx context.Context, userID shared.ID)

SignInHook runs after a sign-in created a session: signing in again cancels a pending self-service account deletion (accountdeletion). It never fails the sign-in.

type SignInMethod

type SignInMethod struct {
	ID string `json:"id"`
	// Provider: google, github or microsoft; organization for an
	// organization's single sign-on (read only here).
	Provider   string     `json:"provider"`
	CreatedAt  time.Time  `json:"created_at"`
	LastUsedAt *time.Time `json:"last_used_at,omitempty"`
	// Unlinkable: the person may remove it now (a social identity that is not
	// the account's last sign-in method).
	Unlinkable bool `json:"unlinkable"`
}

SignInMethod is one way to sign in to the account, for Account > Security.

type SignInMethods

type SignInMethods struct {
	// Password: the account signs in with a password.
	Password   bool           `json:"password"`
	Identities []SignInMethod `json:"identities"`
	// Available: social providers this platform offers for linking.
	Available []string `json:"available"`
	// Proof is what linking or unlinking asks for in the confirm dialog:
	// totp, password, or "" when the account has neither (it must turn on
	// two-factor authentication first).
	Proof string `json:"proof"`
}

SignInMethods lists the account's sign-in methods.

type SignOutResult

type SignOutResult struct {
	// APIKeysRevoked is the number of API keys revoked (0 unless asked).
	APIKeysRevoked int
}

SignOutResult says what a sign-out everywhere also ended.

type StepUpMethod

type StepUpMethod string

StepUpMethod names what the account must present.

const (
	StepUpTOTP        StepUpMethod = "totp"
	StepUpPassword    StepUpMethod = "password"
	StepUpFreshSignIn StepUpMethod = "fresh_sign_in"
)

type StepUpProof

type StepUpProof struct {
	TOTP     string `json:"totp,omitempty"`
	Password string `json:"password,omitempty"`
}

StepUpProof is what the user typed.

type StepUpSessionStore

type StepUpSessionStore interface {
	MarkStepUp(ctx context.Context, sessionID, userID shared.ID, at time.Time) (bool, error)
	RecentAuthAt(ctx context.Context, sessionID, userID shared.ID) (time.Time, error)
}

StepUpSessionStore is the session state step-up needs. The PostgreSQL session repository implements it.

type StepUpState

type StepUpState struct {
	Method StepUpMethod `json:"method"`
	// ValidUntil is when the current window closes; nil when it is closed.
	ValidUntil *time.Time `json:"valid_until,omitempty"`
	// WindowSeconds is the length of a window opened by a step-up.
	WindowSeconds int `json:"window_seconds"`
}

StepUpState tells the client what to ask for and whether the session is already inside the window.

type TenantMemberCreator

type TenantMemberCreator interface {
	CreateMembership(ctx context.Context, m *tenantdom.Membership) error
	GetMembership(ctx context.Context, userID, tenantID shared.ID) (*tenantdom.Membership, error)
}

TenantMemberCreator creates tenant memberships for auto-provisioned users and looks up existing membership (used to gate federated account binding).

type TenantMembershipInfo

type TenantMembershipInfo struct {
	TenantID   string `json:"tenant_id"`
	TenantSlug string `json:"tenant_slug"`
	TenantName string `json:"tenant_name"`
	Role       string `json:"role"`
	// OrganizationSuspended: the organization is suspended by a platform
	// administrator; the client shows tenant.MessageOrganizationSuspended.
	OrganizationSuspended bool `json:"organization_suspended,omitempty"`
	// DeletionDueAt: the organization is scheduled for deletion at this time;
	// an owner may still cancel.
	DeletionDueAt *time.Time `json:"deletion_due_at,omitempty"`
}

TenantMembershipInfo represents a tenant membership for API responses.

type TenantMembershipProvider

type TenantMembershipProvider interface {
	GetUserTenantIDs(ctx context.Context, userID shared.ID) ([]string, error)
}

TenantMembershipProvider provides tenant membership information. Used to get all tenants a user belongs to for cache invalidation.

type TenantSMTPResolver

type TenantSMTPResolver interface {
	GetTenantSMTPConfig(ctx context.Context, tenantID string) (*emaildom.Config, error)
}

TenantSMTPResolver resolves per-tenant SMTP configuration from integrations. Returns nil if tenant has no custom SMTP config (fallback to system default).

type TrustLookup

type TrustLookup interface {
	GetPair(ctx context.Context, host, home shared.ID) (*orgtrust.Trust, error)
}

TrustLookup reads the trust host → home.

type UnlinkInput

type UnlinkInput struct {
	UserID     string
	SessionID  string
	IdentityID string
	// Proof is the code or password typed in the confirm dialog.
	Proof StepUpProof
}

UnlinkInput removes one social identity from the signed-in account.

type UpdateProviderInput

type UpdateProviderInput struct {
	ID               string
	TenantID         string // For authorization check
	DisplayName      *string
	ClientID         *string
	ClientSecret     *string // Plaintext - will be encrypted if provided
	IssuerURL        *string
	TenantIdentifier *string
	Scopes           []string
	AllowedDomains   []string
	AutoProvision    *bool
	DefaultRole      *string
	IsActive         *bool
}

UpdateProviderInput is the input for updating an identity provider config.

type VerifyMFAInput

type VerifyMFAInput struct {
	Token        string
	Code         string
	RecoveryCode string
	IPAddress    string
	UserAgent    string
}

VerifyMFAInput is the second login step.

Directories

Path Synopsis
Package domainverify implements DNS-TXT domain-ownership verification and the verified-domain gate for SSO JIT auto-provisioning (SSO P1).
Package domainverify implements DNS-TXT domain-ownership verification and the verified-domain gate for SSO JIT auto-provisioning (SSO P1).

Jump to

Keyboard shortcuts

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