Documentation
¶
Overview ¶
Package auth provides authentication services and handlers.
Index ¶
- Constants
- Variables
- func DecodeTelegramAuthResult(encoded string) (map[string]string, error)
- func DemoAllowedRoutes() [][2]string
- func EmbedOriginsFromParam(param *models.Parameter) []string
- func FormatDeviceUserCode(canonical string) string
- func ImpersonationForbiddenRoutes() [][2]string
- func InviteExpiresIn(loc i18n.Locale, expiresIn string) string
- func IsDemoWriteAllowed(method, routePattern string) bool
- func IsImpersonationAllowed(method, routePattern string) bool
- func IsMCPCredentialRouteAllowed(claims *Claims, method, routePattern string) bool
- func IsPATAllowed(method, routePattern string) bool
- func IsPATCredential(ctx context.Context) bool
- func IsPasswordRotationExempt(method, path string) bool
- func MCPCredentialAllowedRoutes() [][2]string
- func NormalizeDeviceUserCode(input string) string
- func NotifyUserRegistered(ctx context.Context, user *models.User, method string)
- func PATForbiddenRoutes() [][2]string
- func PasswordRotationRequired(user *models.User) bool
- func RedirectWithHandoff(writer http.ResponseWriter, req *http.Request, dbService db.Service, ...) error
- func RequireSSOProvider(cfg *config.Config, provider string) httpx.Middleware
- func ResolveLinkedOrganization(ctx context.Context, dbSvc db.Service, providerType models.ProviderType, ...) (*models.Organization, error)
- func ResolveLinkedUser(ctx context.Context, dbSvc db.Service, providerType models.ProviderType, ...) (*models.User, error)
- func ResolvedOrgFromContext(ctx context.Context, slug string) *models.Organization
- func WithPATCredential(ctx context.Context) context.Context
- func WithResolvedOrg(ctx context.Context, org *models.Organization) context.Context
- func WriteReauthError(handler *base.HandlerBase, writer http.ResponseWriter, request *http.Request, ...) (bool, error)
- type AcceptInviteRequest
- type AdminUpdateUserRequest
- type AdminUpdateUserResponse
- type AuthedUser
- type ChangePasswordRequest
- type ChangePasswordResponse
- type Claims
- type Confirm2FARequest
- type Confirm2FAResponse
- type ConfirmRegistrationRequest
- type Context
- type CreateOrgRequest
- type CreateTokenRequest
- type CreateTokenResponse
- type DeleteOrgRequest
- type DeviceAuthorizationRequestBody
- type DeviceAuthorizationResponse
- type DeviceConsentInfo
- type DeviceConsentRequest
- type DeviceRequester
- type DeviceTokenRequestBody
- type DeviceTokenResponse
- type Disable2FARequest
- type DiscordGuild
- type DiscordOAuthHandler
- type DiscordOAuthResult
- type DiscordOAuthService
- func (s *DiscordOAuthService) GenerateOAuthState(ctx context.Context, redirectURI string) (string, error)
- func (s *DiscordOAuthService) HandleCallback(ctx context.Context, code string) (*DiscordOAuthResult, error)
- func (s *DiscordOAuthService) LinkDiscordProvider(ctx context.Context, userUID, orgUID, discordUserID string) error
- func (s *DiscordOAuthService) ValidateOAuthState(ctx context.Context, stateParam string) (*OAuthState, error)
- type DiscordTokenResponse
- type DiscordUserInfo
- type EntitlementsChecker
- type GitHubEmail
- type GitHubOAuthHandler
- type GitHubOAuthResult
- type GitHubOAuthService
- func (s *GitHubOAuthService) GenerateOAuthState(ctx context.Context, redirectURI, orgSlug string) (string, error)
- func (s *GitHubOAuthService) HandleCallback(ctx context.Context, code, orgSlug string) (*GitHubOAuthResult, error)
- func (s *GitHubOAuthService) ValidateOAuthState(ctx context.Context, stateParam string) (*OAuthState, error)
- type GitHubTokenResponse
- type GitHubUserInfo
- type GitLabEmail
- type GitLabOAuthHandler
- type GitLabOAuthResult
- type GitLabOAuthService
- func (s *GitLabOAuthService) GenerateOAuthState(ctx context.Context, redirectURI, orgSlug string) (string, error)
- func (s *GitLabOAuthService) HandleCallback(ctx context.Context, code, orgSlug string) (*GitLabOAuthResult, error)
- func (s *GitLabOAuthService) ValidateOAuthState(ctx context.Context, stateParam string) (*OAuthState, error)
- type GitLabTokenResponse
- type GitLabUserInfo
- type GoogleOAuthHandler
- type GoogleOAuthResult
- type GoogleOAuthService
- func (s *GoogleOAuthService) GenerateOAuthState(ctx context.Context, redirectURI, orgSlug string) (string, error)
- func (s *GoogleOAuthService) HandleCallback(ctx context.Context, code, orgSlug string) (*GoogleOAuthResult, error)
- func (s *GoogleOAuthService) ValidateOAuthState(ctx context.Context, stateParam string) (*OAuthState, error)
- type GoogleTokenResponse
- type GoogleUserInfo
- type Handler
- func (h *Handler) AcceptInvite(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) AdminUpdateUser(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) ApproveMembershipRequestHandler(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) CancelMembershipRequestHandler(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) ChangePassword(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) Confirm2FA(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) ConfirmRegistration(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) CreateInvitation(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) CreateMembershipRequestHandler(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) CreateOrg(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) CreateToken(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) DeleteOrg(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) Disable2FA(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) ExchangeHandoff(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) GetAllUserTokens(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) GetDeviceConsent(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) GetInviteInfo(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) GetOrgSettings(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) GetOrgTokens(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) Impersonate(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) ListInvitations(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) ListOrgMembershipRequestsHandler(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) ListOwnMembershipRequestsHandler(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) Login(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) Logout(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) Me(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) PollDeviceToken(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) Recovery2FA(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) Refresh(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) Register(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) RejectMembershipRequestHandler(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) RequestPasswordReset(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) ResetPassword(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) RespondToDeviceConsent(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) RevokeCurrentToken(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) RevokeInvitation(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) RevokeToken(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) Setup2FA(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) StartDeviceAuthorization(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) SwitchOrg(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) UpdateMe(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) UpdateOrgProfile(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) UpdateOrgSettings(writer http.ResponseWriter, req *http.Request) error
- func (h *Handler) Verify2FA(writer http.ResponseWriter, req *http.Request) error
- type HandoffExchangeRequest
- type HandoffExchangeResponse
- type ImpersonateRequest
- type ImpersonationInfo
- type InviteInfoResponse
- type InviteListItem
- type InviteListResponse
- type InviteRequest
- type InviteResponse
- type LDAPService
- type LDAPUserInfo
- type LoginAction
- type LoginBeginResponse
- type LoginOption
- type LoginRequest
- type LoginResponse
- type LogoutRequest
- type LogoutResponse
- type MeResponse
- type MembershipRequestAdminListResponse
- type MembershipRequestAdminView
- type MembershipRequestApproveRequest
- type MembershipRequestCreateRequest
- type MembershipRequestListResponse
- type MembershipRequestRejectRequest
- type MembershipRequestSummary
- type MicrosoftOAuthHandler
- type MicrosoftOAuthResult
- type MicrosoftOAuthService
- func (s *MicrosoftOAuthService) GenerateOAuthState(ctx context.Context, redirectURI, orgSlug string) (string, error)
- func (s *MicrosoftOAuthService) HandleCallback(ctx context.Context, code, orgSlug string) (*MicrosoftOAuthResult, error)
- func (s *MicrosoftOAuthService) ValidateOAuthState(ctx context.Context, stateParam string) (*OAuthState, error)
- type MicrosoftTokenResponse
- type MicrosoftUserInfo
- type OAuthLoginResponse
- type OAuthResponse
- type OAuthState
- type OIDCOAuthHandler
- type OIDCOAuthResult
- type OIDCOAuthService
- func (s *OIDCOAuthService) GenerateOAuthState(ctx context.Context, redirectURI, orgSlug string) (string, error)
- func (s *OIDCOAuthService) HandleCallback(ctx context.Context, code, orgSlug string) (*OIDCOAuthResult, error)
- func (s *OIDCOAuthService) ValidateOAuthState(ctx context.Context, stateParam string) (*OAuthState, error)
- type OpenIDUserInfo
- type OrgAccessDenial
- type OrgProfileResponse
- type OrgResponse
- type OrgSettingsResponse
- type OrganizationInfo
- type OrganizationRef
- type OrganizationSummary
- type PageMemoInvalidator
- type PasskeyHandler
- func (h *PasskeyHandler) Delete(writer http.ResponseWriter, req *http.Request) error
- func (h *PasskeyHandler) List(writer http.ResponseWriter, req *http.Request) error
- func (h *PasskeyHandler) LoginBegin(writer http.ResponseWriter, req *http.Request) error
- func (h *PasskeyHandler) LoginFinish(writer http.ResponseWriter, req *http.Request) error
- func (h *PasskeyHandler) RegisterBegin(writer http.ResponseWriter, req *http.Request) error
- func (h *PasskeyHandler) RegisterFinish(writer http.ResponseWriter, req *http.Request) error
- func (h *PasskeyHandler) Rename(writer http.ResponseWriter, req *http.Request) error
- type PasskeyInfo
- type PasskeyService
- func (s *PasskeyService) BeginLogin(ctx context.Context, email string) (*LoginBeginResponse, error)
- func (s *PasskeyService) BeginRegistration(ctx context.Context, userUID string, currentPassword *string) (*RegisterBeginResponse, error)
- func (s *PasskeyService) DeletePasskey(ctx context.Context, userUID, passkeyUID string) error
- func (s *PasskeyService) Enabled() bool
- func (s *PasskeyService) FinishLogin(ctx context.Context, sessionToken string, credentialJSON []byte, ...) (*LoginResponse, error)
- func (s *PasskeyService) FinishRegistration(ctx context.Context, sessionToken string, credentialJSON []byte, name string) (*PasskeyInfo, error)
- func (s *PasskeyService) ListPasskeys(ctx context.Context, userUID string) ([]PasskeyInfo, error)
- func (s *PasskeyService) RenamePasskey(ctx context.Context, userUID, passkeyUID, name string) error
- type PreferencesRequest
- type ProviderInfo
- type ProviderLoginResult
- type ProviderOutcome
- type ProvidersHandler
- type ProvidersResponse
- type Recovery2FARequest
- type RefreshRequest
- type RegisterBeginResponse
- type RegisterRequest
- type RegisterResponse
- type RequestPasswordResetRequest
- type RequestPasswordResetResponse
- type ResetPasswordRequest
- type ResetPasswordResponse
- type SAMLHandler
- type SAMLRelayState
- type SAMLResult
- type SAMLService
- func (s *SAMLService) GenerateAuthnRequest(ctx context.Context, redirectURI, orgSlug string) (string, error)
- func (s *SAMLService) HandleACS(ctx context.Context, httpReq *http.Request, state *SAMLRelayState) (*SAMLResult, error)
- func (s *SAMLService) Metadata(ctx context.Context) ([]byte, error)
- func (s *SAMLService) ValidateRelayState(ctx context.Context, relayState string) (*SAMLRelayState, error)
- type Service
- func (s *Service) AcceptInvite(ctx context.Context, req AcceptInviteRequest, callerUID string) (*LoginResponse, error)
- func (s *Service) AdminUpdateUser(ctx context.Context, claims *Claims, targetUID string, ...) (*AdminUpdateUserResponse, error)
- func (s *Service) ApproveMembershipRequest(ctx context.Context, decidedByUID, orgSlug, requestUID string, roleStr string) error
- func (s *Service) CancelMembershipRequest(ctx context.Context, userUID, requestUID string) error
- func (s *Service) ChangePassword(ctx context.Context, userUID, currentRefreshUID string, ...) (*ChangePasswordResponse, error)
- func (s *Service) CheckMembershipSlot(ctx context.Context, orgUID string) error
- func (s *Service) CompleteOrgLogin(ctx context.Context, org *models.Organization, user *models.User, ...) (*ProviderLoginResult, error)
- func (s *Service) Confirm2FA(ctx context.Context, userUID string, req Confirm2FARequest) (*Confirm2FAResponse, error)
- func (s *Service) ConfirmRegistration(ctx context.Context, token string) (*LoginResponse, error)
- func (s *Service) CreateInvitation(ctx context.Context, orgSlug, inviterUID string, req InviteRequest) (*InviteResponse, error)
- func (s *Service) CreateMembershipRequest(ctx context.Context, userUID string, req MembershipRequestCreateRequest) (*MembershipRequestSummary, error)
- func (s *Service) CreateOrg(ctx context.Context, userUID string, req CreateOrgRequest, authContext Context) (*OrgResponse, error)
- func (s *Service) CreatePAT(ctx context.Context, orgSlug, userUID string, req CreateTokenRequest) (*CreateTokenResponse, error)
- func (s *Service) DeleteOrg(ctx context.Context, orgSlug, callerUserUID string, req DeleteOrgRequest, ...) (*LoginResponse, error)
- func (s *Service) Disable2FA(ctx context.Context, userUID, code string) error
- func (s *Service) ExchangeHandoffCode(ctx context.Context, code string) (*HandoffExchangeResponse, error)
- func (s *Service) GenerateMCPAccessToken(ctx context.Context, userUID, orgSlug string, scopes []string, audience string, ...) (string, error)
- func (s *Service) GenerateTokensForOAuth(ctx context.Context, user *models.User, org *models.Organization, ...) (*OAuthLoginResponse, error)
- func (s *Service) GetAllUserTokens(ctx context.Context, userUID, tokenType, callerRefreshUID string) (*TokenListResponse, error)
- func (s *Service) GetDeviceConsent(ctx context.Context, rawUserCode string) (*DeviceConsentInfo, error)
- func (s *Service) GetInviteInfo(ctx context.Context, token string) (*InviteInfoResponse, error)
- func (s *Service) GetOrgSettings(ctx context.Context, orgSlug string) (*OrgSettingsResponse, error)
- func (s *Service) GetUserInfo(ctx context.Context, claims *Claims) (*MeResponse, error)
- func (s *Service) GetUserTokens(ctx context.Context, orgSlug, userUID, tokenType, callerRefreshUID string) (*TokenListResponse, error)
- func (s *Service) Impersonate(ctx context.Context, actorUID, targetUID, orgSlug string, authContext Context) (*LoginResponse, error)
- func (s *Service) ImpersonationInfoFor(ctx context.Context, claims *Claims) *ImpersonationInfo
- func (s *Service) JoinOrgViaLogin(ctx context.Context, org *models.Organization, user *models.User, ...) (*models.OrganizationMember, bool, error)
- func (s *Service) ListInvitations(ctx context.Context, orgSlug string) (*InviteListResponse, error)
- func (s *Service) ListOrgMembershipRequests(ctx context.Context, orgSlug string, status models.MembershipRequestStatus) (*MembershipRequestAdminListResponse, error)
- func (s *Service) ListOwnMembershipRequests(ctx context.Context, userUID string) (*MembershipRequestListResponse, error)
- func (s *Service) LocalLoginEnabled(ctx context.Context) bool
- func (s *Service) Login(ctx context.Context, orgSlug, email, password string, authContext Context) (*LoginResponse, error)
- func (s *Service) Logout(ctx context.Context, refreshToken string) error
- func (s *Service) LogoutOtherSessions(ctx context.Context, userUID, currentRefreshUID string) (*LogoutResponse, error)
- func (s *Service) LogoutSession(ctx context.Context, userUID, refreshUID string) error
- func (s *Service) LogoutUser(ctx context.Context, userUID string) (*LogoutResponse, error)
- func (s *Service) NotifyContactAdded(ctx context.Context, user *models.User, orgUID, display string)
- func (s *Service) NotifyTelegramLinked(ctx context.Context, userUID, orgUID string)
- func (s *Service) PollDeviceToken(ctx context.Context, deviceCode string) (string, error)
- func (s *Service) ReauthenticateForFactor(ctx context.Context, user *models.User, currentPassword *string) error
- func (s *Service) Recovery2FA(ctx context.Context, tempToken, recoveryCode string, authContext Context) (*LoginResponse, error)
- func (s *Service) Refresh(ctx context.Context, refreshTokenValue string) (*LoginResponse, error)
- func (s *Service) Register(ctx context.Context, req RegisterRequest) (*RegisterResponse, error)
- func (s *Service) RejectMembershipRequest(ctx context.Context, decidedByUID, orgSlug, requestUID, reason string) error
- func (s *Service) ReportDanglingProviderLinks(ctx context.Context)
- func (s *Service) RequestPasswordReset(ctx context.Context, req RequestPasswordResetRequest, remoteAddr string) (*RequestPasswordResetResponse, error)
- func (s *Service) ResetPassword(ctx context.Context, req ResetPasswordRequest) (*ResetPasswordResponse, error)
- func (s *Service) RespondToDeviceConsent(ctx context.Context, claims *Claims, rawUserCode, orgSlug string, approve bool) error
- func (s *Service) RevokeInvitation(ctx context.Context, orgSlug, invitationUID string) error
- func (s *Service) RevokeToken(ctx context.Context, userUID, tokenUID string) error
- func (s *Service) SendContactVerificationCode(ctx context.Context, user *models.User, orgUID, address, code string) error
- func (s *Service) SetEventNotifier(ctx context.Context, n notifier.EventNotifier)
- func (s *Service) SetPageMemoInvalidator(inv PageMemoInvalidator)
- func (s *Service) SetSupportInbox(svc *support.Service)
- func (s *Service) Setup2FA(ctx context.Context, userUID string, req Setup2FARequest) (*Setup2FAResponse, error)
- func (s *Service) StartDeviceAuthorization(ctx context.Context, clientName string, requester DeviceRequester) (*DeviceAuthorizationResponse, error)
- func (s *Service) SwitchOrg(ctx context.Context, userUID, targetOrgSlug string, authContext Context) (*LoginResponse, error)
- func (s *Service) UpdateOrgProfile(ctx context.Context, orgSlug string, userUID string, ...) (*OrgProfileResponse, error)
- func (s *Service) UpdateOrgSettings(ctx context.Context, orgSlug string, req UpdateOrgSettingsRequest) (*OrgSettingsResponse, error)
- func (s *Service) UpdateProfile(ctx context.Context, claims *Claims, req UpdateProfileRequest) (*MeResponse, error)
- func (s *Service) ValidatePATToken(ctx context.Context, patToken string) (*Claims, error)
- func (s *Service) ValidateToken(ctx context.Context, tokenString string) (*Claims, error)
- func (s *Service) Verify2FA(ctx context.Context, tempToken, code string, authContext Context) (*LoginResponse, error)
- type Setup2FARequest
- type Setup2FAResponse
- type SlackExchangeResult
- type SlackOAuthHandler
- type SlackOAuthResult
- type SlackOAuthService
- func (s *SlackOAuthService) ExchangeSlackInstallCode(ctx context.Context, code string) (*SlackExchangeResult, error)
- func (s *SlackOAuthService) GenerateOAuthState(ctx context.Context, redirectURI string) (string, error)
- func (s *SlackOAuthService) HandleCallback(ctx context.Context, code string) (*SlackOAuthResult, error)
- func (s *SlackOAuthService) ValidateOAuthState(ctx context.Context, stateParam string) (*OAuthState, error)
- type SwitchOrgRequest
- type TelegramIdentity
- type TelegramLoginHandler
- type TelegramLoginService
- func (s *TelegramLoginService) GenerateOAuthState(ctx context.Context, redirectURI, orgSlug string) (string, error)
- func (s *TelegramLoginService) HandleCallback(ctx context.Context, fields map[string]string, orgSlug string) (*ProviderOutcome, error)
- func (s *TelegramLoginService) ValidateOAuthState(ctx context.Context, stateParam string) (*OAuthState, error)
- type TokenCreatedWith
- type TokenInfo
- type TokenListResponse
- type TwoFAClaims
- type UpdateOrgProfileRequest
- type UpdateOrgSettingsRequest
- type UpdateProfileRequest
- type UserInfo
- type Verify2FARequest
Constants ¶
const ( // AuthMethodPassword is a local password login. AuthMethodPassword = "password" // AuthMethodLDAP is a login verified against the configured LDAP directory. AuthMethodLDAP = "ldap" // AuthMethodPasskey is a WebAuthn login. AuthMethodPasskey = "passkey" // AuthMethodOAuth is the fallback for a federated connector that did not // name itself. AuthMethodOAuth = "oauth" // AuthMethodInvitation is a session minted by accepting an invitation. AuthMethodInvitation = "invitation" // AuthMethodRegistration is a session minted by confirming a registration. AuthMethodRegistration = "registration" // AuthMethodSwitchOrg is a session minted for a different organization the // user already belongs to. AuthMethodSwitchOrg = "switch_org" // AuthMethodImpersonate is a super admin acting as another user through a // short-lived impersonation token (spec 2026-09-29-03). It mints no // session, so it is recorded on auth.impersonation_started, never on // auth.login_succeeded. AuthMethodImpersonate = "impersonate" // AuthMethodOrgSession is a session re-minted because the org itself // changed under the caller (creation, slug rename). AuthMethodOrgSession = "org_session" // SecondFactorTOTP / SecondFactorRecoveryCode are appended to the // first-factor method, e.g. "password+totp", so the trail records BOTH // factors rather than losing the first one at the 2FA hand-off. SecondFactorTOTP = "totp" SecondFactorRecoveryCode = "recovery_code" )
Authentication methods recorded on auth.login_succeeded. The federated values are supplied by each connector through WithLoginMethod; the rest are the local session-minting paths, which are just as much "a session was issued" facts as an SSO callback is.
const ( // DemoPathLogout keeps a demo session from being a session with no exit. DemoPathLogout = "/api/v1/auth/logout" // DemoPatternChecks is check creation — the whole point of the demo. DemoPatternChecks = "/api/v1/orgs/{org}/checks" // DemoPatternChecksValidate is the dry-run validation the check form calls // as you type. It writes nothing. DemoPatternChecksValidate = "/api/v1/orgs/{org}/checks/validate" // DemoPatternCheck is edit/delete of ONE check. The guard lets the method // through; whether this particular check may be touched is an OWNERSHIP // question, answered in checks.Service against checks.created_by. DemoPatternCheck = "/api/v1/orgs/{org}/checks/{checkUid}" // DemoPatternCheckClone clones a check into one the visitor owns — which // is how a seeded, un-owned check becomes editable without ever being // mutated. DemoPatternCheckClone = "/api/v1/orgs/{org}/checks/{checkUid}/clone" )
Route patterns a demo session may write to. These are chi's RESOLVED route patterns (httpx.RoutePattern), never raw request paths: matching on the raw path would let a previous-slug redirect, a trailing slash or a crafted check identifier smuggle a request past the list.
const ( // DeviceAuthTTL bounds how long a device-authorization request stays // usable — the human has this long to walk to a browser and approve. DeviceAuthTTL = 15 * time.Minute // DevicePollIntervalSeconds is the minimum spacing the client must keep // between polls (RFC 8628 `interval`). Polling faster earns slow_down. DevicePollIntervalSeconds = 5 // DevicePATExpiry is the lifetime of the PAT minted at consent time. It // matches the dashboard's default token expiry (90 days). DevicePATExpiry = 90 * 24 * time.Hour // DeviceGrantType is the RFC 8628 grant_type the token endpoint accepts. // Not a credential despite the linter's guess: it is an RFC 8628 URN. DeviceGrantType = "urn:ietf:params:oauth:grant-type:device_code" )
OAuth 2.0 Device Authorization Grant (RFC 8628) parameters.
The wire format of the device endpoints is snake_case (device_code, user_code, verification_uri, expires_in, interval, and the RFC 6749 §5.2 error codes) rather than solidping's house camelCase: these are the interoperable OAuth contract, and every off-the-shelf device-flow client expects the RFC spelling. The deviation is deliberate and confined to the four /auth/device* endpoints.
const ( OAuthCodeInvalidState = "INVALID_STATE" OAuthCodeEmailNotVerified = "EMAIL_NOT_VERIFIED" OAuthCodeTokenExchange = "TOKEN_EXCHANGE_FAILED" OAuthCodeFailed = "OAUTH_FAILED" // OAuthCodeAccountExistsSignInFirst refuses a first provider sign-in whose // email matches an existing account: it is never linked silently. OAuthCodeAccountExistsSignInFirst = "ACCOUNT_EXISTS_SIGN_IN_FIRST" OAuthDescAccountExistsSignInFirst = "An account already uses this email. " + "Sign in with the method you already use for it" OAuthDescInvalidState = "Invalid or expired state parameter" OAuthDescTokenExchange = "Failed to exchange authorization code" // OAuthDescGenericFailure is what an UNEXPECTED provider-callback failure // tells the user. The details never travel with the redirect: the browser // lands on the SPA with these params in the URL bar, so anything specific // put here leaks internals to anyone looking over the user's shoulder (the // production incident behind spec 2026-08-25-01 put a raw // "sql: no rows in result set" there). The real error goes to the server // log instead — see logOAuthFailure. OAuthDescGenericFailure = "Sign-in failed, please try again" )
OAuth error codes shared across all OAuth handlers.
const ( ImpersonationPathSwitchOrg = "/api/v1/auth/switch-org" ImpersonationPathChangePassword = "/api/v1/auth/change-password" ImpersonationPathMe = "/api/v1/auth/me" ImpersonationPatternSystemUser = "/api/v1/system/users/{uid}" ImpersonationPath2FASetup = "/api/v1/auth/2fa/setup" ImpersonationPath2FAConfirm = "/api/v1/auth/2fa/confirm" ImpersonationPath2FA = "/api/v1/auth/2fa" ImpersonationPathTokenCurrent = "/api/v1/auth/tokens/current" ImpersonationPatternToken = "/api/v1/auth/tokens/{tokenUid}" ImpersonationPathPasskeyBegin = "/api/v1/auth/passkeys/register/begin" ImpersonationPathPasskeyFinish = "/api/v1/auth/passkeys/register/finish" ImpersonationPatternPasskey = "/api/v1/auth/passkeys/{uid}" ImpersonationPathDeviceConsent = "/api/v1/auth/device/consent" ImpersonationPathOrgs = "/api/v1/orgs" ImpersonationPathAcceptInvite = "/api/v1/auth/accept-invite" ImpersonationPatternOrgTokens = "/api/v1/orgs/{org}/tokens" ImpersonationPatternEnrollmentToken = "/api/v1/orgs/{org}/agent-enrollment-tokens" ImpersonationPatternImpersonate = "/api/v1/system/users/{uid}/impersonate" ImpersonationPatternDiscordLink = "/api/v1/orgs/{org}/users/me/discord/link-start" ImpersonationPatternDiscordConnect = "/api/v1/orgs/{org}/users/me/discord/connect" ImpersonationPatternTelegramLink = "/api/v1/orgs/{org}/users/me/telegram/link" ImpersonationPatternDiscoveryScans = "/api/v1/orgs/{org}/discovery/scans" // The generic paging-contact routes (spec 2026-11-19-02): adding a // contact, re-enabling a route, and the code round trip that makes a // phone, WhatsApp or email contact pageable. ImpersonationPatternNotificationContacts = "/api/v1/orgs/{org}/users/me/notification-contacts" ImpersonationPatternNotificationRoute = "/api/v1/orgs/{org}/users/me/notification-routes/{routeUid}" ImpersonationPatternContactVerify = "/api/v1/orgs/{org}/users/me/notification-contacts/{contactUid}/verify" ImpersonationPatternContactVerifyConfirm = ImpersonationPatternContactVerify + "/confirm" )
Route patterns an impersonation token must never reach (spec 2026-09-29-03). These are chi's RESOLVED route patterns (httpx.RoutePattern), exactly like the demo guard's allowlist, so a trailing slash or a previous-slug redirect cannot smuggle a request past the list.
const ( // CLIOAuthClientID is the client_id of the pre-registered first-party CLI // OAuth client (oauth.CLIClientID aliases it). Dynamic registrations get a // random server-generated ID, so no third party can claim it. CLIOAuthClientID = "solidping-cli" // MCPCredentialRESTMessage is the 401 detail when an MCP credential is // presented to a REST route. MCPCredentialRESTMessage = "This token is only valid for the MCP endpoint" )
MCP credentials on REST (spec 2026-10-16-12).
An OAuth access token and a scoped PAT are bearer tokens on the same verification path as the dashboard session, but their consent is narrower: an `mcp:read` grant must not hand the client the user's full REST role, a PAT mint or a dashboard session. RequireAuth, the realtime WS handshake, feedback attribution and the OAuth consent endpoint all refuse them; the MCP resource server (RequireMCPAuth) is the only place they work.
const ( RoleChangeSuperAdminGranted = "super_admin_granted" RoleChangeSuperAdminRevoked = "super_admin_revoked" // RoleChangeSuperAdminKept: out of every super-admin group, but the last // super admin of the instance, so the claim grant was kept. RoleChangeSuperAdminKept = "super_admin_kept_last" RoleChangeOrgOwnerGranted = "org_owner_granted" RoleChangeOrgAdminGranted = "org_admin_granted" RoleChangeOrgAdminRevoked = "org_admin_revoked" // RoleChangeOrgAdminKept: out of every org-admin group, but the last // owner/admin of the org, so the claim grant was kept. RoleChangeOrgAdminKept = "org_admin_kept_last" )
Role changes the IdP group claim made during a login, reported in the login response (HandoffExchangeResponse.RoleChanges) next to the log line and the audit event of each one (spec 2026-11-21-02).
const ( // PathChangePassword is the authenticated rotation endpoint. PathChangePassword = "/api/v1/auth/change-password" // PathMe is how a client discovers that it must rotate. PathMe = "/api/v1/auth/me" // PathLogout keeps a blocked session from being a session with no exit. PathLogout = "/api/v1/auth/logout" )
Paths a must-change-password session may still reach. Exported because the route table in internal/app/server.go and the clients that route on the refusal all name the same three endpoints.
const ( SAMLCodeAssertionInvalid = "ASSERTION_INVALID" SAMLCodeNoEmail = "NO_EMAIL" SAMLCodeNotConfigured = "NOT_CONFIGURED" )
SAML-specific error codes surfaced to the frontend via the `error` query parameter on the redirect-back URL.
const ( // OAuthCodeTelegramNotLinked is the error code of a Telegram sign-in by // an account no SolidPing user linked. OAuthCodeTelegramNotLinked = "TELEGRAM_NOT_LINKED" // OAuthDescTelegramNotLinked tells the user how to get past it. OAuthDescTelegramNotLinked = "This Telegram account is not linked to a SolidPing account. " + "Sign in another way, then connect Telegram in your account's notification settings." // OAuthCodeTelegramAmbiguous is the error code of a Telegram sign-in by an // account several SolidPing users linked. OAuthCodeTelegramAmbiguous = "TELEGRAM_AMBIGUOUS" // OAuthDescTelegramAmbiguous is its user-facing description. OAuthDescTelegramAmbiguous = "This Telegram account is linked to several SolidPing accounts. " + "Sign in from your organization's login page, or another way." // OAuthCodeTelegramExpired is the error code of a stale login result. OAuthCodeTelegramExpired = "TELEGRAM_AUTH_EXPIRED" // OAuthDescTelegramExpired is its user-facing description. OAuthDescTelegramExpired = "The Telegram sign-in expired, please try again" // OAuthCodeTelegramInvalid is the error code of a login result whose // signature does not verify. OAuthCodeTelegramInvalid = "TELEGRAM_AUTH_INVALID" // OAuthDescTelegramInvalid is its user-facing description. OAuthDescTelegramInvalid = "The Telegram sign-in could not be verified" )
const AAGUIDLabelSecurityKey = "Security key"
AAGUIDLabelSecurityKey is the fallback label shown for passkeys whose AAGUID is missing or unrecognized — ergonomic enough to ship while the lookup table grows.
const CookieAuthToken = "access_token"
CookieAuthToken is the name of the cookie used for storing the access token.
const DemoWriteMessage = "This is the shared live demo. " +
"Only checks you create here can be changed — sign up free to change anything else."
DemoWriteMessage is the human half of every DEMO_READ_ONLY response. It says what the session IS rather than what it lacks, and names the one thing it can still do, so a curl user or a CLI reading only the JSON body understands why a perfectly valid credential was refused (a bare "Forbidden" would read as a permission bug).
The wording has to be true for BOTH refusal paths that reuse it: the route-level guard here (an endpoint entirely outside the allowlist) and the ownership check in checks.ErrDemoReadOnly (an allowlisted endpoint refusing because this particular check was not created by this session). "Only checks you create here can be changed" covers both without contradicting either — see the dashboard's localized org:demo.writeRefused key, which must stay in sync with this string.
const EventPATRevoked = "auth.patrevoked"
EventPATRevoked is broadcast with the revoked PAT's token hash as payload, so every replica evicts it from its cache. It must not contain '_': the Postgres notifier maps '.' to '_' in channel names and back.
const ImpersonationForbiddenMessage = "You are viewing the dashboard as another user. " +
"Their credentials, tokens and sessions cannot be changed from an impersonation session."
ImpersonationForbiddenMessage is the human half of every IMPERSONATION_FORBIDDEN response.
const ImpersonationTTL = 30 * time.Minute
ImpersonationTTL is the fixed lifetime of an impersonation token (spec 2026-09-29-03). There is no refresh: when it runs out the admin is back on their own session, so a forgotten tab cannot keep acting as someone else.
const PATForbiddenMessage = "A personal access token is bound to one organization. " +
"It cannot open a session, switch organization, or change how the account signs in: " +
"sign in to the dashboard, or with `sp auth login`, to do that."
PATForbiddenMessage is the human half of every PAT_FORBIDDEN response.
const PATTokenPrefix = "pat_"
PATTokenPrefix is the literal prefix every personal access token carries. It is what distinguishes a PAT from a session JWT without parsing either, both for validation routing here and for audit actor classification in middleware.actorTypeForToken.
const PasswordRotationMessage = "A password change is required before this account can be used. " +
"Rotate it with POST /api/v1/auth/change-password (or the dashboard's " +
"\"set a new password\" screen), then retry."
PasswordRotationMessage is the human half of every PASSWORD_CHANGE_REQUIRED response. It names the action and the endpoint, so a CLI user or a curl scripter reading only the JSON body knows what to do next — a bare "Forbidden" would leave them guessing which permission they lack.
const RoleSuperAdmin = "superadmin"
RoleSuperAdmin is the role value for super administrators.
const (
SignupMethodSlack = "slack"
)
Signup method labels attached to the user_signed_up product event. These are deliberately low-cardinality, non-identifying strings: the provider family, never a tenant name, issuer URL, directory DN or email domain.
SignupMethodSlack is exported because the Sign-in-with-Slack path lives in internal/integrations/slack and must use the same label — a second literal there could drift and split the metric in two.
Variables ¶
var ( // ErrDeviceAuthorizationPending means the human has not decided yet. ErrDeviceAuthorizationPending = errors.New("authorization_pending") // ErrDeviceSlowDown means the client polled faster than the advertised // interval. ErrDeviceSlowDown = errors.New("slow_down") // ErrDeviceExpiredToken means the device code is unknown, expired, or // already consumed — the three are deliberately indistinguishable. ErrDeviceExpiredToken = errors.New("expired_token") // ErrDeviceAccessDenied means the human denied the request. ErrDeviceAccessDenied = errors.New("access_denied") // ErrDeviceAuthNotFound means no live request carries that user code. ErrDeviceAuthNotFound = errors.New("device authorization request not found or expired") // ErrDeviceAuthAlreadyResolved means the request was already approved or // denied — consent is single-shot. ErrDeviceAuthAlreadyResolved = errors.New("device authorization request already responded to") // ErrDeviceClientNameTooLong rejects an oversized consent-page label. ErrDeviceClientNameTooLong = errors.New("client_name is too long") )
Device authorization errors. The four *Device* sentinels below map 1:1 onto the RFC 8628 §3.5 token-endpoint error codes.
var ( // ErrDiscordLinkStateInvalid covers an unknown, expired or already-redeemed // link token. One message for all three, so the public callback cannot be // used as an oracle for probing live tokens. ErrDiscordLinkStateInvalid = errors.New("this Discord link has expired") // ErrDiscordLinkClaimedByOther is returned when the Discord account is // already bound to a DIFFERENT SolidPing account. Two accounts cannot share // one snowflake: whoever got there first keeps it, because the alternative is // that completing this flow silently steals another member's paging route. ErrDiscordLinkClaimedByOther = errors.New("this Discord account is already linked to another user") )
Link-mode failures. All of them end as a redirect back to the dashboard with an error code, never as a session.
var ( ErrDiscordTokenExchange = errors.New("discord token exchange failed") ErrDiscordAPI = errors.New("discord API error") )
Discord OAuth specific errors.
var ( // ErrInvalidEmail: the new address is empty or not a plain address. // Mapped to 400 VALIDATION_ERROR. ErrInvalidEmail = errors.New("invalid email address") // ErrEmailChangeNoPassword: the account has no local password (it signs in // through OAuth, OIDC, SAML or LDAP), so there is nothing to re-verify the // caller with. Mapped to 403. ErrEmailChangeNoPassword = errors.New( "this account has no password: change your email address at your identity provider") // ErrEmailChangeDemo: the shared demo principal's address is fixed. ErrEmailChangeDemo = errors.New("the shared demo account's email address cannot be changed") // ErrEmailChangeNotSuperAdmin: the system endpoint's actor is not a super // admin. The route is already behind RequireSuperAdmin; this is the // service's own check. ErrEmailChangeNotSuperAdmin = errors.New("only a super admin can change another user's email") // ErrFirstLoginEmailNotAllowed: the change-password call carried an email // while the caller is not in the mustChangeEmail state. Mapped to 400. ErrFirstLoginEmailNotAllowed = errors.New( "an email can only be set here on the first login of the default admin: use your profile instead") // ErrDefaultEmailRefused: the new address is the published default one. // Mapped to 400. ErrDefaultEmailRefused = errors.New("choose an email address other than the default one") )
Email-change refusals (spec 2026-09-30-08).
var ( ErrGitHubTokenExchange = errors.New("github token exchange failed") ErrGitHubAPI = errors.New("github API error") )
GitHub OAuth specific errors.
var ( ErrGitLabTokenExchange = errors.New("gitlab token exchange failed") ErrGitLabAPI = errors.New("gitlab API error") // ErrGitLabLinkRequiresSignIn refuses a first GitLab sign-in whose email // matches an existing SolidPing account (GHSA-c7jr-53g7-65q8). The GitLab // instance admin controls the emails of every account on it, so even a // confirmed GitLab email does not prove the SolidPing account is the same // person's: the owner signs in with the method they already use instead. ErrGitLabLinkRequiresSignIn = errors.New("an account already uses this email: sign in with it first") )
GitLab OAuth specific errors.
var ( ErrGoogleTokenExchange = errors.New("google token exchange failed") ErrGoogleAPI = errors.New("google API error") )
Google OAuth specific errors.
var ( // ErrImpersonationDisabled: auth.impersonation_enabled is false. Mapped to // 404, as if the endpoint did not exist. ErrImpersonationDisabled = errors.New("impersonation is disabled") // ErrImpersonationNotSuperAdmin: the actor is not a super admin. The route // is already behind RequireSuperAdmin; this is the service's own check. ErrImpersonationNotSuperAdmin = errors.New("only a super admin can impersonate") // ErrImpersonationTargetSuperAdmin: no lateral moves between super admins. ErrImpersonationTargetSuperAdmin = errors.New("a super admin cannot be impersonated") // ErrImpersonationTargetSelf: impersonating yourself is meaningless. ErrImpersonationTargetSelf = errors.New("you cannot impersonate yourself") // ErrImpersonationChained: the caller's own credential is an impersonation // token. ErrImpersonationChained = errors.New("an impersonation session cannot start another impersonation") // ErrImpersonationTargetDemo: the shared public-demo principal has nothing // to reproduce and is guarded by its own rules. ErrImpersonationTargetDemo = errors.New("the shared demo account cannot be impersonated") // ErrImpersonationTargetNotMember: the target does not belong to the // requested org, or belongs to no org at all. Mapped to 404. ErrImpersonationTargetNotMember = errors.New("the user is not a member of this organization") // ErrImpersonationForbidden: something an impersonation token must never // do (mint a session, change a credential). Mapped to 403 // IMPERSONATION_FORBIDDEN. ErrImpersonationForbidden = errors.New("not allowed while impersonating a user") )
Impersonation refusals. Each is its own error so the handler maps it to the right status and so the tests can tell one refusal from another.
var ( ErrLDAPNotConfigured = errors.New("LDAP bind authentication is not configured") // ErrLDAPEmptyPassword is returned when an empty password is submitted. // This is a security-critical guard, not a validation nicety — see // Authenticate's doc comment. ErrLDAPEmptyPassword = errors.New("empty password is never sent to an LDAP bind") ErrLDAPUserNotFound = errors.New("no matching LDAP directory entry") ErrLDAPAmbiguousUser = errors.New("more than one matching LDAP directory entry") ErrLDAPBindFailed = errors.New("LDAP bind failed") ErrLDAPSearchFailed = errors.New("LDAP search failed") ErrLDAPNoEmail = errors.New("LDAP entry has no usable email attribute") )
LDAP bind-authentication errors.
var ( ErrMicrosoftTokenExchange = errors.New("microsoft token exchange failed") ErrMicrosoftAPI = errors.New("microsoft API error") )
Microsoft OAuth specific errors.
var ( ErrOIDCNotConfigured = errors.New("generic OIDC provider is not configured") ErrOIDCDiscovery = errors.New("oidc discovery failed") ErrOIDCTokenExchange = errors.New("oidc token exchange failed") ErrOIDCNoIDToken = errors.New("oidc token response did not include an id_token") ErrOIDCTokenInvalid = errors.New("oidc id token validation failed") )
Generic OIDC specific errors.
var ( // ErrInvalidOrgName is returned when the requested name is empty or too long. ErrInvalidOrgName = errors.New("organization name is invalid") // ErrInvalidLogoURL is returned when the requested logo URL is not an // absolute http(s) URL of a reasonable length. ErrInvalidLogoURL = errors.New("organization logo URL is invalid") )
Organization-profile errors.
var ( // ErrPasskeyNotFound — the credential ID has no row, or the row was // soft-deleted. ErrPasskeyNotFound = errors.New("passkey not found") // ErrPasskeyVerificationFailed — the WebAuthn assertion did not // validate (bad signature, RP-ID mismatch, sign-count regression). ErrPasskeyVerificationFailed = errors.New("passkey verification failed") // ErrPasskeySessionExpired — the sealed session JWT is past its TTL // or invalid. ErrPasskeySessionExpired = errors.New("passkey session expired") // ErrPasskeyLastAuthMethod — removing this passkey would leave the // user with no way to sign in. ErrPasskeyLastAuthMethod = errors.New("passkey is the user's last auth method") // ErrWebAuthnNotConfigured — the server is missing or has rejected // the WebAuthn config (e.g. RP ID could not be derived from the // base URL). ErrWebAuthnNotConfigured = errors.New("webauthn is not configured on this server") )
Errors specific to the passkey path.
var ( ErrUnsupportedLocale = errors.New("locale must be one of en, fr, de, es, zh") ErrInvalidTimezone = errors.New("timezone must be an IANA zone name, e.g. Europe/Paris") ErrInvalidWindow = errors.New("dashboardWindow must be one of 24h, 7d, 30d") ErrInvalidGlanceRows = errors.New("glanceRows must be one of 10, 25, 50, 100") )
Preference validation errors (PATCH /auth/me answers 400 VALIDATION_ERROR).
var ( // ErrTooManyPendingRegistrations is returned when the client IP already // has auth.registration_max_pending_per_ip sign-ups waiting for // confirmation. It wraps ErrRateLimited, so the handler answers 429. ErrTooManyPendingRegistrations = fmt.Errorf("%w: too many unconfirmed registrations from this address", ErrRateLimited) // ErrRegistrationTooSoon is returned when the client IP already signed up // in the last minute. It wraps ErrRateLimited, so the handler answers 429. ErrRegistrationTooSoon = fmt.Errorf("%w: a registration from this address was sent less than a minute ago", ErrRateLimited) )
var ( ErrSAMLNotConfigured = errors.New("SAML SP is not configured") ErrSAMLIDPMetadata = errors.New("failed to fetch/parse SAML IdP metadata") ErrSAMLInvalidState = errors.New("invalid or expired SAML relay state") ErrSAMLAssertionInvalid = errors.New("SAML assertion validation failed") ErrSAMLNameIDNamespace = errors.New("SAML NameID does not come from the SAML assertion namespace") ErrSAMLNoEmail = errors.New("SAML assertion did not include a usable email address") ErrSAMLNoSSOEndpoint = errors.New("SAML IdP metadata has no HTTP-Redirect SSO endpoint") )
SAML specific errors.
var ( ErrInvalidCredentials = errors.New("invalid credentials") ErrUserNotFound = errors.New("user not found") ErrInvalidToken = errors.New("invalid token") ErrTokenExpired = errors.New("token expired") ErrOrganizationNotFound = errors.New("organization not found") ErrTokenNotFound = errors.New("token not found") ErrUnexpectedSigningMethod = errors.New("unexpected signing method") ErrRegistrationDisabled = errors.New("registration is not enabled") ErrEmailNotAllowed = errors.New("email does not match allowed pattern") ErrRegistrationExpired = errors.New("registration link has expired") ErrEmailAlreadyTaken = errors.New("email is already registered") ErrInvitationNotFound = errors.New("invitation not found") // ErrTooManyInvitations is returned when the org already has the maximum // number of live invitations (maxLiveInvitationsPerOrg, or its seat cap // when lower). ErrTooManyInvitations = errors.New("too many pending invitations") ErrInvitationExpired = errors.New("invitation has expired") ErrEmailMismatch = errors.New("email does not match invitation") // ErrInviteLoginRequired refuses an anonymous acceptance of an invitation // addressed to an existing account: the invite token alone is not proof of // being that account, since the inviter holds it (spec 2026-10-16-06). ErrInviteLoginRequired = errors.New("invitation is for an existing account: sign in as that account to accept it") // ErrInviteEmailMismatch refuses an acceptance by a signed-in caller who is // not the invited account. ErrInviteEmailMismatch = errors.New("invitation is addressed to another account") ErrOrgSlugTaken = errors.New("organization slug is already taken") ErrInvalidOrgSlug = errors.New("invalid organization slug") ErrPasswordResetExpired = errors.New("password reset link has expired or is invalid") // ErrDemoAccountNotResettable refuses a password reset aimed at the shared // public-demo account (spec 2026-09-06-02). Its password is published by // design; rotating it would lock every visitor out of the live demo, and // the reset endpoint is unauthenticated, so the demo write guard cannot // see it. ErrDemoAccountNotResettable = errors.New("the shared demo account's password cannot be reset") // ErrInvalidCurrentPassword is returned by ChangePassword when the caller // supplies a currentPassword that does not match the stored hash. Kept // distinct from ErrInvalidCredentials so the handler can emit the // field-specific INVALID_CURRENT_PASSWORD code. ErrInvalidCurrentPassword = errors.New("current password is incorrect") ErrInvalid2FACode = errors.New("invalid 2FA code") ErrInvalidRecoveryCode = errors.New("invalid recovery code") ErrTwoFAAlreadyEnabled = errors.New("2FA is already enabled") ErrTwoFANotEnabled = errors.New("2FA is not enabled") // ErrRateLimited is returned when a client exceeds the per-endpoint // rate limit. The handler maps this to HTTP 429. ErrRateLimited = errors.New("rate limit exceeded") // ErrInvalidAutoJoinRegex is returned when an admin tries to set a // dangerously broad registration email pattern. ErrInvalidAutoJoinRegex = errors.New("invalid auto-join regex pattern") // ErrInvalidEscalationPolicy is returned when the default-escalation-policy // UID does not reference a policy that exists in this org. ErrInvalidEscalationPolicy = errors.New("escalation policy not found in this organization") // ErrInvalidReminderInterval is returned when the org default reminder // interval is neither 0 (off) nor between 900 and 86400 seconds. ErrInvalidReminderInterval = errors.New( "reminderIntervalSeconds must be 0 (off) or between 900 and 86400 seconds (15 minutes to 24 hours)") // ErrAlreadyAMember is returned when a user tries to request membership // in an org they already belong to. ErrAlreadyAMember = errors.New("already a member of this organization") // ErrRequestPending is returned when a user re-requests membership // while a previous request is still pending. ErrRequestPending = errors.New("a membership request is already pending") // ErrRequestNotFound is returned when a membership request lookup fails. ErrRequestNotFound = errors.New("membership request not found") // ErrRequestCooldownActive is returned when a user re-requests // membership during the rejection cooldown window. ErrRequestCooldownActive = errors.New("membership request cooldown active") // ErrOrgNotAcceptingRequests is returned when the target org never admits // membership requests (the demo org, or the SaaS platform default org). ErrOrgNotAcceptingRequests = errors.New("this organization does not accept membership requests") )
Service errors.
var ( ErrInvalidOAuthState = errors.New("invalid or expired OAuth state") ErrSlackOAuthFailed = errors.New("slack OAuth exchange failed") ErrEmailNotVerified = errors.New("email not verified in Slack profile") ErrSlackTokenExchange = errors.New("token exchange failed") ErrSlackAPI = errors.New("slack API error") )
Slack OAuth specific errors.
var ( // ErrTelegramAuthInvalid means the login result failed the signature // check, or is missing the fields the check needs. ErrTelegramAuthInvalid = errors.New("telegram login data failed verification") // ErrTelegramAuthExpired means the login result is older than // telegramAuthMaxAge (or dated in the future): a replay, or a tab left // open far too long. ErrTelegramAuthExpired = errors.New("telegram login data expired") // ErrTelegramNotLinked means no SolidPing user has this Telegram account // as a verified contact. Telegram returns no email address, so there is // nothing to match or create an account with. ErrTelegramNotLinked = errors.New("telegram account not linked to any user") // ErrTelegramAmbiguous means several SolidPing users linked this same // Telegram account and the login named no org that would pick one. ErrTelegramAmbiguous = errors.New("telegram account linked to several users") )
Sign in with Telegram errors.
var ErrContactCodeNotSent = errors.New("the verification code could not be sent")
ErrContactCodeNotSent is returned when an email contact's verification code could not be queued (no job service, or an invalid address).
var ErrInvalidApp = errors.New("invalid app: must be one of dash0, dash")
ErrInvalidApp is returned when an invalid app value is provided. Since spec 2026-09-09-01 the two accepted values are equivalent — both resolve to config.DashboardBasePath — so this only guards the accepted-value set, it no longer selects a target application.
var ErrInvalidExpiresIn = errors.New("invalid expiresIn: must be one of 1h, 6h, 12h, 24h, 48h, 1w")
ErrInvalidExpiresIn is returned when an invalid expiresIn value is provided.
var ErrInvalidSetupToken = errors.New("2FA setup token is invalid or expired")
ErrInvalidSetupToken is returned by Confirm2FA when the setup token is missing, expired, for another user, or for another secret.
var ErrLocalLoginDisabled = errors.New("local login is disabled")
ErrLocalLoginDisabled is returned by every local-credential entry point (password and LDAP login, registration, password reset, password change) while auth.local_login.enabled is false (spec 2026-11-21-02). Passkeys, the federated providers, API tokens, the device flow and the MCP OAuth server are not local login and keep working.
var ( // ErrOrgSlugConfirmationMismatch is returned when the confirmation slug in // the delete request does not match the organization being deleted. ErrOrgSlugConfirmationMismatch = errors.New("organization slug confirmation does not match") )
Organization-deletion errors.
var ErrPATForbidden = errors.New("not allowed with a personal access token")
ErrPATForbidden is returned when a personal access token asks for something it must never do (spec 2026-10-28-01): mint a session, a token for another org, or change how the account signs in. Mapped to 403 PAT_FORBIDDEN.
var ErrReauthenticationRequired = errors.New("a recent sign-in is required for this action")
ErrReauthenticationRequired is returned when an account without a password asks to add a sign-in factor from a session whose primary sign-in is older than reauthSignInWindow (or unknown). The user must sign in again.
Functions ¶
func DecodeTelegramAuthResult ¶
DecodeTelegramAuthResult decodes the `tgAuthResult` value oauth.telegram.org appends to the return URL: base64 (standard or URL-safe, padded or not) of a JSON object. Numbers keep their exact text so the data-check string matches what Telegram signed.
func DemoAllowedRoutes ¶
func DemoAllowedRoutes() [][2]string
DemoAllowedRoutes returns the allowlist as (method, pattern) pairs. Exported for the route-table test in internal/app, which walks every registered non-GET route and asserts that everything outside this set is refused — that is what makes the allowlist a structural property rather than a promise.
func EmbedOriginsFromParam ¶
EmbedOriginsFromParam reads the statuspage.allowed_embed_origins parameter into its validated list. The read path is lenient (an entry that does not validate is dropped, see securityheaders.ParseEmbedOrigins), so a row written behind the API's back can never inject a CSP directive. Never nil, so the JSON field is always an array.
func FormatDeviceUserCode ¶
FormatDeviceUserCode inserts a dash at the midpoint of a canonical user code for display (WDJP4KXR -> WDJP-4KXR).
func ImpersonationForbiddenRoutes ¶
func ImpersonationForbiddenRoutes() [][2]string
ImpersonationForbiddenRoutes returns the denylist as (method, pattern) pairs, for the route-table test in internal/app that proves every entry names a route that really exists.
func InviteExpiresIn ¶
InviteExpiresIn words an expiresIn code (e.g. "24h") in loc for the invitation email: "24 hours", "24 heures", "24 Stunden". Falls back to the raw code for any value outside getAllowedInviteExpirations (defensive only: CreateInvitation validates the code first). Exported for the email preview.
func IsDemoWriteAllowed ¶
IsDemoWriteAllowed reports whether a demo session may perform this request.
routePattern is the router's RESOLVED pattern (httpx.RoutePattern), not the request path. An empty pattern — no chi route context, which in practice means the request never matched a registered route — is refused: the guard fails closed by construction, which is the entire point of an allowlist.
Safe methods pass unconditionally. GET/HEAD are the read-only demo; OPTIONS is a CORS preflight that carries no credentials and mutates nothing.
func IsImpersonationAllowed ¶
IsImpersonationAllowed reports whether an impersonation token may perform this request. Safe methods always pass: reading is the whole point.
func IsMCPCredentialRouteAllowed ¶
IsMCPCredentialRouteAllowed reports whether an MCP credential may perform this REST request. routePattern is chi's resolved pattern (httpx.RoutePattern), as for the demo and impersonation guards.
func IsPATAllowed ¶
IsPATAllowed reports whether a personal access token may perform this request. Safe methods always pass.
func IsPATCredential ¶
IsPATCredential reports whether the request authenticated with a personal access token.
func IsPasswordRotationExempt ¶
IsPasswordRotationExempt reports whether the request may proceed despite the caller's pending rotation.
The match is on the exact method and path — no prefix matching, so "/api/v1/auth/me/anything" is not exempt — with a trailing slash tolerated because chi treats "/auth/me" and "/auth/me/" as the same route. OPTIONS is exempt unconditionally: a CORS preflight carries no credentials and answering it reveals nothing.
func MCPCredentialAllowedRoutes ¶
func MCPCredentialAllowedRoutes() [][2]string
MCPCredentialAllowedRoutes returns the allowlist as (method, pattern) pairs, for the route-table test in internal/app that proves every entry names a route that really exists.
func NormalizeDeviceUserCode ¶
NormalizeDeviceUserCode canonicalizes a user-entered code: uppercased, with every character outside the alphabet (dashes, spaces, …) stripped. So "wdjp-4kxr", "WDJP 4KXR" and "WDJP4KXR" all resolve to the same stored code.
func NotifyUserRegistered ¶
NotifyUserRegistered raises the instance-level `user.registered` operator notice (spec 2026-09-03-01).
PRIVACY, deliberately different from the analytics capture above: this notice DOES carry the email address and the display name. That is not an oversight and must not be "fixed". Its only recipients are super admins, who can already read both in the users admin, and an operator who is told "somebody signed up" without being told who cannot welcome them or notice that the signup got stuck. The analytics event stays UID-only because it leaves the instance; this one never does.
Fire-and-forget: opsnotify.Notify cannot fail or block, so a signup can never fail because a messaging provider is down. Exported because Sign-in-with-Slack creates accounts from internal/integrations/slack, which has its own account-creation chokepoint. One function, so the two sites cannot drift into two different notices.
func PATForbiddenRoutes ¶
func PATForbiddenRoutes() [][2]string
PATForbiddenRoutes returns the denylist as (method, pattern) pairs, for the route-table test in internal/app that proves every entry names a real route.
func PasswordRotationRequired ¶
PasswordRotationRequired reports whether the authenticated principal must rotate its password before it may do anything else.
It is the single predicate every surface consults — the REST middleware (RequireAuth), the MCP resource server (RequireMCPAuth) and the realtime WebSocket handshake — so the rule cannot drift between them the way org authorization did before it was funneled through AuthorizeOrgAccess.
What it deliberately does NOT look at is who the user is. The seeded bootstrap admin is blocked because its row carries the flag, not because it is the seeded admin; an operator-forced reset on any ordinary user is blocked identically.
func RedirectWithHandoff ¶
func RedirectWithHandoff( writer http.ResponseWriter, req *http.Request, dbService db.Service, baseURL string, outcome *ProviderOutcome, returnTo string, ) error
RedirectWithHandoff stores the outcome's session under a single-use handoff code and redirects the browser to the dashboard's handoff route with that code — never with a token. It also sets the SPA session cookie, as every federated callback did before (the embedded MCP OAuth consent flow authenticates with it); a pending session is either org-less or scoped to an org the user already belongs to, so that cookie never grants anything on the org that refused the login.
It is exported for callbacks that live outside this package (the Slack app-install callback). baseURL, when set, makes the target absolute; callers that redirect within the same origin pass "". returnTo is where the dashboard should land afterwards, subject to its own guards; a value that is not a same-origin relative path is replaced by the org's default landing before it is sealed (sanitizePostLoginRedirect), whoever the caller is.
On error nothing has been written to the response: the caller decides how to report the failure.
func RequireSSOProvider ¶
func RequireSSOProvider(cfg *config.Config, provider string) httpx.Middleware
RequireSSOProvider guards the always-mounted /auth/<provider> routes (spec 2026-11-25-02): each request reads the live SSO snapshot and answers 404 while the provider is not configured, so a provider saved on Server Settings > Authentication works without a restart, and one switched off stops at once.
func ResolveLinkedOrganization ¶
func ResolveLinkedOrganization( ctx context.Context, dbSvc db.Service, providerType models.ProviderType, providerID string, link *models.OrganizationProvider, ) (*models.Organization, error)
ResolveLinkedOrganization returns the organization behind a live organization_providers row.
It returns (org, nil) when the link resolves, (nil, nil) when the link was stale and has been cleared — the caller must then fall through to creating a fresh organization — and (nil, err) for anything else.
func ResolveLinkedUser ¶
func ResolveLinkedUser( ctx context.Context, dbSvc db.Service, providerType models.ProviderType, providerID string, link *models.UserProvider, ) (*models.User, error)
ResolveLinkedUser returns the user behind a live user_providers row.
It returns (user, nil) when the link resolves, (nil, nil) when the link was stale and has been cleared — the caller must then fall through to its email lookup / create path — and (nil, err) for anything else.
func ResolvedOrgFromContext ¶
func ResolvedOrgFromContext(ctx context.Context, slug string) *models.Organization
ResolvedOrgFromContext returns the memoized organization when it matches the requested slug, or nil when the caller must query the database.
func WithPATCredential ¶
WithPATCredential marks the request context as authenticated by a personal access token. Called by RequireAuth. Its own key, like the impersonator, so no later rewrite of the audit actor can drop it.
func WithResolvedOrg ¶
WithResolvedOrg memoizes an organization loaded by slug on the request context. middleware.OrgSlugRedirect has to resolve the :org slug before the auth chain runs (to decide whether the request is hitting a renamed org's previous slug); memoizing the result keeps AuthorizeOrgAccess from repeating the very same query one middleware later.
The memo is per-request and keyed by slug, so it can never serve a different organization than a fresh lookup would have.
func WriteReauthError ¶
func WriteReauthError( handler *base.HandlerBase, writer http.ResponseWriter, request *http.Request, err error, ) (bool, error)
WriteReauthError answers the errors of reauthenticateForFactor. It reports false when err is not one of them, so the caller falls through to its own mapping.
Types ¶
type AcceptInviteRequest ¶
type AcceptInviteRequest struct {
Token string `json:"token"`
Name string `json:"name"`
Password string `json:"password"`
// Locale and Timezone seed the preferences of an account created by the
// acceptance (an existing account keeps its own). Optional and lenient,
// like RegisterRequest's.
Locale string `json:"locale,omitempty"`
Timezone string `json:"timezone,omitempty"`
}
AcceptInviteRequest contains the request data for accepting an invitation.
type AdminUpdateUserRequest ¶
type AdminUpdateUserRequest struct {
Email *string `json:"email,omitempty"`
}
AdminUpdateUserRequest is the body of PATCH /api/v1/system/users/:uid. Every field is optional; only email exists today.
type AdminUpdateUserResponse ¶
type AdminUpdateUserResponse struct {
UID string `json:"uid"`
Email string `json:"email"`
Name string `json:"name"`
EmailVerified bool `json:"emailVerified"`
}
AdminUpdateUserResponse is the updated user, as the system directory shows it.
type AuthedUser ¶
type AuthedUser struct {
ID string `json:"id"`
Scope string `json:"scope"`
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
}
AuthedUser represents the authenticated user in OAuth response.
type ChangePasswordRequest ¶
type ChangePasswordRequest struct {
CurrentPassword string `json:"currentPassword"`
NewPassword string `json:"newPassword"`
Email string `json:"email,omitempty"`
}
ChangePasswordRequest is the body of POST /api/v1/auth/change-password.
CurrentPassword is required when the account already has a password, and ignored when it does not (the SSO-only "set a password" case).
Email is optional. It is accepted only while the caller is in the mustChangeEmail state (the seeded admin on the published default address, spec 2026-10-13-02), and is then written in the same UPDATE as the new password. Every other email change goes through PATCH /auth/me.
type ChangePasswordResponse ¶
type ChangePasswordResponse struct {
Message string `json:"message"`
}
ChangePasswordResponse confirms the rotation.
type Claims ¶
type Claims struct {
UserUID string `json:"userUid"`
OrgSlug string `json:"orgSlug"`
Role string `json:"role,omitempty"`
// Scopes lists fine-grained capabilities granted to this credential.
// Empty means "no scope restrictions" — the credential is treated as a
// full user session (back-compat for dashboard JWTs that pre-date scopes).
// Populated values gate access to specific subsystems; see e.g. the
// "mcp" / "mcp:read" scopes consumed by the MCP handler.
Scopes []string `json:"scopes,omitempty"`
// RefreshUID is the user_tokens.uid of the refresh-token row that issued
// this access token. Set on login and refresh so the sessions listing can
// flag the caller's own row (isCurrent) and "sign out other sessions" can
// spare it. Empty for PAT-validated claims and 2FA temp tokens — neither
// is minted from a refresh-token row.
RefreshUID string `json:"refreshUid,omitempty"`
// Demo marks a session belonging to the shared public-demo user
// (users.demo, spec 2026-09-06-02). It rides in the token so the write
// guard in RequireAuth needs no extra lookup, and so a PAT issued by the
// demo user is a demo session too — which is what would make a published
// demo API key safe.
//
// omitempty: the field is only ever meaningful when true, and every
// ordinary session's token stays byte-identical to what it was before.
Demo bool `json:"demo,omitempty"`
// ImpersonatedBy is the UID of the super admin who minted this token to
// act as UserUID (spec 2026-09-29-03). Set ONLY by Service.Impersonate,
// which never issues a refresh token, so the field lives exactly as long
// as the short-lived access token. When set, RequireSuperAdmin denies, the
// credential-changing surface answers IMPERSONATION_FORBIDDEN, no session
// can be minted from the request, and every audit row written under it
// carries the real actor.
//
// omitempty keeps every ordinary token byte-identical to before.
ImpersonatedBy string `json:"impersonatedBy,omitempty"`
// ClientID is the OAuth client an MCP access token was issued to (spec
// 2026-10-16-12). Empty on every other token. It lets RequireAuth tell the
// first-party CLI client from a third-party one; see IsMCPCredential.
ClientID string `json:"clientId,omitempty"`
// AuthTime is when (Unix seconds) the primary sign-in that opened this
// session happened (spec 2026-10-31-02). It survives refreshes and org
// switches, but never takes the time a refresh minted the token. A
// passwordless account may only add a sign-in factor while it is recent.
// 0 when unknown (sessions opened before the claim existed, impersonation,
// MCP and PAT credentials).
AuthTime int64 `json:"authTime,omitempty"`
jwt.RegisteredClaims
// contains filtered or unexported fields
}
Claims represents the JWT token claims of a bearer token (session access, impersonation, MCP access, or a validated PAT).
A JWT carrying a "purpose" claim is never a bearer: non-bearer tokens (2FA temp token, passkey sessions) are signed with a purpose-derived key through signJWT, and ValidateToken refuses any token with a purpose.
func (*Claims) HasOrgRole ¶
func (c *Claims) HasOrgRole(minRole models.MemberRole) bool
HasOrgRole reports whether the claims carry at least the given org role for the org the token is scoped to. Super admins always pass.
Use this instead of `claims.Role == "admin"`: with the owner role above admin (spec 2026-08-08-11) an equality check silently locks owners out of every admin surface, and enumerating `|| "owner"` at each call site is exactly the per-site drift the role hierarchy exists to prevent.
func (*Claims) IsImpersonation ¶
IsImpersonation reports whether these claims come from an impersonation token.
func (*Claims) IsMCPCredential ¶
IsMCPCredential reports whether these claims come from a credential whose consent is scoped to the MCP resource: an OAuth access token (it carries an `aud` and, since spec 2026-10-16-12, the client ID) or a PAT created with scopes. Keyed on `aud` too so tokens minted before the client ID claim existed are recognized.
func (*Claims) IsPAT ¶
IsPAT reports whether these claims were produced by ValidatePATToken, i.e. the request authenticated with a personal access token. The flag is an unexported field, so no signed JWT can claim it, nor shed it.
func (*Claims) IsSuperAdmin ¶
IsSuperAdmin returns true if the claims indicate a super admin.
type Confirm2FARequest ¶
Confirm2FARequest is the body of POST /auth/2fa/confirm.
type Confirm2FAResponse ¶
type Confirm2FAResponse struct {
RecoveryCodes []string `json:"recoveryCodes"`
}
Confirm2FAResponse contains the recovery codes after enabling 2FA.
type ConfirmRegistrationRequest ¶
type ConfirmRegistrationRequest struct {
Token string `json:"token"`
}
ConfirmRegistrationRequest contains the confirmation request data.
type Context ¶
type Context struct {
UserAgent string `json:"userAgent,omitempty"`
RemoteAddr string `json:"remoteAddr,omitempty"`
}
Context contains metadata about the authentication request.
type CreateOrgRequest ¶
type CreateOrgRequest struct {
Name string `json:"name"`
// Slug is OPTIONAL. Left empty, the server derives one from Name (or
// SlugBase, see below) via orgslug.GenerateUnique — a newcomer creating
// their first organization from /no-org should not have to invent a URL
// identifier before they can see a single check (spec 2026-09-05-01). A
// slug that IS supplied keeps the strict contract: invalid -> 422, already
// taken -> 409. Never silently "fix up" a slug the caller chose, or an API
// client would end up owning an org at an address it never asked for.
Slug string `json:"slug"`
// SlugBase is an OPTIONAL hint, consulted only when Slug is empty — a
// preferred candidate to derive the slug from instead of Name (spec
// 2026-09-07-01). /no-org sends the user's first name here: Name is a
// localized possessive sentence ("L'organisation de Florent") whose
// boilerplate prefix would otherwise dominate the 20-char slug cap and
// bury the one part that identifies the person.
//
// Unlike Slug, SlugBase is a HINT, not a claim: it goes through the same
// orgslug.Slugify + GenerateUnique pipeline as Name (normalized, capped,
// suffixed 2/3/... on collision) and is silently ignored — falling
// through to Name — when it normalizes to nothing usable. It never
// answers 422 or 409. When both Slug and SlugBase are sent, Slug wins and
// keeps its strict contract; SlugBase is ignored entirely.
SlugBase string `json:"slugBase"`
}
CreateOrgRequest contains the request data for creating an organization.
type CreateTokenRequest ¶
type CreateTokenRequest struct {
Name string `json:"name"`
ExpiresAt *time.Time `json:"expiresAt,omitempty"`
// Scopes restricts the capabilities of the token. Empty means the token
// inherits the user's full role (back-compat). See Claims.Scopes for the
// well-known values, e.g. "mcp" or "mcp:read".
Scopes []string `json:"scopes,omitempty"`
}
CreateTokenRequest contains the request data for creating a token.
type CreateTokenResponse ¶
type CreateTokenResponse struct {
UID string `json:"uid"`
Token string `json:"token"`
Name string `json:"name"`
ExpiresAt *time.Time `json:"expiresAt,omitempty"`
CreatedAt time.Time `json:"createdAt"`
}
CreateTokenResponse contains the response data for a created token.
type DeleteOrgRequest ¶
type DeleteOrgRequest struct {
Slug string `json:"slug"`
}
DeleteOrgRequest is the body of DELETE /api/v1/orgs/:org. The caller must re-type the org slug: deletion takes down every check, status page and session of the organization at once, so a bare DELETE with no payload is too easy to fire by accident (or by a stray script).
type DeviceAuthorizationRequestBody ¶
type DeviceAuthorizationRequestBody struct {
ClientName string `json:"clientName"`
ClientID string `json:"clientId"`
}
DeviceAuthorizationRequestBody is the body of POST /auth/device. clientName labels the request on the consent page; clientId is accepted for OAuth compatibility and ignored (solidping is not a multi-client authorization server on this endpoint).
type DeviceAuthorizationResponse ¶
type DeviceAuthorizationResponse struct {
DeviceCode string `json:"device_code"`
UserCode string `json:"user_code"`
VerificationURI string `json:"verification_uri"`
VerificationURIComplete string `json:"verification_uri_complete"`
ExpiresIn int `json:"expires_in"`
Interval int `json:"interval"`
}
DeviceAuthorizationResponse is the RFC 8628 §3.2 device authorization response. Field names are the RFC's, not the house camelCase style.
type DeviceConsentInfo ¶
type DeviceConsentInfo struct {
ClientName string `json:"clientName"`
UserCode string `json:"userCode"`
Status string `json:"status"`
ExpiresAt time.Time `json:"expiresAt"`
RequestedAt time.Time `json:"requestedAt"`
RequesterIP string `json:"requesterIp,omitempty"`
RequesterUserAgent string `json:"requesterUserAgent,omitempty"`
ApproverIP string `json:"approverIp,omitempty"`
}
DeviceConsentInfo is the public detail of a device-authorization request, safe to render on the (authenticated) consent page. It never carries the device code or the minted token.
RequestedAt, RequesterIP and RequesterUserAgent describe who opened the request, so a member can tell a sign-in they started from a code someone sent them (RFC 8628 §5.4, spec 2026-10-27-01). ApproverIP is the IP of the consent page's own caller, for a "different network" hint; the handler sets it.
type DeviceConsentRequest ¶
type DeviceConsentRequest struct {
UserCode string `json:"userCode"`
Org string `json:"org"`
Approve bool `json:"approve"`
}
DeviceConsentRequest is the body of POST /auth/device/consent. Org is the slug the approving user picked on the consent page — the minted PAT is bound to it, NOT implicitly to the session's org. Empty means "the session's org".
type DeviceRequester ¶
DeviceRequester describes the client opening a device-authorization request. IP must come from the trusted-proxy resolution (base.ExtractTrustedClientIP), never from a raw forwarding header.
type DeviceTokenRequestBody ¶
type DeviceTokenRequestBody struct {
GrantType string `json:"grant_type"`
DeviceCode string `json:"device_code"`
ClientID string `json:"client_id"`
}
DeviceTokenRequestBody is the body of POST /auth/device/token. RFC 8628 names.
type DeviceTokenResponse ¶
type DeviceTokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
}
DeviceTokenResponse is the successful RFC 8628 §3.5 token response. The access token is a solidping PAT, so the client can use it as a normal bearer credential with no further exchange.
type Disable2FARequest ¶
type Disable2FARequest struct {
Code string `json:"code"`
}
Disable2FARequest contains the request data for disabling 2FA.
type DiscordGuild ¶
type DiscordGuild struct {
ID string `json:"id"`
Name string `json:"name"`
Icon string `json:"icon"`
}
DiscordGuild represents a guild from Discord's /users/@me/guilds endpoint.
type DiscordOAuthHandler ¶
type DiscordOAuthHandler struct {
base.HandlerBase
// contains filtered or unexported fields
}
DiscordOAuthHandler handles Discord OAuth authentication endpoints.
func NewDiscordOAuthHandler ¶
func NewDiscordOAuthHandler( service *DiscordOAuthService, cfg *config.Config, ) *DiscordOAuthHandler
NewDiscordOAuthHandler creates a new Discord OAuth handler.
func (*DiscordOAuthHandler) Callback ¶
func (h *DiscordOAuthHandler) Callback(writer http.ResponseWriter, req *http.Request) error
Callback handles the OAuth callback from Discord. GET /api/v1/auth/discord/callback?code=...&state=...
func (*DiscordOAuthHandler) Login ¶
func (h *DiscordOAuthHandler) Login(writer http.ResponseWriter, req *http.Request) error
Login initiates the Discord OAuth flow. GET /api/v1/auth/discord/login?redirect_uri=...
type DiscordOAuthResult ¶
type DiscordOAuthResult = ProviderOutcome
DiscordOAuthResult contains the result of a successful Discord OAuth flow. It is the ProviderOutcome every federated callback hands to finishProviderCallback.
type DiscordOAuthService ¶
type DiscordOAuthService struct {
// contains filtered or unexported fields
}
DiscordOAuthService handles Discord OAuth authentication logic.
func NewDiscordOAuthService ¶
func NewDiscordOAuthService( dbService db.Service, cfg *config.Config, authService *Service, ) *DiscordOAuthService
NewDiscordOAuthService creates a new Discord OAuth service.
func (*DiscordOAuthService) GenerateOAuthState ¶
func (s *DiscordOAuthService) GenerateOAuthState( ctx context.Context, redirectURI string, ) (string, error)
GenerateOAuthState creates a new OAuth state and stores it in the database.
func (*DiscordOAuthService) HandleCallback ¶
func (s *DiscordOAuthService) HandleCallback( ctx context.Context, code string, ) (*DiscordOAuthResult, error)
HandleCallback processes the OAuth callback from Discord.
func (*DiscordOAuthService) LinkDiscordProvider ¶
func (s *DiscordOAuthService) LinkDiscordProvider( ctx context.Context, userUID, orgUID, discordUserID string, ) error
LinkDiscordProvider binds a Discord snowflake to an existing SolidPing user, idempotently.
Already bound to this user — nothing to do. Already bound to someone else — refused: the first binding wins, because overwriting it would move another member's Discord paging route onto this account without telling either of them.
A new binding is a new way to sign in to the account, so the owner gets a "Discord account linked" notice (spec 2026-11-01-03). orgUID is the org whose account page started the link; it only shapes the notice's link.
func (*DiscordOAuthService) ValidateOAuthState ¶
func (s *DiscordOAuthService) ValidateOAuthState( ctx context.Context, stateParam string, ) (*OAuthState, error)
ValidateOAuthState validates and consumes an OAuth state.
type DiscordTokenResponse ¶
type DiscordTokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
Scope string `json:"scope"`
}
DiscordTokenResponse represents the response from Discord's token exchange.
type DiscordUserInfo ¶
type DiscordUserInfo struct {
ID string `json:"id"`
Username string `json:"username"`
Discriminator string `json:"discriminator"`
GlobalName string `json:"global_name"`
Email string `json:"email"`
Verified bool `json:"verified"`
Avatar string `json:"avatar"`
}
DiscordUserInfo represents user info from Discord's /users/@me endpoint.
func (*DiscordUserInfo) AvatarURL ¶
func (u *DiscordUserInfo) AvatarURL() string
AvatarURL returns the Discord CDN URL for the user's avatar.
func (*DiscordUserInfo) DisplayName ¶
func (u *DiscordUserInfo) DisplayName() string
DisplayName returns the user's display name, preferring global name over username.
type EntitlementsChecker ¶
type EntitlementsChecker interface {
// CheckMembership returns a non-nil error (wrapping
// entitlements.ErrEntitlementExceeded) when adding another member to
// orgUID would breach the MaxUsers cap.
CheckMembership(ctx context.Context, orgUID string) error
}
EntitlementsChecker is the slice of the entitlements service the auth package needs. Defined as an interface so we can stub it in tests without dragging the full service in.
type GitHubEmail ¶
type GitHubEmail struct {
Email string `json:"email"`
Primary bool `json:"primary"`
Verified bool `json:"verified"`
}
GitHubEmail represents an email from GitHub's user/emails endpoint.
type GitHubOAuthHandler ¶
type GitHubOAuthHandler struct {
base.HandlerBase
// contains filtered or unexported fields
}
GitHubOAuthHandler handles GitHub OAuth authentication endpoints.
func NewGitHubOAuthHandler ¶
func NewGitHubOAuthHandler(service *GitHubOAuthService, cfg *config.Config) *GitHubOAuthHandler
NewGitHubOAuthHandler creates a new GitHub OAuth handler.
func (*GitHubOAuthHandler) Callback ¶
func (h *GitHubOAuthHandler) Callback(writer http.ResponseWriter, req *http.Request) error
Callback handles the OAuth callback from GitHub. GET /api/v1/auth/github/callback?code=...&state=...
func (*GitHubOAuthHandler) Login ¶
func (h *GitHubOAuthHandler) Login(writer http.ResponseWriter, req *http.Request) error
Login initiates the GitHub OAuth flow. GET /api/v1/auth/github/login?org=...&redirect_uri=...
type GitHubOAuthResult ¶
type GitHubOAuthResult = ProviderOutcome
GitHubOAuthResult contains the result of a successful GitHub OAuth flow. It is the ProviderOutcome every federated callback hands to finishProviderCallback.
type GitHubOAuthService ¶
type GitHubOAuthService struct {
// contains filtered or unexported fields
}
GitHubOAuthService handles GitHub OAuth authentication logic.
func NewGitHubOAuthService ¶
func NewGitHubOAuthService(dbService db.Service, cfg *config.Config, authService *Service) *GitHubOAuthService
NewGitHubOAuthService creates a new GitHub OAuth service.
func (*GitHubOAuthService) GenerateOAuthState ¶
func (s *GitHubOAuthService) GenerateOAuthState(ctx context.Context, redirectURI, orgSlug string) (string, error)
GenerateOAuthState creates a new OAuth state and stores it in the database.
func (*GitHubOAuthService) HandleCallback ¶
func (s *GitHubOAuthService) HandleCallback(ctx context.Context, code, orgSlug string) (*GitHubOAuthResult, error)
HandleCallback processes the OAuth callback from GitHub.
func (*GitHubOAuthService) ValidateOAuthState ¶
func (s *GitHubOAuthService) ValidateOAuthState(ctx context.Context, stateParam string) (*OAuthState, error)
ValidateOAuthState validates and consumes an OAuth state.
type GitHubTokenResponse ¶
type GitHubTokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
Scope string `json:"scope"`
Error string `json:"error,omitempty"`
ErrorDesc string `json:"error_description,omitempty"`
}
GitHubTokenResponse represents the response from GitHub's token exchange.
type GitHubUserInfo ¶
type GitHubUserInfo struct {
ID int `json:"id"`
Login string `json:"login"`
Name string `json:"name"`
Email string `json:"email"`
AvatarURL string `json:"avatar_url"` //nolint:tagliatelle // GitHub API uses snake_case
}
GitHubUserInfo represents user info from GitHub's user endpoint.
type GitLabEmail ¶
type GitLabEmail struct {
ID int `json:"id"`
Email string `json:"email"`
ConfirmedAt *string `json:"confirmed_at"`
}
GitLabEmail is one entry of GitLab's /api/v4/user/emails endpoint.
type GitLabOAuthHandler ¶
type GitLabOAuthHandler struct {
base.HandlerBase
// contains filtered or unexported fields
}
GitLabOAuthHandler handles GitLab OAuth authentication endpoints.
func NewGitLabOAuthHandler ¶
func NewGitLabOAuthHandler(service *GitLabOAuthService, cfg *config.Config) *GitLabOAuthHandler
NewGitLabOAuthHandler creates a new GitLab OAuth handler.
func (*GitLabOAuthHandler) Callback ¶
func (h *GitLabOAuthHandler) Callback(writer http.ResponseWriter, req *http.Request) error
Callback handles the OAuth callback from GitLab. GET /api/v1/auth/gitlab/callback?code=...&state=...
func (*GitLabOAuthHandler) Login ¶
func (h *GitLabOAuthHandler) Login(writer http.ResponseWriter, req *http.Request) error
Login initiates the GitLab OAuth flow. GET /api/v1/auth/gitlab/login?org=...&redirect_uri=...
type GitLabOAuthResult ¶
type GitLabOAuthResult = ProviderOutcome
GitLabOAuthResult contains the result of a successful GitLab OAuth flow. It is the ProviderOutcome every federated callback hands to finishProviderCallback.
type GitLabOAuthService ¶
type GitLabOAuthService struct {
// contains filtered or unexported fields
}
GitLabOAuthService handles GitLab OAuth authentication logic.
func NewGitLabOAuthService ¶
func NewGitLabOAuthService( dbService db.Service, cfg *config.Config, authService *Service, ) *GitLabOAuthService
NewGitLabOAuthService creates a new GitLab OAuth service.
func (*GitLabOAuthService) GenerateOAuthState ¶
func (s *GitLabOAuthService) GenerateOAuthState( ctx context.Context, redirectURI, orgSlug string, ) (string, error)
GenerateOAuthState creates a new OAuth state and stores it in the database.
func (*GitLabOAuthService) HandleCallback ¶
func (s *GitLabOAuthService) HandleCallback( ctx context.Context, code, orgSlug string, ) (*GitLabOAuthResult, error)
HandleCallback processes the OAuth callback from GitLab.
func (*GitLabOAuthService) ValidateOAuthState ¶
func (s *GitLabOAuthService) ValidateOAuthState(ctx context.Context, stateParam string) (*OAuthState, error)
ValidateOAuthState validates and consumes an OAuth state.
type GitLabTokenResponse ¶
type GitLabTokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
RefreshToken string `json:"refresh_token"`
Scope string `json:"scope"`
Error string `json:"error,omitempty"`
ErrorDesc string `json:"error_description,omitempty"`
}
GitLabTokenResponse represents the response from GitLab's token exchange.
type GitLabUserInfo ¶
type GitLabUserInfo struct {
ID int `json:"id"`
Username string `json:"username"`
Name string `json:"name"`
Email string `json:"email"`
AvatarURL string `json:"avatar_url"`
// ConfirmedAt is when the GitLab account confirmed its email. Null or
// absent means unconfirmed: self-managed instances can run with email
// confirmation off or soft, and an admin can set any address.
ConfirmedAt *string `json:"confirmed_at"`
}
GitLabUserInfo represents user info from GitLab's /api/v4/user endpoint.
type GoogleOAuthHandler ¶
type GoogleOAuthHandler struct {
base.HandlerBase
// contains filtered or unexported fields
}
GoogleOAuthHandler handles Google OAuth authentication endpoints.
func NewGoogleOAuthHandler ¶
func NewGoogleOAuthHandler(service *GoogleOAuthService, cfg *config.Config) *GoogleOAuthHandler
NewGoogleOAuthHandler creates a new Google OAuth handler.
func (*GoogleOAuthHandler) Callback ¶
func (h *GoogleOAuthHandler) Callback(writer http.ResponseWriter, req *http.Request) error
Callback handles the OAuth callback from Google. GET /api/v1/auth/google/callback?code=...&state=...
func (*GoogleOAuthHandler) Login ¶
func (h *GoogleOAuthHandler) Login(writer http.ResponseWriter, req *http.Request) error
Login initiates the Google OAuth flow. GET /api/v1/auth/google/login?org=...&redirect_uri=...
type GoogleOAuthResult ¶
type GoogleOAuthResult = ProviderOutcome
GoogleOAuthResult contains the result of a successful Google OAuth flow. It is the ProviderOutcome every federated callback hands to finishProviderCallback.
type GoogleOAuthService ¶
type GoogleOAuthService struct {
// contains filtered or unexported fields
}
GoogleOAuthService handles Google OAuth authentication logic.
func NewGoogleOAuthService ¶
func NewGoogleOAuthService(dbService db.Service, cfg *config.Config, authService *Service) *GoogleOAuthService
NewGoogleOAuthService creates a new Google OAuth service.
func (*GoogleOAuthService) GenerateOAuthState ¶
func (s *GoogleOAuthService) GenerateOAuthState(ctx context.Context, redirectURI, orgSlug string) (string, error)
GenerateOAuthState creates a new OAuth state and stores it in the database.
func (*GoogleOAuthService) HandleCallback ¶
func (s *GoogleOAuthService) HandleCallback(ctx context.Context, code, orgSlug string) (*GoogleOAuthResult, error)
HandleCallback processes the OAuth callback from Google.
func (*GoogleOAuthService) ValidateOAuthState ¶
func (s *GoogleOAuthService) ValidateOAuthState(ctx context.Context, stateParam string) (*OAuthState, error)
ValidateOAuthState validates and consumes an OAuth state.
type GoogleTokenResponse ¶
type GoogleTokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
ExpiresIn int `json:"expires_in"`
IDToken string `json:"id_token,omitempty"`
Error string `json:"error,omitempty"`
ErrorDesc string `json:"error_description,omitempty"`
}
GoogleTokenResponse represents the response from Google's token exchange.
type GoogleUserInfo ¶
type GoogleUserInfo struct {
Sub string `json:"sub"`
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
Name string `json:"name"`
Picture string `json:"picture"`
}
GoogleUserInfo represents user info from Google's userinfo endpoint.
type Handler ¶
type Handler struct {
base.HandlerBase
// contains filtered or unexported fields
}
Handler provides HTTP handlers for authentication endpoints.
func NewHandler ¶
NewHandler creates a new authentication handler.
func (*Handler) AcceptInvite ¶
AcceptInvite accepts an invitation. Anonymous for a new invitee; an existing account must be signed in as itself (spec 2026-10-16-06).
func (*Handler) AdminUpdateUser ¶
AdminUpdateUser handles PATCH /api/v1/system/users/:uid (super admin only).
func (*Handler) ApproveMembershipRequestHandler ¶
func (h *Handler) ApproveMembershipRequestHandler( writer http.ResponseWriter, req *http.Request, ) error
ApproveMembershipRequestHandler — POST .../approve.
func (*Handler) CancelMembershipRequestHandler ¶
func (h *Handler) CancelMembershipRequestHandler( writer http.ResponseWriter, req *http.Request, ) error
CancelMembershipRequestHandler — DELETE /api/v1/auth/membership-requests/{uid}.
func (*Handler) ChangePassword ¶
ChangePassword rotates the authenticated caller's password (or sets an initial one for an SSO-only account). Unlike ResetPassword it needs no emailed token — the session is the proof of identity, plus the current password when the account has one.
func (*Handler) Confirm2FA ¶
Confirm2FA validates the TOTP code and enables 2FA, returning recovery codes.
func (*Handler) ConfirmRegistration ¶
ConfirmRegistration handles email confirmation for registration.
func (*Handler) CreateInvitation ¶
CreateInvitation handles invitation creation.
func (*Handler) CreateMembershipRequestHandler ¶
func (h *Handler) CreateMembershipRequestHandler( writer http.ResponseWriter, req *http.Request, ) error
CreateMembershipRequestHandler — POST /api/v1/auth/membership-requests.
func (*Handler) CreateToken ¶
CreateToken creates a new Personal Access Token. Org-scoped via URL param.
func (*Handler) DeleteOrg ¶
DeleteOrg handles DELETE /api/v1/orgs/:org. The route is owner-gated by middleware.RequireOrgOwner, so reaching this handler already proves the caller owns the org (or is a super admin); the body must additionally repeat the org slug as an explicit confirmation.
It answers 200 with a login-shaped session payload rather than a bare 204: the caller's old token names an org that no longer resolves, so the response carries the replacement session (scoped to a remaining org, or org-less when there is none) and refreshes the access-token cookie with it. This mirrors the org-rename path below, which re-issues tokens for the same reason.
func (*Handler) Disable2FA ¶
Disable2FA disables 2FA for the authenticated user.
func (*Handler) ExchangeHandoff ¶
ExchangeHandoff trades a single-use handoff code for the session a federated login callback minted. Public: the code is the credential.
POST /api/v1/auth/handoff/exchange body: {"code": "..."}.
A code that cannot be redeemed, for whatever reason, answers the same 401 body. The code is never logged.
func (*Handler) GetAllUserTokens ¶
GetAllUserTokens returns all tokens for the authenticated user across all orgs.
func (*Handler) GetDeviceConsent ¶
GetDeviceConsent returns the public details of a device-authorization request so the consent page can render them. Authenticated (the user code is the brute-forceable surface) and rate limited at the route level. GET /api/v1/auth/device/consent?userCode=WDJP-4KXR.
func (*Handler) GetInviteInfo ¶
GetInviteInfo returns public info about an invitation (no auth required).
func (*Handler) GetOrgSettings ¶
GetOrgSettings returns organization settings.
func (*Handler) GetOrgTokens ¶
GetOrgTokens returns the list of tokens for the authenticated user scoped to an org.
func (*Handler) Impersonate ¶
Impersonate handles POST /api/v1/system/users/:uid/impersonate. The route sits in the super-admin system group (RequireAuth + RequireSuperAdmin); the service re-checks everything anyway.
func (*Handler) ListInvitations ¶
ListInvitations lists pending invitations for an organization.
func (*Handler) ListOrgMembershipRequestsHandler ¶
func (h *Handler) ListOrgMembershipRequestsHandler( writer http.ResponseWriter, req *http.Request, ) error
ListOrgMembershipRequestsHandler — GET /api/v1/orgs/{org}/membership-requests.
func (*Handler) ListOwnMembershipRequestsHandler ¶
func (h *Handler) ListOwnMembershipRequestsHandler( writer http.ResponseWriter, req *http.Request, ) error
ListOwnMembershipRequestsHandler — GET /api/v1/auth/membership-requests.
func (*Handler) Login ¶
Login handles user login with email and password. Org is read from the request body (optional).
func (*Handler) Me ¶
Me returns information about the current authenticated user. Uses claims from middleware context.
func (*Handler) PollDeviceToken ¶
PollDeviceToken is the RFC 8628 token endpoint. Public and deliberately not given a stricter rate limit than the global one: a legitimate client polls it every few seconds for the request's whole TTL, and the device_code (32 random bytes) is the real capability — brute-forcing it is infeasible. Over-eager polling is answered with slow_down rather than 429. POST /api/v1/auth/device/token.
func (*Handler) Recovery2FA ¶
Recovery2FA uses a recovery code during login to complete authentication.
func (*Handler) Refresh ¶
Refresh handles token refresh. No org parameter needed — derived from refresh token.
func (*Handler) RejectMembershipRequestHandler ¶
func (h *Handler) RejectMembershipRequestHandler( writer http.ResponseWriter, req *http.Request, ) error
RejectMembershipRequestHandler — POST .../reject.
func (*Handler) RequestPasswordReset ¶
RequestPasswordReset handles password reset requests.
func (*Handler) ResetPassword ¶
ResetPassword handles setting a new password with a reset token.
func (*Handler) RespondToDeviceConsent ¶
RespondToDeviceConsent approves or denies a pending device-authorization request. Approval mints a real PAT owned by the approving user and scoped to the selected org, so this requires a full authenticated session. POST /api/v1/auth/device/consent.
func (*Handler) RevokeCurrentToken ¶
RevokeCurrentToken revokes the grant backing the caller's own credential — the "I'm done, drop my access" call. It targets the row named by Claims.RefreshUID, so it works for a session principal and, crucially, for an MCP/OAuth client authenticated with only its short-lived access token (which no longer holds the refresh token itself). Scoped-down tokens (mcp:read) may self-revoke too: dropping your own credential is never a privilege escalation. A credential with no backing grant row (PAT, 2FA temp token) has nothing to revoke here and gets a 422 validation error.
func (*Handler) RevokeInvitation ¶
RevokeInvitation revokes a pending invitation.
func (*Handler) RevokeToken ¶
RevokeToken revokes (deletes) a user token. User-scoped via middleware context.
func (*Handler) StartDeviceAuthorization ¶
StartDeviceAuthorization opens a device-authorization request. Public: it grants nothing until a logged-in user approves it. POST /api/v1/auth/device.
func (*Handler) UpdateMe ¶
UpdateMe updates the current user's profile. Uses claims from middleware context.
func (*Handler) UpdateOrgProfile ¶
UpdateOrgProfile handles PATCH /api/v1/orgs/:org. The route is owner-gated by middleware.RequireOrgOwner (an admin gets the standard 403, not a hidden button), so this handler only validates and translates errors.
On a slug rename the response carries a fresh org-scoped session, and the access-token cookie is refreshed with it — exactly like CreateOrg/SwitchOrg. Without that the dashboard's very next request, now addressed to the new slug, would 403 on the token-scope check.
func (*Handler) UpdateOrgSettings ¶
UpdateOrgSettings updates organization settings.
type HandoffExchangeRequest ¶
type HandoffExchangeRequest struct {
Code string `json:"code"`
}
HandoffExchangeRequest is the body of POST /api/v1/auth/handoff/exchange.
type HandoffExchangeResponse ¶
type HandoffExchangeResponse struct {
LoginResponse
// ReturnTo is the path the login was started from, or a landing page the
// callback chose (the Slack install's channel). The dashboard only follows
// it through its own same-origin / same-org guards.
ReturnTo string `json:"returnTo,omitempty"`
// MembershipPending names the org that did not admit the user yet, for the
// no-org page. Empty when no join request was opened.
MembershipPending string `json:"membershipPending,omitempty"`
// RoleChanges are the login diagnostics of the IdP group claim: the roles
// it granted or revoked during this login (super_admin_granted,
// super_admin_revoked, org_admin_granted, ...). Empty when none.
RoleChanges []string `json:"roleChanges,omitempty"`
}
HandoffExchangeResponse is the login-shaped answer to a redeemed handoff code: exactly what a password login returns (so the dashboard feeds it to the same applyLoginResponse), plus where to land.
type ImpersonateRequest ¶
type ImpersonateRequest struct {
// OrgSlug is the organization to view the dashboard in. Optional: the
// target's default organization is used when empty.
OrgSlug string `json:"orgSlug,omitempty"`
}
ImpersonateRequest is the body of POST /api/v1/system/users/:uid/impersonate.
type ImpersonationInfo ¶
type ImpersonationInfo struct {
// ImpersonatorUID is the super admin acting as the user.
ImpersonatorUID string `json:"impersonatorUid"`
// ImpersonatorEmail is their email, for the banner. Empty if the admin's
// row can no longer be read.
ImpersonatorEmail string `json:"impersonatorEmail,omitempty"`
// ExpiresAt is when the impersonation token stops working.
ExpiresAt *time.Time `json:"expiresAt,omitempty"`
}
ImpersonationInfo describes the impersonation behind the caller's token on /auth/me.
type InviteInfoResponse ¶
type InviteInfoResponse struct {
OrgName string `json:"orgName"`
OrgSlug string `json:"orgSlug"`
Role string `json:"role"`
Email string `json:"email"`
}
InviteInfoResponse contains public info about an invitation.
type InviteListItem ¶
type InviteListItem struct {
UID string `json:"uid"`
Email string `json:"email"`
Role string `json:"role"`
ExpiresAt *time.Time `json:"expiresAt,omitempty"`
CreatedAt time.Time `json:"createdAt"`
}
InviteListItem represents an invitation in a list response.
type InviteListResponse ¶
type InviteListResponse struct {
Data []InviteListItem `json:"data"`
}
InviteListResponse contains a list of invitations.
type InviteRequest ¶
type InviteRequest struct {
Email string `json:"email"`
Role string `json:"role"`
ExpiresIn string `json:"expiresIn"` // "1h", "6h", "12h", "24h", "48h", "1w" (default: "24h")
// App selects the target application. Both accepted values now resolve to
// the one remaining dashboard (config.DashboardBasePath); it is kept only
// so existing API clients keep working.
App string `json:"app"` // "dash0" or "dash" (default: "dash0")
}
InviteRequest contains the request data for creating an invitation.
type InviteResponse ¶
type InviteResponse struct {
UID string `json:"uid"`
Token string `json:"token"`
Email string `json:"email"`
Role string `json:"role"`
InviteURL string `json:"inviteUrl"`
ExpiresAt time.Time `json:"expiresAt"`
// EmailSent reports whether the invitation email was queued for
// delivery — NOT confirmation that it reached an inbox, since delivery
// itself is async (job type "email"). False when email sending is
// disabled instance-wide, or when enqueueing the job failed; either way
// the dashboard must treat InviteURL as the only channel.
EmailSent bool `json:"emailSent"`
}
InviteResponse contains the response after creating an invitation.
type LDAPService ¶
type LDAPService struct {
// contains filtered or unexported fields
}
LDAPService performs LDAP/Active Directory bind authentication for the password-login path (spec 2026-07-08-08, part 3 — global-only, single connector; see config.LDAPConfig). It carries no state beyond the config snapshot it was built with — every Authenticate call opens its own connection, so a super-admin config edit takes effect on the very next login attempt, with no cache to invalidate.
func NewLDAPService ¶
func NewLDAPService(cfg *config.Config) *LDAPService
NewLDAPService creates a new LDAP bind-authentication service.
func (*LDAPService) Authenticate ¶
func (s *LDAPService) Authenticate(ctx context.Context, identifier, password string) (*LDAPUserInfo, error)
Authenticate performs a search-then-bind against the configured directory: bind as the service account (or anonymously, when BindDN is blank), search for exactly one entry matching the submitted identifier via a filter built with RFC 4515 escaping (see buildUserFilter), then bind as that entry's DN with the submitted password — the step that actually verifies it.
SECURITY — empty password / "unauthenticated bind": per RFC 4513 §5.1.2, an LDAP bind carrying a valid DN and an EMPTY password is defined as an "unauthenticated bind", which servers may accept as a SUCCESS without checking any credential at all. If this function ever reached the final user-bind step with password == "", an attacker could authenticate as any directory entry our search could find, with zero knowledge of its real password. The guard below is therefore the load-bearing control, not a nicety, and it runs first — before any network I/O at all, i.e. before the service-account bind and the search, not just before the user bind. It does not depend on: (a) the go-ldap client's own default refusal (Conn.Bind already rejects an empty password unless AllowEmptyPassword is explicitly set, which this code never does), or (b) the directory rejecting it — a misconfigured or permissive directory that *would* honor an unauthenticated bind is still safe against this code, because the bind is simply never attempted.
func (*LDAPService) Enabled ¶
func (s *LDAPService) Enabled() bool
Enabled reports whether LDAP bind auth is usable: enabled and minimally configured (server + base DN present).
type LDAPUserInfo ¶
LDAPUserInfo is what we learn about a directory entry after a successful search-then-bind: the entry's DN (used as the stable UserProvider identifier) and the mapped email/name attributes (used as the local User's identity — see Service.findOrCreateLDAPUser).
type LoginAction ¶
type LoginAction string
LoginAction describes how the frontend should handle the login result.
const ( // LoginActionDefault means normal login to the requested or resolved org. LoginActionDefault LoginAction = "" // LoginActionOrgRedirect means the user was redirected to their only available org. LoginActionOrgRedirect LoginAction = "orgRedirect" // LoginActionOrgChoice means the user has multiple orgs and must choose. LoginActionOrgChoice LoginAction = "orgChoice" // LoginActionNoOrg means the user has no organizations. LoginActionNoOrg LoginAction = "noOrg" )
type LoginBeginResponse ¶
type LoginBeginResponse struct {
Options *protocol.CredentialAssertion `json:"options"`
Session string `json:"session"`
}
LoginBeginResponse is the wire shape of POST /auth/passkeys/login/begin.
type LoginOption ¶
type LoginOption func(*loginOptions)
LoginOption carries a provider-verified fact about the login being completed into the shared admission policy. Connectors that have nothing to attest pass none, which leaves every attestation-driven rule inert.
func WithLoginMethod ¶
func WithLoginMethod(method string) LoginOption
WithLoginMethod names the connector completing this login, for the audit trail. Every federated connector should pass one — without it their sign-ins are all recorded as the generic "oauth".
func WithSlackWorkspace ¶
func WithSlackWorkspace(teamID string) LoginOption
WithSlackWorkspace attests that the user completing this login is a member of the given Slack workspace (team ID), as proven by a Slack OAuth token exchange this server performed itself.
func WithoutOrgBootstrap ¶
func WithoutOrgBootstrap() LoginOption
WithoutOrgBootstrap disables the "first member of an empty org becomes its owner" admission rule for this login.
type LoginRequest ¶
type LoginRequest struct {
Org string `json:"org"`
Email string `json:"email"`
Password string `json:"password"`
}
LoginRequest represents a login request body.
type LoginResponse ¶
type LoginResponse struct {
AccessToken string `json:"accessToken,omitempty"`
RefreshToken string `json:"refreshToken,omitempty"`
ExpiresIn int `json:"expiresIn,omitempty"`
TokenType string `json:"tokenType,omitempty"`
User *UserInfo `json:"user,omitempty"`
Organization *OrganizationInfo `json:"organization,omitempty"`
Organizations []OrganizationSummary `json:"organizations,omitempty"`
LoginAction LoginAction `json:"loginAction,omitempty"`
Requires2FA bool `json:"requires2Fa,omitempty"`
TempToken string `json:"tempToken,omitempty"`
}
LoginResponse contains the response data for a successful login.
type LogoutRequest ¶
type LogoutRequest struct {
DeleteAllTokens bool `json:"deleteAllTokens"`
SignOutOthers bool `json:"signOutOthers"`
}
LogoutRequest represents a logout request body. DeleteAllTokens and SignOutOthers are mutually exclusive: the former ends every session (including the caller's own — a full logout), the latter spares the caller's own session (a "sign out other devices" action, not a logout).
type LogoutResponse ¶
type LogoutResponse struct {
Success bool `json:"success"`
TokensDeleted int `json:"tokensDeleted"`
}
LogoutResponse contains the response data for a logout operation.
type MeResponse ¶
type MeResponse struct {
User *UserInfo `json:"user"`
Organization *OrganizationInfo `json:"organization,omitempty"`
Organizations []OrganizationSummary `json:"organizations"`
TOTPEnabled bool `json:"totpEnabled"`
PasskeyCount int `json:"passkeyCount"`
HasPassword bool `json:"hasPassword"`
PendingMembershipRequests []MembershipRequestSummary `json:"pendingMembershipRequests,omitempty"`
// Impersonation is present only when the caller's token is a super-admin
// impersonation token (spec 2026-09-29-03), so every tab of the dashboard,
// including a freshly opened one, shows the "viewing as" banner.
Impersonation *ImpersonationInfo `json:"impersonation,omitempty"`
}
MeResponse contains the current user's information.
type MembershipRequestAdminListResponse ¶
type MembershipRequestAdminListResponse struct {
Data []MembershipRequestAdminView `json:"data"`
}
MembershipRequestAdminListResponse wraps admin-side list.
type MembershipRequestAdminView ¶
type MembershipRequestAdminView struct {
UID string `json:"uid"`
User UserInfo `json:"user"`
Status models.MembershipRequestStatus `json:"status"`
Message string `json:"message,omitempty"`
DecisionReason string `json:"decisionReason,omitempty"`
CreatedAt time.Time `json:"createdAt"`
DecidedAt *time.Time `json:"decidedAt,omitempty"`
}
MembershipRequestAdminView is what admins see — includes the requesting user's identity. Used in GET /api/v1/orgs/{org}/membership-requests.
type MembershipRequestApproveRequest ¶
type MembershipRequestApproveRequest struct {
Role string `json:"role,omitempty"`
}
MembershipRequestApproveRequest is the body of approve.
type MembershipRequestCreateRequest ¶
type MembershipRequestCreateRequest struct {
OrgSlug string `json:"orgSlug"`
Message string `json:"message,omitempty"`
}
MembershipRequestCreateRequest is the body of POST /api/v1/auth/membership-requests.
type MembershipRequestListResponse ¶
type MembershipRequestListResponse struct {
Data []MembershipRequestSummary `json:"data"`
}
MembershipRequestListResponse wraps the data array per API conventions.
type MembershipRequestRejectRequest ¶
type MembershipRequestRejectRequest struct {
Reason string `json:"reason,omitempty"`
}
MembershipRequestRejectRequest is the body of reject.
type MembershipRequestSummary ¶
type MembershipRequestSummary struct {
UID string `json:"uid"`
Organization OrganizationRef `json:"organization"`
Status models.MembershipRequestStatus `json:"status"`
Message string `json:"message,omitempty"`
DecisionReason string `json:"decisionReason,omitempty"`
CreatedAt time.Time `json:"createdAt"`
DecidedAt *time.Time `json:"decidedAt,omitempty"`
}
MembershipRequestSummary is the compact form returned on /auth/me and /auth/membership-requests for the requester to render their queue.
type MicrosoftOAuthHandler ¶
type MicrosoftOAuthHandler struct {
base.HandlerBase
// contains filtered or unexported fields
}
MicrosoftOAuthHandler handles Microsoft OAuth authentication endpoints.
func NewMicrosoftOAuthHandler ¶
func NewMicrosoftOAuthHandler(service *MicrosoftOAuthService, cfg *config.Config) *MicrosoftOAuthHandler
NewMicrosoftOAuthHandler creates a new Microsoft OAuth handler.
func (*MicrosoftOAuthHandler) Callback ¶
func (h *MicrosoftOAuthHandler) Callback(writer http.ResponseWriter, req *http.Request) error
Callback handles the OAuth callback from Microsoft. GET /api/v1/auth/microsoft/callback?code=...&state=...
func (*MicrosoftOAuthHandler) Login ¶
func (h *MicrosoftOAuthHandler) Login(writer http.ResponseWriter, req *http.Request) error
Login initiates the Microsoft OAuth flow. GET /api/v1/auth/microsoft/login?org=...&redirect_uri=...
type MicrosoftOAuthResult ¶
type MicrosoftOAuthResult = ProviderOutcome
MicrosoftOAuthResult contains the result of a successful Microsoft OAuth flow. It is the ProviderOutcome every federated callback hands to finishProviderCallback.
type MicrosoftOAuthService ¶
type MicrosoftOAuthService struct {
// contains filtered or unexported fields
}
MicrosoftOAuthService handles Microsoft OAuth authentication logic.
func NewMicrosoftOAuthService ¶
func NewMicrosoftOAuthService(dbService db.Service, cfg *config.Config, authService *Service) *MicrosoftOAuthService
NewMicrosoftOAuthService creates a new Microsoft OAuth service.
func (*MicrosoftOAuthService) GenerateOAuthState ¶
func (s *MicrosoftOAuthService) GenerateOAuthState(ctx context.Context, redirectURI, orgSlug string) (string, error)
GenerateOAuthState creates a new OAuth state and stores it in the database.
func (*MicrosoftOAuthService) HandleCallback ¶
func (s *MicrosoftOAuthService) HandleCallback( ctx context.Context, code, orgSlug string, ) (*MicrosoftOAuthResult, error)
HandleCallback processes the OAuth callback from Microsoft.
func (*MicrosoftOAuthService) ValidateOAuthState ¶
func (s *MicrosoftOAuthService) ValidateOAuthState(ctx context.Context, stateParam string) (*OAuthState, error)
ValidateOAuthState validates and consumes an OAuth state.
type MicrosoftTokenResponse ¶
type MicrosoftTokenResponse struct {
AccessToken string `json:"access_token"`
TokenType string `json:"token_type"`
Scope string `json:"scope"`
ExpiresIn int `json:"expires_in"`
IDToken string `json:"id_token,omitempty"`
Error string `json:"error,omitempty"`
ErrorDesc string `json:"error_description,omitempty"`
}
MicrosoftTokenResponse represents the response from Microsoft's token exchange.
type MicrosoftUserInfo ¶
type MicrosoftUserInfo struct {
ID string `json:"id"`
DisplayName string `json:"displayName"`
Mail string `json:"mail"`
UserPrincipalName string `json:"userPrincipalName"`
}
MicrosoftUserInfo represents user info from Microsoft Graph /me endpoint.
type OAuthLoginResponse ¶
type OAuthLoginResponse struct {
AccessToken string `json:"accessToken"`
RefreshToken string `json:"refreshToken"`
ExpiresIn int `json:"expiresIn"`
}
OAuthLoginResponse contains the response for OAuth-based login.
type OAuthResponse ¶
type OAuthResponse struct {
OK bool `json:"ok"`
Error string `json:"error,omitempty"`
AccessToken string `json:"access_token"`
Team struct {
ID string `json:"id"`
Name string `json:"name"`
} `json:"team"`
AuthedUser AuthedUser `json:"authed_user"`
}
OAuthResponse represents the response from Slack's OAuth token exchange.
type OAuthState ¶
type OAuthState struct {
Nonce string `json:"nonce"`
RedirectURI string `json:"redirectUri"`
OrgSlug string `json:"orgSlug,omitempty"`
CreatedAt int64 `json:"createdAt"`
}
OAuthState represents the state stored during OAuth flow.
type OIDCOAuthHandler ¶
type OIDCOAuthHandler struct {
base.HandlerBase
// contains filtered or unexported fields
}
OIDCOAuthHandler handles generic OpenID Connect authentication endpoints.
func NewOIDCOAuthHandler ¶
func NewOIDCOAuthHandler(service *OIDCOAuthService, cfg *config.Config) *OIDCOAuthHandler
NewOIDCOAuthHandler creates a new generic OIDC handler.
func (*OIDCOAuthHandler) Callback ¶
func (h *OIDCOAuthHandler) Callback(writer http.ResponseWriter, req *http.Request) error
Callback handles the OAuth callback from the generic OIDC provider. GET /api/v1/auth/oidc/callback?code=...&state=...
func (*OIDCOAuthHandler) Login ¶
func (h *OIDCOAuthHandler) Login(writer http.ResponseWriter, req *http.Request) error
Login initiates the generic OIDC flow. GET /api/v1/auth/oidc/login?org=...&redirect_uri=...
type OIDCOAuthResult ¶
type OIDCOAuthResult = ProviderOutcome
OIDCOAuthResult contains the result of a successful generic OIDC flow. It is the ProviderOutcome every federated callback hands to finishProviderCallback.
type OIDCOAuthService ¶
type OIDCOAuthService struct {
// contains filtered or unexported fields
}
OIDCOAuthService handles generic OpenID Connect authentication logic.
Exactly one issuer is supported (spec 2026-07-08-08, part 1 — global-only, single instance). Discovery and the JWKS key set are cached in-process and only re-fetched when the configured issuer URL changes, so a super-admin edit to the config takes effect on the next login without a restart.
func NewOIDCOAuthService ¶
func NewOIDCOAuthService(dbService db.Service, cfg *config.Config, authService *Service) *OIDCOAuthService
NewOIDCOAuthService creates a new generic OIDC service.
func (*OIDCOAuthService) GenerateOAuthState ¶
func (s *OIDCOAuthService) GenerateOAuthState(ctx context.Context, redirectURI, orgSlug string) (string, error)
GenerateOAuthState creates a new OAuth state and stores it in the database.
func (*OIDCOAuthService) HandleCallback ¶
func (s *OIDCOAuthService) HandleCallback(ctx context.Context, code, orgSlug string) (*OIDCOAuthResult, error)
HandleCallback processes the OAuth callback from the generic OIDC provider: exchanges the code, validates the ID token (issuer, audience, signature via JWKS, expiry), maps claims, and resolves/creates the local user.
func (*OIDCOAuthService) ValidateOAuthState ¶
func (s *OIDCOAuthService) ValidateOAuthState(ctx context.Context, stateParam string) (*OAuthState, error)
ValidateOAuthState validates and consumes an OAuth state.
type OpenIDUserInfo ¶
type OpenIDUserInfo struct {
OK bool `json:"ok"`
Sub string `json:"sub"` // Slack user ID
Email string `json:"email"`
EmailVerified bool `json:"email_verified"`
Name string `json:"name"`
Picture string `json:"picture"`
// SlackTeamName / SlackTeamDomain are workspace-identity custom claims
// returned by openid.connect.userInfo with the profile scope. TeamDomain
// is the workspace subdomain (e.g. "acme" for acme.slack.com) and makes
// an ideal org slug.
SlackTeamName string `json:"https://slack.com/team_name"`
SlackTeamDomain string `json:"https://slack.com/team_domain"`
Error string `json:"error,omitempty"`
}
OpenIDUserInfo represents user info from OpenID Connect endpoint.
type OrgAccessDenial ¶
type OrgAccessDenial int
OrgAccessDenial classifies the outcome of an org-access authorization check so each transport can map it to its own signal (a REST HTTP status vs. a WebSocket close code).
const ( // OrgAccessGranted means the user may access the organization. OrgAccessGranted OrgAccessDenial = iota // OrgAccessOrgNotFound means the organization slug does not resolve. Only // reachable once the caller has already cleared the token-scope check (or // is a super-admin), so it never leaks org existence to an unrelated user. OrgAccessOrgNotFound // OrgAccessDenied means the user is authenticated but not authorized for // this org (token scoped to a different org, or not a member). OrgAccessDenied )
func AuthorizeOrgAccess ¶
func AuthorizeOrgAccess( ctx context.Context, dbService db.Service, claims *Claims, user *models.User, orgSlug string, ) (*models.Organization, OrgAccessDenial)
AuthorizeOrgAccess is the single source of truth for whether an authenticated user may access an organization's resources. Both the REST middleware (middleware.RequireOrgAccess) and the realtime WebSocket handshake (realtimews.authorizeOrg) call it, so the two surfaces cannot drift — the cross-tenant leak fixed by spec 2026-07-15-01 existed precisely because REST had no such check while the WS had its own hand-maintained copy.
The rule is token-scope equality PLUS membership:
- A claims super-admin may access any org.
- A non-super-admin's access token must be scoped to the org it is accessing (claims.OrgSlug == orgSlug). This is deliberate and load-bearing: downstream handlers trust claims.Role / claims.OrgSlug as the caller's role FOR THE ORG BEING ACCESSED (see the many `claims.Role == "admin"` admin gates). Allowing membership-only cross-org access with a token minted for a different org would let a stale claims.Role grant elevated privileges in an org where the user has a lower role. The dashboard therefore re-mints the token (switch-org) when navigating between orgs so claims.OrgSlug tracks the URL.
- A DB-only super-admin (user.SuperAdmin) skips the membership check but NOT the token-scope check — a DB super-admin whose token is scoped elsewhere is still denied, matching the historical REST behavior.
- Everyone else must be a member of the org.
The token-scope check runs before the org is loaded so a user whose token is not scoped to the org can't use the not-found-vs-denied distinction to probe which org slugs exist.
type OrgProfileResponse ¶
type OrgProfileResponse struct {
UID string `json:"uid"`
Slug string `json:"slug"`
Name string `json:"name"`
LogoURL *string `json:"logoUrl"`
// PreviousSlug is the slug that was just freed; it keeps redirecting to
// Slug until another organization claims it. Empty when the slug did not
// change.
PreviousSlug string `json:"previousSlug,omitempty"`
AccessToken string `json:"accessToken,omitempty"`
RefreshToken string `json:"refreshToken,omitempty"`
ExpiresIn int `json:"expiresIn,omitempty"`
TokenType string `json:"tokenType,omitempty"`
}
OrgProfileResponse is the updated organization profile.
When the slug changed it also carries a fresh org-scoped session: the caller's current access token has the OLD slug in its orgSlug claim, and AuthorizeOrgAccess compares that claim with the URL, so without a re-mint the very next request to the renamed org would 403. Other sessions self-heal on their next Refresh, which derives the claim from the org row by UID.
type OrgResponse ¶
type OrgResponse struct {
UID string `json:"uid"`
Slug string `json:"slug"`
Name string `json:"name"`
LogoURL *string `json:"logoUrl"`
AccessToken string `json:"accessToken"`
RefreshToken string `json:"refreshToken"`
ExpiresIn int `json:"expiresIn"`
TokenType string `json:"tokenType"`
}
OrgResponse contains the response for org creation. It carries a fresh org-scoped session (accessToken/refreshToken/expiresIn/tokenType) alongside the org identity — the caller who creates their first org has no other way to obtain a token whose orgSlug claim matches the new org (see the 2026-07-08 "create-org missing org-scoped token" spec).
type OrgSettingsResponse ¶
type OrgSettingsResponse struct {
RegistrationEmailPattern string `json:"registrationEmailPattern"`
// SessionMaxDurationSeconds is this org's auth.session_max_duration
// override, in seconds, or nil when the org has no override and
// inherits the system-wide value (spec B.2/B.4). The UI shows the
// effective/inherited value separately via
// GET /api/v1/system/parameters (super-admin) — this field is only the
// org-level override itself, so the settings page can distinguish "not
// set" from "explicitly set to the same number".
SessionMaxDurationSeconds *int `json:"sessionMaxDurationSeconds,omitempty"`
// DefaultEscalationPolicyUID is the org-wide fallback escalation policy
// applied to checks that resolve to no policy of their own (check → group →
// org default → none). nil/absent = no org default (legacy behavior).
DefaultEscalationPolicyUID *string `json:"defaultEscalationPolicyUid,omitempty"`
// InheritingCheckCount is how many of the org's live checks currently
// resolve to no policy of their own — the blast radius of setting or
// changing DefaultEscalationPolicyUID. Always present.
InheritingCheckCount int `json:"inheritingCheckCount"`
// TracerouteOnFailure is the ORG-LEVEL default for the path capture taken
// when a check goes down on a network-reachability failure (spec
// 2026-08-21-10). It applies to every check whose own
// `tracerouteOnFailure` is `inherit`.
//
// ALWAYS PRESENT, and true when the org has never set it — the spec's
// "org-level default (on)". A nullable field here would make the settings
// page render an unchecked box for an org that is in fact tracing.
TracerouteOnFailure bool `json:"tracerouteOnFailure"`
// StatusPageAllowedEmbedOrigins lists the scheme+host origins allowed to
// frame this org's public status pages (spec 2026-09-25-28). They are
// rendered into the status page's `frame-ancestors`, after 'self'. ALWAYS
// PRESENT; empty means only the SolidPing origin itself may frame them.
StatusPageAllowedEmbedOrigins []string `json:"statusPageAllowedEmbedOrigins"`
// ReminderIntervalSeconds is the org default reminder interval for every
// check whose own `reminderIntervalSeconds` is null (spec 2026-10-12-16).
// ALWAYS PRESENT; 0 (off) when the org never set it.
ReminderIntervalSeconds int `json:"reminderIntervalSeconds"`
// BrowserSealingMode is `optional` (server or browser encryption, per
// check) or `required` (plaintext check secrets refused), spec
// 2026-11-08-01. ALWAYS PRESENT; `optional` when never set.
BrowserSealingMode string `json:"browserSealingMode"`
}
OrgSettingsResponse contains org settings.
type OrganizationInfo ¶
type OrganizationInfo struct {
UID string `json:"uid"`
Slug string `json:"slug"`
Name string `json:"name,omitempty"`
// LogoURL is the org's logo (absolute http(s) URL, or /pub/assets/<uid>
// for an uploaded one). Null means "no logo" and the client falls back to
// the product default.
LogoURL *string `json:"logoUrl"`
}
OrganizationInfo represents organization information.
type OrganizationRef ¶
type OrganizationRef struct {
UID string `json:"uid"`
Slug string `json:"slug"`
Name string `json:"name"`
}
OrganizationRef is a slug+name handle to an org.
type OrganizationSummary ¶
type OrganizationSummary struct {
Slug string `json:"slug"`
Name string `json:"name,omitempty"`
LogoURL *string `json:"logoUrl"`
Role string `json:"role"`
}
OrganizationSummary represents a brief organization entry for listing.
type PageMemoInvalidator ¶
type PageMemoInvalidator interface {
InvalidateOrg(orgUID string)
}
PageMemoInvalidator evicts memoized public status-page views of one organization. Injected, because the status-pages package owns the memo.
type PasskeyHandler ¶
type PasskeyHandler struct {
base.HandlerBase
// contains filtered or unexported fields
}
PasskeyHandler exposes the passkey HTTP endpoints. It's a sibling of Handler — both share the same base.HandlerBase machinery and live on the same auth route prefix. We keep them separate so service.go stays password+TOTP-focused.
func NewPasskeyHandler ¶
func NewPasskeyHandler(svc *PasskeyService, base base.HandlerBase) *PasskeyHandler
NewPasskeyHandler wires the passkey service to HTTP.
func (*PasskeyHandler) Delete ¶
func (h *PasskeyHandler) Delete(writer http.ResponseWriter, req *http.Request) error
Delete handles DELETE /api/v1/auth/passkeys/:uid.
func (*PasskeyHandler) List ¶
func (h *PasskeyHandler) List(writer http.ResponseWriter, req *http.Request) error
List handles GET /api/v1/auth/passkeys.
func (*PasskeyHandler) LoginBegin ¶
func (h *PasskeyHandler) LoginBegin(writer http.ResponseWriter, req *http.Request) error
LoginBegin handles POST /api/v1/auth/passkeys/login/begin (public).
func (*PasskeyHandler) LoginFinish ¶
func (h *PasskeyHandler) LoginFinish(writer http.ResponseWriter, req *http.Request) error
LoginFinish handles POST /api/v1/auth/passkeys/login/finish (public).
func (*PasskeyHandler) RegisterBegin ¶
func (h *PasskeyHandler) RegisterBegin(writer http.ResponseWriter, req *http.Request) error
RegisterBegin handles POST /api/v1/auth/passkeys/register/begin.
func (*PasskeyHandler) RegisterFinish ¶
func (h *PasskeyHandler) RegisterFinish(writer http.ResponseWriter, req *http.Request) error
RegisterFinish handles POST /api/v1/auth/passkeys/register/finish.
func (*PasskeyHandler) Rename ¶
func (h *PasskeyHandler) Rename(writer http.ResponseWriter, req *http.Request) error
Rename handles PATCH /api/v1/auth/passkeys/:uid.
type PasskeyInfo ¶
type PasskeyInfo struct {
UID string `json:"uid"`
Name string `json:"name"`
AAGUIDLabel string `json:"aaguidLabel,omitempty"`
Transports []string `json:"transports,omitempty"`
BackupState bool `json:"backupState,omitempty"`
CreatedAt time.Time `json:"createdAt"`
LastUsedAt *time.Time `json:"lastUsedAt,omitempty"`
}
PasskeyInfo is the read-side projection returned by GET /auth/passkeys and embedded in the FinishRegistration response.
type PasskeyService ¶
type PasskeyService struct {
// contains filtered or unexported fields
}
PasskeyService owns the registration/login WebAuthn ceremonies and the passkey CRUD endpoints. It depends on the auth Service for the shared completeLogin path so passkey sign-ins issue tokens identical to the password and OAuth flows.
func NewPasskeyService ¶
func NewPasskeyService(authSvc *Service, dbSvc db.Service) *PasskeyService
NewPasskeyService constructs a PasskeyService from the auth service's state. Returns an instance with enabled=false (and a usable error) when the WebAuthn config is incomplete or insecure (e.g. base URL is plain http and the host is not localhost). The handler surfaces the disabled state as `passkeysEnabled: false` on /auth/providers; HTTP routes return WEBAUTHN_NOT_CONFIGURED.
func (*PasskeyService) BeginLogin ¶
func (s *PasskeyService) BeginLogin( ctx context.Context, email string, ) (*LoginBeginResponse, error)
BeginLogin starts the assertion ceremony. When email is empty the returned options have an empty allowCredentials list — the browser uses discoverable credentials and the response carries the user handle. When email maps to a known user we list that user's credentials. Either way the response is indistinguishable to a caller probing for valid emails (the library generates a fresh challenge regardless).
func (*PasskeyService) BeginRegistration ¶
func (s *PasskeyService) BeginRegistration( ctx context.Context, userUID string, currentPassword *string, ) (*RegisterBeginResponse, error)
BeginRegistration starts the ceremony for an authenticated user. The returned session JWT carries the WebAuthn challenge and the user's UID; the client must echo it back to FinishRegistration.
A passkey is a sign-in factor that survives a password reset, so the caller re-authenticates first: currentPassword when the account has a password, a recent sign-in otherwise (spec 2026-10-31-02). FinishRegistration is bound to this call by the sealed session.
func (*PasskeyService) DeletePasskey ¶
func (s *PasskeyService) DeletePasskey( ctx context.Context, userUID, passkeyUID string, ) error
DeletePasskey enforces the last-auth-method invariant: a user can't remove their only sign-in method. A user has at least one of:
- a password set,
- another non-deleted passkey,
- a linked OAuth provider.
func (*PasskeyService) Enabled ¶
func (s *PasskeyService) Enabled() bool
Enabled reports whether the WebAuthn config resolved cleanly. /auth/ providers reads this; handlers refuse to start a ceremony when false.
func (*PasskeyService) FinishLogin ¶
func (s *PasskeyService) FinishLogin( ctx context.Context, sessionToken string, credentialJSON []byte, orgPreference string, authContext Context, ) (*LoginResponse, error)
FinishLogin verifies the assertion, updates sign_count + last_used_at, resolves the user's organization preference, and delegates to completeLogin so the issued tokens match the password / OAuth paths. Skips TOTP per D2 — a passkey is already MFA-equivalent.
func (*PasskeyService) FinishRegistration ¶
func (s *PasskeyService) FinishRegistration( ctx context.Context, sessionToken string, credentialJSON []byte, name string, ) (*PasskeyInfo, error)
FinishRegistration consumes the sealed session and the credential returned by navigator.credentials.create(). On success it stores a row in user_passkeys and returns the projected info.
func (*PasskeyService) ListPasskeys ¶
func (s *PasskeyService) ListPasskeys(ctx context.Context, userUID string) ([]PasskeyInfo, error)
ListPasskeys returns the projected info for every non-deleted passkey owned by the user.
func (*PasskeyService) RenamePasskey ¶
func (s *PasskeyService) RenamePasskey( ctx context.Context, userUID, passkeyUID, name string, ) error
RenamePasskey updates the user-visible label.
type PreferencesRequest ¶
type PreferencesRequest struct {
Locale *string `json:"locale,omitempty"`
Timezone *string `json:"timezone,omitempty"`
DashboardWindow *string `json:"dashboardWindow,omitempty"`
GlanceRows *int `json:"glanceRows,omitempty"`
}
PreferencesRequest is the partial preferences update of PATCH /auth/me. A nil field is left alone; an empty string clears it.
type ProviderInfo ¶
ProviderInfo represents an available auth provider.
type ProviderLoginResult ¶
type ProviderLoginResult struct {
AccessToken string
RefreshToken string
ExpiresIn int
// Pending is true when the user authenticated successfully but was NOT
// admitted to the org. No session on THAT org exists: the tokens are
// scoped to FallbackOrgSlug when set, and are otherwise an org-less
// session (empty org slug, no refresh token).
Pending bool
// FallbackOrgSlug is, for a pending login only, the org the user IS an
// admitted member of that the session was minted on instead (spec
// 2026-09-25-15). The identity is proven, so a real member signing in from
// someone else's login page gets a session they can use rather than an
// org-less one. Empty means the user belongs to no org at all.
FallbackOrgSlug string
// PendingOrgSlug is the org the no-org screen should NAME as "your sign-in
// succeeded but this org hasn't admitted you yet". It is the org's slug
// whenever a membership request was actually opened, and deliberately EMPTY
// when rule 6 suppressed one (the demo org, or the SaaS platform default org): naming an org nobody
// asked for and no admin will ever see a request from is worse than saying
// nothing. Meaningless unless Pending is true.
PendingOrgSlug string
// Requires2FA is true when the user has TOTP enabled: no session was
// minted (the token fields are empty) and TempToken is the 2FA challenge
// that Verify2FA / Recovery2FA trade for the session described by the
// other fields (spec 2026-10-16-14).
Requires2FA bool
TempToken string
}
ProviderLoginResult is the outcome of a completed federated login for one organization: either a real org-scoped session, or (Pending) a membership request awaiting an admin decision plus a session on another org the user already belongs to (FallbackOrgSlug) or, failing that, an org-less one.
func (*ProviderLoginResult) Outcome ¶
func (r *ProviderLoginResult) Outcome(orgSlug, userUID string) *ProviderOutcome
Outcome is the ProviderOutcome of this login, completed against the org orgSlug for the user userUID. Every federated connector builds its result through it, so none can drop a field (the 2FA challenge in particular).
type ProviderOutcome ¶
type ProviderOutcome struct {
AccessToken string
RefreshToken string
ExpiresIn int
// OrgSlug is the org the login was completed against.
OrgSlug string
UserUID string
// Pending is true when the org did not admit the user: the tokens above
// are then scoped to FallbackOrgSlug, or org-less (no refresh token) when
// that is empty.
Pending bool
// FallbackOrgSlug is the org a pending login's session was minted on
// instead — see ProviderLoginResult.FallbackOrgSlug. Meaningless unless
// Pending is true.
FallbackOrgSlug string
// PendingOrgSlug is the org to NAME on the no-org screen — see
// ProviderLoginResult.PendingOrgSlug. Meaningless unless Pending is true.
PendingOrgSlug string
// Requires2FA / TempToken: see ProviderLoginResult. When set, the token
// fields are empty and the handoff carries the challenge instead.
Requires2FA bool
TempToken string
// RoleChanges are the roles the IdP group claim granted or revoked
// during this login (RoleChange* constants, OIDC only), surfaced in the
// login response diagnostics (spec 2026-11-21-02).
RoleChanges []string
}
ProviderOutcome is what every federated callback knows once the login is done: the session CompleteOrgLogin minted and whether the org admitted the user. It is the input of the shared redirect tail.
type ProvidersHandler ¶
type ProvidersHandler struct {
base.HandlerBase
// contains filtered or unexported fields
}
ProvidersHandler handles the available auth providers endpoint.
func NewProvidersHandler ¶
func NewProvidersHandler(cfg *config.Config, passkeyEnabled func() bool) *ProvidersHandler
NewProvidersHandler creates a new providers handler. When passkeyEnabled is non-nil it's queried each request — supports the case where WebAuthn is configured but disabled at runtime (e.g. base URL is not https).
func (*ProvidersHandler) ListProviders ¶
func (h *ProvidersHandler) ListProviders(writer http.ResponseWriter, req *http.Request) error
ListProviders returns which auth providers are configured, and whether the email/password form is offered (localLogin, spec 2026-11-21-02).
func (*ProvidersHandler) SetLocalLoginResolver ¶
func (h *ProvidersHandler) SetLocalLoginResolver(resolve func(ctx context.Context) bool)
SetLocalLoginResolver replaces the env-and-config-only local-login lookup with one that also reads the DB parameter (Service.LocalLoginEnabled).
type ProvidersResponse ¶
type ProvidersResponse struct {
Data []ProviderInfo `json:"data"`
RegistrationEnabled bool `json:"registrationEnabled"`
PasskeysEnabled bool `json:"passkeysEnabled"`
// LocalLogin is false while local password login is switched off: the
// login page then hides the email/password form, the forgot-password
// and the sign-up links.
LocalLogin bool `json:"localLogin"`
}
ProvidersResponse is the response for the providers endpoint.
type Recovery2FARequest ¶
type Recovery2FARequest struct {
RecoveryCode string `json:"recoveryCode"`
}
Recovery2FARequest contains the request data for using a recovery code.
type RefreshRequest ¶
type RefreshRequest struct {
RefreshToken string `json:"refreshToken"`
}
RefreshRequest represents a token refresh request body.
type RegisterBeginResponse ¶
type RegisterBeginResponse struct {
Options *protocol.CredentialCreation `json:"options"`
Session string `json:"session"`
}
RegisterBeginResponse is the wire shape of POST /auth/passkeys/register/begin.
type RegisterRequest ¶
type RegisterRequest struct {
Name string `json:"name"`
Email string `json:"email"`
Password string `json:"password"`
// Attribution is the campaign context the dashboard captured from its
// landing URL (spec 2026-09-07-03). Optional; normalized and bounded by
// normalizeSignupAttribution before it is stored, so a client cannot use
// it to park arbitrary data on a user row.
Attribution *models.SignupAttribution `json:"attribution,omitempty"`
// Locale and Timezone are the browser's language and IANA zone, the
// preferences the account starts with (spec 2026-10-21-01). Optional and
// lenient: an unsupported value is dropped, never refused.
Locale string `json:"locale,omitempty"`
Timezone string `json:"timezone,omitempty"`
// ClientIP is the caller's address, set by the HTTP handler with the
// trusted-proxy rules, never read from the body. It counts the sign-up
// against auth.registration_max_pending_per_ip; empty skips the per-IP limits.
ClientIP string `json:"-"`
}
RegisterRequest contains the registration request data.
type RegisterResponse ¶
type RegisterResponse struct {
Message string `json:"message"`
}
RegisterResponse contains the response after registration.
type RequestPasswordResetRequest ¶
type RequestPasswordResetRequest struct {
Email string `json:"email"`
}
RequestPasswordResetRequest contains the password reset request data.
type RequestPasswordResetResponse ¶
type RequestPasswordResetResponse struct {
Message string `json:"message"`
}
RequestPasswordResetResponse contains the password reset request response.
type ResetPasswordRequest ¶
ResetPasswordRequest contains the password reset confirmation data.
type ResetPasswordResponse ¶
type ResetPasswordResponse struct {
Message string `json:"message"`
}
ResetPasswordResponse contains the password reset confirmation response.
type SAMLHandler ¶
type SAMLHandler struct {
base.HandlerBase
// contains filtered or unexported fields
}
SAMLHandler handles SAML 2.0 Service Provider authentication endpoints.
func NewSAMLHandler ¶
func NewSAMLHandler(service *SAMLService, cfg *config.Config) *SAMLHandler
NewSAMLHandler creates a new SAML SP handler.
func (*SAMLHandler) ACS ¶
func (h *SAMLHandler) ACS(writer http.ResponseWriter, req *http.Request) error
ACS (Assertion Consumer Service) consumes the SAML assertion POSTed back by the IdP after the user authenticates there. POST /api/v1/auth/saml/acs.
func (*SAMLHandler) Login ¶
func (h *SAMLHandler) Login(writer http.ResponseWriter, req *http.Request) error
Login initiates the SP-initiated SAML flow: builds an AuthnRequest and redirects the browser to the configured IdP's SSO endpoint. GET /api/v1/auth/saml/login?org=...&redirect_uri=...
func (*SAMLHandler) Metadata ¶
func (h *SAMLHandler) Metadata(writer http.ResponseWriter, req *http.Request) error
Metadata serves this SP's own metadata document (entity ID, ACS URL, certificate) so IdP admins can configure their side by URL. GET /api/v1/auth/saml/metadata.
type SAMLRelayState ¶
type SAMLRelayState struct {
Nonce string `json:"nonce"`
RequestID string `json:"requestId"`
RedirectURI string `json:"redirectUri"`
OrgSlug string `json:"orgSlug"`
CreatedAt int64 `json:"createdAt"`
}
SAMLRelayState is the state tracked between GenerateAuthnRequest (the login redirect) and HandleACS (the assertion consumer). Stored under a random nonce via the same TTL'd db state-entry store the OAuth providers' OAuthState uses, and carried as the SAML RelayState parameter — the RequestID is what lets ParseResponse enforce InResponseTo (replay/CSRF protection): only a request this SP actually issued and hasn't yet consumed can complete a login.
type SAMLResult ¶
type SAMLResult = ProviderOutcome
SAMLResult contains the result of a successful SAML SP-initiated login. It is the ProviderOutcome every federated callback hands to finishProviderCallback.
type SAMLService ¶
type SAMLService struct {
// contains filtered or unexported fields
}
SAMLService implements the SAML 2.0 Service Provider role for SolidPing.
Exactly one IdP is supported (spec 2026-07-08-08, part 2 — global-only, single instance, SP-initiated login only). IdP metadata (fetched from a URL or parsed from pasted XML) is cached in-process and only re-parsed when the configured source changes, so a super-admin edit takes effect on the next login without a restart.
Trust model / why linking by email is safe here: unlike the generic OIDC connector (which had to add an explicit `email_verified` gate — see oidc_service.go — because an admin-configured OIDC issuer might not itself verify the email it asserts), SAML has no standard "unverified claim" escape hatch. The entire assertion, including every attribute, is signed by the IdP's private key, and the SP only trusts that key because an admin explicitly configured it (via IDPMetadataURL/IDPMetadataXML) — the same admin-established trust boundary OIDC relies on for its issuer. Once ParseResponse has validated the signature, Conditions, Audience, and InResponseTo, the asserted email is exactly as trustworthy as an OIDC token's `email_verified: true` claim: linking to a pre-existing local user by email is therefore acceptable. The residual risk — an IdP that lets end users self-assert their own "email" attribute via a self-service profile — is an IdP-configuration concern outside what any SP can detect from the wire protocol (SAML has nothing equivalent to OIDC's email_verified to check), exactly as an OIDC issuer that doesn't verify email ownership is a provider-configuration concern. This is called out here so a security review evaluates it explicitly rather than assuming an oversight.
func NewSAMLService ¶
NewSAMLService creates a new SAML SP service.
func (*SAMLService) GenerateAuthnRequest ¶
func (s *SAMLService) GenerateAuthnRequest(ctx context.Context, redirectURI, orgSlug string) (string, error)
GenerateAuthnRequest builds an AuthnRequest for the configured IdP and returns the URL to redirect the browser to (HTTP-Redirect binding). Stores the request ID plus redirectURI/orgSlug under a random nonce (RelayState) so HandleACS can validate the response against a request this SP actually issued and carry the original returnTo through, mirroring the OAuthState pattern used by the OAuth-shaped providers.
func (*SAMLService) HandleACS ¶
func (s *SAMLService) HandleACS( ctx context.Context, httpReq *http.Request, state *SAMLRelayState, ) (*SAMLResult, error)
HandleACS validates the SAML assertion delivered to the ACS endpoint and resolves/creates the local user. ParseResponse performs the security-critical validation: signature (against the IdP's metadata certificate), Conditions NotBefore/NotOnOrAfter, Audience restriction (must name this SP), SubjectConfirmationData Recipient (must be our ACS URL) and NotOnOrAfter, and InResponseTo matched against the request ID we actually issued (replay/CSRF protection). validateNameIDNamespace then cross-checks the extracted NameID against the raw XML (GO-2026-6909) — see SAMLService's doc comment for why linking the resulting identity by email is safe once that validation has passed.
func (*SAMLService) Metadata ¶
func (s *SAMLService) Metadata(ctx context.Context) ([]byte, error)
Metadata returns this SP's metadata document (entity ID, ACS URL, certificate) as XML, for IdP admins to configure their side.
func (*SAMLService) ValidateRelayState ¶
func (s *SAMLService) ValidateRelayState(ctx context.Context, relayState string) (*SAMLRelayState, error)
ValidateRelayState validates and consumes (one-time use) the RelayState nonce carried on the ACS POST, returning the state stored by GenerateAuthnRequest.
type Service ¶
type Service struct {
// contains filtered or unexported fields
}
Service provides authentication business logic.
func NewService ¶
func NewService( dbService db.Service, cfg config.AuthConfig, fullCfg *config.Config, jobsSvc jobsvc.Service, entitlements EntitlementsChecker, ) *Service
NewService creates a new authentication service.
entitlements is optional; pass nil for callers that do not need SSO membership-cap enforcement (e.g. unit tests of unrelated paths).
func (*Service) AcceptInvite ¶
func (s *Service) AcceptInvite(ctx context.Context, req AcceptInviteRequest, callerUID string) (*LoginResponse, error)
AcceptInvite accepts an invitation and creates/authenticates the user.
callerUID is the UID of the authenticated caller, or "" for an anonymous request. An invitation addressed to an existing account is accepted only by that account, signed in: the invite token alone proves nothing, the inviter holds it (spec 2026-10-16-06). Every check runs before any write, so a refused attempt creates nothing and leaves the invitation in place.
func (*Service) AdminUpdateUser ¶
func (s *Service) AdminUpdateUser( ctx context.Context, claims *Claims, targetUID string, req AdminUpdateUserRequest, ) (*AdminUpdateUserResponse, error)
AdminUpdateUser lets a super admin change any user's email (spec 2026-09-30-08). No password is asked of the target: the caller's super admin authentication is what authorizes it.
func (*Service) ApproveMembershipRequest ¶
func (s *Service) ApproveMembershipRequest( ctx context.Context, decidedByUID, orgSlug, requestUID string, roleStr string, ) error
ApproveMembershipRequest commits status + new membership in one tx.
func (*Service) CancelMembershipRequest ¶
CancelMembershipRequest lets the requester drop their own request. Returns ErrRequestNotFound on missing or non-owned rows.
func (*Service) ChangePassword ¶
func (s *Service) ChangePassword( ctx context.Context, userUID, currentRefreshUID string, req ChangePasswordRequest, ) (*ChangePasswordResponse, error)
ChangePassword rotates the password of an already-authenticated user.
It is the authenticated twin of ResetPassword: identical post-change side effects (other sessions revoked, PATs preserved, password-changed.html confirmation email) so it does not matter which path rotated the password.
Two behaviors are deliberate and load-bearing:
- When the account has no password yet (signed up through an identity provider), currentPassword is ignored and this *sets* the initial password. Without it an SSO user is permanently locked to their IdP. A first password is a new sign-in factor, so the session must come from a sign-in within the last 10 minutes (ErrReauthenticationRequired otherwise, spec 2026-10-31-02).
- currentRefreshUID (the caller's own Claims.RefreshUID) is spared by the revocation sweep. Changing your password from the settings page must not bounce you to the login screen; every *other* session still dies.
func (*Service) CheckMembershipSlot ¶
CheckMembershipSlot is exposed for OAuth services that already share the auth Service. It delegates to the configured entitlements checker; nil checker = no-op (passes through).
func (*Service) CompleteOrgLogin ¶
func (s *Service) CompleteOrgLogin( ctx context.Context, org *models.Organization, user *models.User, opts ...LoginOption, ) (*ProviderLoginResult, error)
CompleteOrgLogin is the shared tail of every federated callback: run the admission rules, replay the cross-org auto-join, then mint the session that matches the outcome.
A pending outcome never grants anything on the org that refused the login. The identity is proven, though, so when the user is an admitted member of another org the session is a normal one on that org (refresh token included, FallbackOrgSlug set): a real member who started from someone else's login page must not be handed a session they cannot use (spec 2026-09-25-15). A user with no membership at all gets the org-less access token (no refresh token) that lets the dashboard show the request-access surface without any org-scoped API access.
A user with TOTP enabled gets no session at all here: the result carries Requires2FA and a 2FA temp token naming the org and role the session would have had, and Verify2FA / Recovery2FA mint it once the code is accepted (spec 2026-10-16-14). Admission (membership requests, invitations, auto-join) still runs before the code, as for an LDAP login: it only ever benefits the real account, and nothing usable is issued without the code. Passkeys are the only sign-in that skips TOTP, because a passkey already is a second factor (passkey_service.go FinishLogin, which never comes here).
func (*Service) Confirm2FA ¶
func (s *Service) Confirm2FA(ctx context.Context, userUID string, req Confirm2FARequest) (*Confirm2FAResponse, error)
Confirm2FA validates the TOTP code, enables 2FA, and returns recovery codes. setupToken must be the one Setup2FA returned with the pending secret: it is what proves the re-authentication.
func (*Service) ConfirmRegistration ¶
ConfirmRegistration confirms a registration and creates the user.
func (*Service) CreateInvitation ¶
func (s *Service) CreateInvitation( ctx context.Context, orgSlug, inviterUID string, req InviteRequest, ) (*InviteResponse, error)
CreateInvitation creates an invitation for a user to join an organization.
func (*Service) CreateMembershipRequest ¶
func (s *Service) CreateMembershipRequest( ctx context.Context, userUID string, req MembershipRequestCreateRequest, ) (*MembershipRequestSummary, error)
CreateMembershipRequest opens (or re-opens) a pending request.
func (*Service) CreateOrg ¶
func (s *Service) CreateOrg( ctx context.Context, userUID string, req CreateOrgRequest, authContext Context, ) (*OrgResponse, error)
CreateOrg creates a new organization, makes the caller its OWNER, and mints a session scoped to the new org — mirroring SwitchOrg, since this is structurally the same "hand the caller a token for an org other than the one in their current claims" problem.
The org is always created for the authenticated caller: userUID comes from the validated JWT claims, never from the request body, so there is no way to create an org on somebody else's behalf.
Slug availability is decided by GetOrganizationBySlug, which filters `deleted_at IS NULL` — so a deleted org's slug is free for reuse, matching the partial unique index on organizations(slug). A slug held only as a renamed org's previous slug is likewise free, and claiming it releases that alias (spec 2026-08-08-12).
func (*Service) CreatePAT ¶
func (s *Service) CreatePAT( ctx context.Context, orgSlug, userUID string, req CreateTokenRequest, ) (*CreateTokenResponse, error)
CreatePAT creates a new Personal Access Token.
func (*Service) DeleteOrg ¶
func (s *Service) DeleteOrg( ctx context.Context, orgSlug, callerUserUID string, req DeleteOrgRequest, authContext Context, ) (*LoginResponse, error)
DeleteOrg soft-deletes an organization and everything that would otherwise keep serving after it is gone. Owner-only — the route is guarded by middleware.RequireOrgOwner; this function assumes that check already ran.
Order matters, and each step exists for a reason:
- check_jobs are HARD-deleted first. The scheduler's claim query (checkjobsvc.selectAvailableJobs) never joins organizations, so a surviving row would keep probing targets for a deleted org. Killing the jobs is what actually stops the checks; soft-deleting the checks alone would not.
- checks are soft-deleted so nothing re-creates jobs for them.
- memberships are soft-deleted — the org disappears from every member's org switcher.
- org-scoped tokens are revoked so no live session (including the caller's own) keeps org-scoped API access. The caller does not lose their *authentication* over it: step 6 hands them a brand-new session. Every OTHER member is signed out of the org for good, which is the deliberate behavior from spec 2026-08-08-11.
- the organization row itself is soft-deleted LAST. From that instant every lookup 404s: dashboard API, status pages, badges and the embed widget all resolve the org through GetOrganizationBySlug, which filters `deleted_at IS NULL`. The slug also becomes claimable again — the unique slug index is partial on `deleted_at is null` — with no alias, tombstone or redirect left behind (a *renamed* org's previous slug is a different mechanism entirely and must not resolve deleted orgs).
- the CALLER is handed a replacement session. Steps 3-4 took away the org their access token names, so without this they would be logged out by their own maintenance action (GitHub issue #206). See mintPostDeletionSession.
There is deliberately no restore path: soft-delete is an implementation detail, and recovery is a manual database intervention.
func (*Service) Disable2FA ¶
Disable2FA disables 2FA for the user after validating the current TOTP code.
It spends the same per-user attempt budget as Verify2FA and Recovery2FA before the code is looked at: a stolen session or PAT must not get an unthrottled oracle that ends with the second factor removed.
func (*Service) ExchangeHandoffCode ¶
func (s *Service) ExchangeHandoffCode(ctx context.Context, code string) (*HandoffExchangeResponse, error)
ExchangeHandoffCode redeems a handoff code minted by a federated login callback (spec 2026-09-25-12) and returns the session it carried, in the login response shape. The user and organization are read fresh, the same way /auth/me reads them.
Every unusable code, and a code whose user or membership vanished in the meantime, yields authhandoff.ErrInvalidCode.
A code carrying a 2FA challenge (the user has TOTP enabled, spec 2026-10-16-14) answers requires2Fa and the temp token only, plus where to land: no session, and no user or organization info, the same disclosure as a password login stopped at the code prompt.
func (*Service) GenerateMCPAccessToken ¶
func (s *Service) GenerateMCPAccessToken( ctx context.Context, userUID, orgSlug string, scopes []string, audience string, ttl time.Duration, refreshUID, clientID string, ) (string, error)
GenerateMCPAccessToken mints a short-lived, audience-bound JWT access token for the embedded OAuth 2.1 authorization server (MCP resource). It reuses the existing HS256 signing key so the token is validated by the same code path as session JWTs and PATs, but adds:
- aud = the MCP resource (RFC 8707 audience binding), so the token cannot be replayed at other SolidPing surfaces, and
- the consented scopes (mcp / mcp:read), which the MCP handler enforces.
refreshUID is the user_tokens.uid of the oauth_refresh grant backing this access token — embedded in Claims.RefreshUID so a client authenticated with only the access token can identify (isCurrent) and self-revoke the grant it rides on. ttl is supplied by the caller so the OAuth service controls the access-token lifetime independently of the dashboard's session expiry.
The demo claim is resolved from the user row here rather than left to the RequireMCPAuth backstop. The backstop does re-derive it, but §1 of spec 2026-09-06-02 says the claim is populated wherever claims are minted, and a guard that works only because a second layer repairs the first is exactly the fragility the second layer exists to cover.
func (*Service) GenerateTokensForOAuth ¶
func (s *Service) GenerateTokensForOAuth( ctx context.Context, user *models.User, org *models.Organization, role, method string, authContext Context, ) (*OAuthLoginResponse, error)
GenerateTokensForOAuth generates access and refresh tokens for OAuth login. This is used when a user authenticates via an external OAuth provider (e.g., Slack).
func (*Service) GetAllUserTokens ¶
func (s *Service) GetAllUserTokens( ctx context.Context, userUID, tokenType, callerRefreshUID string, ) (*TokenListResponse, error)
GetAllUserTokens returns all tokens for a user across all orgs (for root-level listing). callerRefreshUID is the caller's own Claims.RefreshUID (empty for PATs), used to flag isCurrent.
func (*Service) GetDeviceConsent ¶
func (s *Service) GetDeviceConsent(ctx context.Context, rawUserCode string) (*DeviceConsentInfo, error)
GetDeviceConsent resolves a live request by user code for the consent page. The user code is the brute-forceable surface, so this lookup is both authenticated and rate limited at the route level.
func (*Service) GetInviteInfo ¶
GetInviteInfo returns public information about an invitation.
func (*Service) GetOrgSettings ¶
GetOrgSettings returns settings for an organization.
func (*Service) GetUserInfo ¶
GetUserInfo returns information about the current user. orgSlug is extracted from the JWT claims.
func (*Service) GetUserTokens ¶
func (s *Service) GetUserTokens( ctx context.Context, orgSlug, userUID, tokenType, callerRefreshUID string, ) (*TokenListResponse, error)
GetUserTokens returns a list of tokens for a user, org-scoped. callerRefreshUID is the caller's own Claims.RefreshUID (empty for PATs), used to flag isCurrent on the caller's own session row.
func (*Service) Impersonate ¶
func (s *Service) Impersonate( ctx context.Context, actorUID, targetUID, orgSlug string, authContext Context, ) (*LoginResponse, error)
Impersonate mints a short-lived access token that acts as targetUID in orgSlug, on behalf of the super admin actorUID (spec 2026-09-29-03).
Modeled on SwitchOrg, with the differences that make it safe:
- the role is the target's REAL membership role, never RoleSuperAdmin, so every permission check downstream runs as the target;
- no refresh token and no user_tokens row: the target's session list is untouched and the token dies after ImpersonationTTL;
- the claims carry ImpersonatedBy, which the middleware uses to deny super admin routes and the credential-changing surface.
The admin's own authentication is what gates this, so a target with 2FA enabled can be impersonated: their 2FA still protects their real sessions.
func (*Service) ImpersonationInfoFor ¶
func (s *Service) ImpersonationInfoFor(ctx context.Context, claims *Claims) *ImpersonationInfo
ImpersonationInfoFor returns the impersonation behind claims, or nil for an ordinary token.
func (*Service) JoinOrgViaLogin ¶
func (s *Service) JoinOrgViaLogin( ctx context.Context, org *models.Organization, user *models.User, opts ...LoginOption, ) (*models.OrganizationMember, bool, error)
JoinOrgViaLogin decides what an authenticated user gets when they complete a login flow that was initiated from org's login page. It is the single admission chokepoint for every federated connector (Microsoft, Google, GitHub, GitLab, Discord, Slack, OIDC, SAML, LDAP) — before it existed each connector carried its own `ensureMembership` copy that added *any* authenticated account to *any* org whose slug appeared in the login URL, bypassing the org's registration.email_pattern entirely.
Admission rules, in order:
- Super admin → no membership row, implicit access (member is nil).
- Existing member → returned as-is (pure login, nothing changes).
- Zero-member org → joins as OWNER (bootstrap / self-hosted onboarding); whoever brings an org into existence owns it.
- Pending invite for the email → joins with the invited role, invite consumed. Only for a verified email (see emailAdmits).
- Slack workspace attestation for the workspace THIS org is linked to → joins as user (see slackWorkspaceAdmits).
- Email matches registration.email_pattern → joins as user. Only for a verified email (see emailAdmits).
- Otherwise → NO membership; a membership_requests row is created or re-opened and pending=true is returned.
The MaxUsers cap (CheckMembershipSlot) is enforced here, once, ahead of any membership creation.
A nil member with pending=false means "no membership row is needed" — only the super-admin case produces that.
func (*Service) ListInvitations ¶
ListInvitations lists pending invitations for an organization.
func (*Service) ListOrgMembershipRequests ¶
func (s *Service) ListOrgMembershipRequests( ctx context.Context, orgSlug string, status models.MembershipRequestStatus, ) (*MembershipRequestAdminListResponse, error)
ListOrgMembershipRequests returns admin-facing rows for an org. The caller is expected to have validated admin role at the handler level.
func (*Service) ListOwnMembershipRequests ¶
func (s *Service) ListOwnMembershipRequests( ctx context.Context, userUID string, ) (*MembershipRequestListResponse, error)
ListOwnMembershipRequests returns the user's own request history with org summaries.
func (*Service) LocalLoginEnabled ¶
LocalLoginEnabled reports whether local password login is enforced on right now. It is resolved per call (env > DB parameter > startup config), and fails open while no SSO provider is available.
func (*Service) Login ¶
func (s *Service) Login( ctx context.Context, orgSlug, email, password string, authContext Context, ) (*LoginResponse, error)
Login authenticates a user and returns access and refresh tokens. orgSlug is treated as a preference — the system will try to honor it but will gracefully fall back to available organizations if the user is not a member.
Credential verification order (spec 2026-07-08-08, part 3 — LDAP bind auth): a local password hash, when the user has one, is always tried first and is the ONLY mechanism attempted for that user — LDAP is never consulted, even on a wrong password. This is deliberate on two counts: it's what keeps the bootstrap super-admin (and anyone else with a local password) able to log in regardless of LDAP being disabled, misconfigured, or unreachable, and it avoids bouncing a merely mistyped local password off the directory, which can trip an Active Directory account-lockout policy on repeated failures. Only a user with NO local password hash — a brand-new identity, or one previously provisioned by LDAP/OIDC/SAML — falls through to the LDAP bind, when configured. See authenticateViaLDAP (ldap_service.go) for why that fallback can never be used to hijack an existing local account.
func (*Service) LogoutOtherSessions ¶
func (s *Service) LogoutOtherSessions(ctx context.Context, userUID, currentRefreshUID string) (*LogoutResponse, error)
LogoutOtherSessions deletes every `refresh`-type session row for the user EXCEPT the one identified by currentRefreshUID (the caller's own session). Unlike LogoutUser, the caller's own session survives — this is a "sign out other devices" action, not a logout, and the caller's access token remains valid until it naturally expires (its own refresh-token row was never touched).
func (*Service) LogoutSession ¶
LogoutSession invalidates the refresh-token session row named by refreshUID, scoped to userUID: a forged or stale RefreshUID can never delete another user's row. This backs the default POST /auth/logout path (spec 2026-09-25-24) — without it, the cookie is cleared but the refresh-token row survives, so anyone holding the refresh token (also returned in the login/logout JSON body) keeps a live sliding session after "logout".
func (*Service) LogoutUser ¶
LogoutUser invalidates all refresh tokens for a user across all orgs.
func (*Service) NotifyContactAdded ¶
func (s *Service) NotifyContactAdded(ctx context.Context, user *models.User, orgUID, display string)
NotifyContactAdded emails the account owner that a notification method was added to their account in an org (spec 2026-11-19-02). A contact receives the org's incident pages from then on, so one added behind the owner's back must not go unnoticed: the same reasoning as the Discord and Telegram link notices. Best effort: the contact is already stored.
func (*Service) NotifyTelegramLinked ¶
NotifyTelegramLinked emails the account owner that a Telegram account was linked to their SolidPing account (spec 2026-11-13-03). With Sign in with Telegram on, the linked chat signs in, and survives a password change and the revocation of every session, so one linked behind the owner's back must not go unnoticed. Best effort, like notifyDiscordLinked: the link is already stored.
It runs from the Telegram webhook, which carries no session claims, so the org the connect link was minted in names the notifications page.
func (*Service) PollDeviceToken ¶
PollDeviceToken is the RFC 8628 §3.4 token endpoint body. It returns the minted PAT once, and an error sentinel mapping to an OAuth error code otherwise.
Delivery is exactly-once: the row is hard-deleted as the gate, and only the caller whose delete affected a row receives the token. A poll that arrives after delivery therefore looks exactly like an unknown device code (expired_token), which is also what a replayed device code should look like.
func (*Service) ReauthenticateForFactor ¶
func (s *Service) ReauthenticateForFactor(ctx context.Context, user *models.User, currentPassword *string) error
ReauthenticateForFactor is reauthenticateForFactor for the routes outside this package that add a sign-in factor: linking a Discord account from a session (spec 2026-11-01-03) binds an identity that signs in. Its errors are the ones WriteReauthError answers.
func (*Service) Recovery2FA ¶
func (s *Service) Recovery2FA( ctx context.Context, tempToken, recoveryCode string, authContext Context, ) (*LoginResponse, error)
Recovery2FA validates a recovery code during login and returns full login tokens.
func (*Service) Refresh ¶
Refresh generates a new access token using a valid refresh token. The org is derived from the refresh token itself.
func (*Service) Register ¶
func (s *Service) Register(ctx context.Context, req RegisterRequest) (*RegisterResponse, error)
Register creates a pending registration entry and sends a confirmation email — unless the email is already registered, in which case it silently no-ops (no pending entry, no email) but still returns registerSuccessResponse, so an anonymous caller cannot use this endpoint to enumerate accounts (spec 2026-09-25-30). ConfirmRegistration keeps its own ErrEmailAlreadyTaken path for the race where an account was created by some OTHER path between Register and confirmation — that caller already proved mailbox ownership by holding the token, so it isn't an enumeration surface.
func (*Service) RejectMembershipRequest ¶
func (s *Service) RejectMembershipRequest( ctx context.Context, decidedByUID, orgSlug, requestUID, reason string, ) error
RejectMembershipRequest moves a request to rejected with an optional reason.
func (*Service) ReportDanglingProviderLinks ¶
ReportDanglingProviderLinks logs, once at startup, how many live organization_providers rows point at an organization that no longer resolves, and publishes the same number as a gauge.
This is the observable half of the heal (spec 2026-08-27-02). The helpers above repair a row only when somebody trips over it — they run inside a login or an install — so until then a dangling link is completely silent: the workspace or guild behind it simply cannot sign in or reinstall, and the only trace is an error line in the server log that nobody is reading. One number at boot turns that into something an operator can see, exactly the way slack.Service.ReportDMCapability does for the im:history scope gap.
Deliberately NOT a repair pass: healing is the callers' job and happens where there is a create path to fall through to. This only counts.
func (*Service) RequestPasswordReset ¶
func (s *Service) RequestPasswordReset( ctx context.Context, req RequestPasswordResetRequest, remoteAddr string, ) (*RequestPasswordResetResponse, error)
RequestPasswordReset creates a password reset token and sends a reset email. Always returns success to the caller (anti-enumeration); the only error path the handler must surface is ErrRateLimited so it can map to 429.
remoteAddr is the request's client IP (best-effort — passed through from the handler). Used solely for the per-IP rate limit; an empty string disables that check.
func (*Service) ResetPassword ¶
func (s *Service) ResetPassword(ctx context.Context, req ResetPasswordRequest) (*ResetPasswordResponse, error)
ResetPassword validates a reset token and sets a new password.
Validation order matters for the regression guarantees in this spec: password length is checked *before* the state entry is touched so a rejected weak password doesn't burn the user's reset opportunity.
func (*Service) RespondToDeviceConsent ¶
func (s *Service) RespondToDeviceConsent( ctx context.Context, claims *Claims, rawUserCode, orgSlug string, approve bool, ) error
RespondToDeviceConsent approves or denies a pending request on behalf of the authenticated user.
On approval it mints a named PAT scoped to orgSlug — the org the user SELECTED on the consent page, which is why the caller passes it explicitly instead of it being read off the session. The compare-and-set that publishes the decision is the authority: if it loses (concurrent decision, expiry), the just-minted PAT is revoked again so a lost race can never leave a usable token behind.
func (*Service) RevokeInvitation ¶
RevokeInvitation revokes an invitation by its UID.
func (*Service) RevokeToken ¶
RevokeToken revokes (deletes) a user token. User-scoped, no org check needed.
func (*Service) SendContactVerificationCode ¶
func (s *Service) SendContactVerificationCode( ctx context.Context, user *models.User, orgUID, address, code string, ) error
SendContactVerificationCode emails the code that confirms an email contact (spec 2026-11-19-02) to the contact's address, which may be anyone's: the mail names the requesting account so a stranger knows what to ignore.
func (*Service) SetEventNotifier ¶
func (s *Service) SetEventNotifier(ctx context.Context, n notifier.EventNotifier)
SetEventNotifier wires the cross-replica bus, late like SetSupportInbox. It starts one goroutine that evicts every revoked hash broadcast on the bus and clears the whole cache when the transport reconnects. The goroutine stops on ctx.Done() or when the notifier closes its channel. Call it once, at boot, before the service serves requests. A nil notifier keeps eviction local.
func (*Service) SetPageMemoInvalidator ¶
func (s *Service) SetPageMemoInvalidator(inv PageMemoInvalidator)
SetPageMemoInvalidator wires the status-page view memo. Optional.
func (*Service) SetSupportInbox ¶
SetSupportInbox wires the support inbox used to detach attribution on org deletion. Late injection: the support service is built after auth, and integrations that own it already import this package.
func (*Service) Setup2FA ¶
func (s *Service) Setup2FA(ctx context.Context, userUID string, req Setup2FARequest) (*Setup2FAResponse, error)
Setup2FA generates a TOTP secret for the user and stores it (not yet enabled). TOTP is a sign-in factor, so the caller re-authenticates first (reauthenticateForFactor): a hijacked session must not be able to enable 2FA with its own authenticator and lock the owner out.
func (*Service) StartDeviceAuthorization ¶
func (s *Service) StartDeviceAuthorization( ctx context.Context, clientName string, requester DeviceRequester, ) (*DeviceAuthorizationResponse, error)
StartDeviceAuthorization opens a new device-authorization request. It is unauthenticated: anyone may ask for a request to be opened, but it grants nothing until a logged-in user approves it and it is bound to the org that user selects.
func (*Service) SwitchOrg ¶
func (s *Service) SwitchOrg( ctx context.Context, userUID, targetOrgSlug string, authContext Context, ) (*LoginResponse, error)
SwitchOrg switches the user's current organization context. It verifies membership and mints new tokens scoped to the target org.
func (*Service) UpdateOrgProfile ¶
func (s *Service) UpdateOrgProfile( ctx context.Context, orgSlug string, userUID string, req UpdateOrgProfileRequest, authContext Context, ) (*OrgProfileResponse, error)
UpdateOrgProfile changes an organization's name, slug and/or logo URL. Owner-only — the route is guarded by middleware.RequireOrgOwner; this function assumes that check already ran.
Renaming the slug is the interesting part. It moves every URL of the organization, including the intentionally public ones customers have pasted elsewhere (status pages, SVG badges, the /embed/v1 widget). Those links keep working: the old slug is recorded as an alias (models.OrganizationPreviousSlug) and middleware.OrgSlugRedirect answers a permanent redirect to the new one. Two rules bound that promise:
- An alias can never shadow the organization now living at that slug — resolution tries the live slug first, and db.UpdateOrganization / db.CreateOrganization release any alias on a slug they hand out.
- The guarantee lasts only until another organization claims the freed slug, which is what the dashboard warns about before saving.
func (*Service) UpdateOrgSettings ¶
func (s *Service) UpdateOrgSettings( ctx context.Context, orgSlug string, req UpdateOrgSettingsRequest, ) (*OrgSettingsResponse, error)
UpdateOrgSettings updates settings for an organization.
func (*Service) UpdateProfile ¶
func (s *Service) UpdateProfile(ctx context.Context, claims *Claims, req UpdateProfileRequest) (*MeResponse, error)
UpdateProfile updates the current user's profile fields. Every field is optional: a preferences-only PATCH is as valid as a name-only one.
func (*Service) ValidatePATToken ¶
ValidatePATToken validates a Personal Access Token.
func (*Service) ValidateToken ¶
ValidateToken validates a JWT or PAT token and returns its claims.
type Setup2FARequest ¶
type Setup2FARequest struct {
CurrentPassword *string `json:"currentPassword,omitempty"`
}
Setup2FARequest is the body of POST /auth/2fa/setup. CurrentPassword is required when the account has a password; an account without one must have signed in within the last 10 minutes instead.
type Setup2FAResponse ¶
type Setup2FAResponse struct {
URI string `json:"uri"`
Secret string `json:"secret"`
// SetupToken binds the confirm step to this secret and to the
// re-authentication that produced it (spec 2026-10-31-02). It expires
// after 10 minutes; POST /auth/2fa/confirm requires it.
SetupToken string `json:"setupToken"`
}
Setup2FAResponse contains the TOTP setup data.
type SlackExchangeResult ¶
type SlackExchangeResult struct {
AccessToken string `json:"accessToken"`
RefreshToken string `json:"refreshToken"`
// ExpiresIn is the access token's lifetime in seconds, so the dashboard
// can compute an absolute expiry exactly like every other login path
// (see auth.slack.complete.tsx) instead of assuming the configured
// default.
ExpiresIn int `json:"expiresIn"`
OrgSlug string `json:"orgSlug"`
UserUID string `json:"userUid"`
// ChannelUID is set when the install was triggered from a channel edit page.
// The dashboard uses it to navigate back to that channel after login.
ChannelUID string `json:"channelUid,omitempty"`
}
SlackExchangeResult is what the exchange endpoint returns to the dashboard. It mirrors the payload stashed by the Slack integration's post-callback IssueExchangeCode call.
type SlackOAuthHandler ¶
type SlackOAuthHandler struct {
base.HandlerBase
// contains filtered or unexported fields
}
SlackOAuthHandler handles Slack OAuth authentication endpoints.
func NewSlackOAuthHandler ¶
func NewSlackOAuthHandler(service *SlackOAuthService, cfg *config.Config) *SlackOAuthHandler
NewSlackOAuthHandler creates a new Slack OAuth handler.
func (*SlackOAuthHandler) Callback ¶
func (h *SlackOAuthHandler) Callback(writer http.ResponseWriter, req *http.Request) error
Callback handles the OAuth callback from Slack. GET /api/v1/auth/slack/callback?code=...&state=...
func (*SlackOAuthHandler) Exchange ¶
func (h *SlackOAuthHandler) Exchange(writer http.ResponseWriter, req *http.Request) error
Exchange trades a single-use install-callback code for the freshly minted session tokens. The dashboard calls this server-to-server immediately after landing on /d/auth/slack/complete.
TODO(remove after next release): spec 2026-09-25-12 oauth-callback-one-time-code-exchange. The Slack install callback now hands off through authhandoff and /d/auth/complete like every other federated login; this endpoint only redeems a `slack-exchange` code minted by a pod still running the previous release.
POST /api/v1/auth/slack/exchange body: {"code": "..."}.
func (*SlackOAuthHandler) Login ¶
func (h *SlackOAuthHandler) Login(writer http.ResponseWriter, req *http.Request) error
Login initiates the Slack OAuth flow. GET /api/v1/auth/slack/login?redirect_uri=...
type SlackOAuthResult ¶
type SlackOAuthResult = ProviderOutcome
SlackOAuthResult contains the result of a successful Slack OAuth flow. It is the ProviderOutcome every federated callback hands to finishProviderCallback.
type SlackOAuthService ¶
type SlackOAuthService struct {
// contains filtered or unexported fields
}
SlackOAuthService handles Slack OAuth authentication logic.
func NewSlackOAuthService ¶
func NewSlackOAuthService(dbService db.Service, cfg *config.Config, authService *Service) *SlackOAuthService
NewSlackOAuthService creates a new Slack OAuth service.
func (*SlackOAuthService) ExchangeSlackInstallCode ¶
func (s *SlackOAuthService) ExchangeSlackInstallCode( ctx context.Context, code string, ) (*SlackExchangeResult, error)
ExchangeSlackInstallCode validates a single-use code minted by the Slack integration's install callback and returns the freshly minted session tokens. The code is consumed on success — repeat calls fail.
func (*SlackOAuthService) GenerateOAuthState ¶
func (s *SlackOAuthService) GenerateOAuthState(ctx context.Context, redirectURI string) (string, error)
GenerateOAuthState mints an OAuth state for the Sign-in-with-Slack flow. The redirectURI is stashed in the entry payload so the callback can route the user back where they came from.
func (*SlackOAuthService) HandleCallback ¶
func (s *SlackOAuthService) HandleCallback(ctx context.Context, code string) (*SlackOAuthResult, error)
HandleCallback processes the OAuth callback from Slack.
func (*SlackOAuthService) ValidateOAuthState ¶
func (s *SlackOAuthService) ValidateOAuthState(ctx context.Context, stateParam string) (*OAuthState, error)
ValidateOAuthState validates and consumes a Sign-in-with-Slack OAuth state.
type SwitchOrgRequest ¶
type SwitchOrgRequest struct {
Org string `json:"org"`
}
SwitchOrgRequest represents a switch-org request body.
type TelegramIdentity ¶
type TelegramIdentity struct {
ID int64
FirstName string
LastName string
Username string
PhotoURL string
AuthDate time.Time
}
TelegramIdentity is a verified Telegram login result.
func VerifyTelegramLogin ¶
func VerifyTelegramLogin(fields map[string]string, botToken string, now time.Time) (*TelegramIdentity, error)
VerifyTelegramLogin checks a Telegram login result (the key/value pairs the Login Widget or oauth.telegram.org hands back) against the bot token.
The hash is HMAC-SHA256 of the data-check string — every received field but `hash`, as `key=value`, sorted by key and joined with '\n' — keyed by the SHA-256 of the bot token. Every received field is covered, not just the ones we read, so a field Telegram adds later does not break the check and a field an attacker adds does.
auth_date must be within telegramAuthMaxAge of now: a captured result must not sign anyone in later.
type TelegramLoginHandler ¶
type TelegramLoginHandler struct {
base.HandlerBase
// contains filtered or unexported fields
}
TelegramLoginHandler handles the Sign in with Telegram endpoints.
func NewTelegramLoginHandler ¶
func NewTelegramLoginHandler(service *TelegramLoginService, cfg *config.Config) *TelegramLoginHandler
NewTelegramLoginHandler creates a new Telegram login handler.
func (*TelegramLoginHandler) Callback ¶
func (h *TelegramLoginHandler) Callback(writer http.ResponseWriter, req *http.Request) error
Callback receives the browser back from Telegram. GET /api/v1/auth/telegram/callback?state=...[&tgAuthResult=...|&id=...&hash=...].
func (*TelegramLoginHandler) Login ¶
func (h *TelegramLoginHandler) Login(writer http.ResponseWriter, req *http.Request) error
Login sends the browser to Telegram's login page. GET /api/v1/auth/telegram/login?org=...&redirect_uri=...
org is optional: it only picks the org to sign in to when the Telegram account is linked in several.
type TelegramLoginService ¶
type TelegramLoginService struct {
// contains filtered or unexported fields
}
TelegramLoginService handles Sign in with Telegram.
func NewTelegramLoginService ¶
func NewTelegramLoginService(dbService db.Service, cfg *config.Config, authService *Service) *TelegramLoginService
NewTelegramLoginService creates a new Telegram login service.
func (*TelegramLoginService) GenerateOAuthState ¶
func (s *TelegramLoginService) GenerateOAuthState( ctx context.Context, redirectURI, orgSlug string, ) (string, error)
GenerateOAuthState creates a single-use login state and stores it.
func (*TelegramLoginService) HandleCallback ¶
func (s *TelegramLoginService) HandleCallback( ctx context.Context, fields map[string]string, orgSlug string, ) (*ProviderOutcome, error)
HandleCallback verifies a Telegram login result and signs in the user who linked that Telegram account.
Only a verified `telegram` contact counts as a link: it is created when the user presses Start in a private chat with the instance bot, so its value (the private chat id) is the Telegram user id and the link proves the user controls that account. There is no auto-registration: Telegram returns no email address to create an account with.
func (*TelegramLoginService) ValidateOAuthState ¶
func (s *TelegramLoginService) ValidateOAuthState(ctx context.Context, stateParam string) (*OAuthState, error)
ValidateOAuthState validates and consumes a login state.
type TokenCreatedWith ¶
type TokenCreatedWith struct {
Method string `json:"method,omitempty"`
UserAgent string `json:"userAgent,omitempty"`
RemoteAddr string `json:"remoteAddr,omitempty"`
}
TokenCreatedWith is the camelCase projection of a user_tokens row's properties.created_with metadata — the login method and request context recorded when the token (session or PAT) was minted.
type TokenInfo ¶
type TokenInfo struct {
UID string `json:"uid"`
Name string `json:"name,omitempty"`
Type string `json:"type"`
OrgSlug string `json:"orgSlug,omitempty"`
CreatedAt time.Time `json:"createdAt"`
// LastUsedAt is kept for back-compat with existing PAT consumers.
// LastActiveAt duplicates the same value under the name the sessions UI
// expects; both are populated for every token type.
LastUsedAt *time.Time `json:"lastUsedAt,omitempty"`
LastActiveAt *time.Time `json:"lastActiveAt,omitempty"`
ExpiresAt *time.Time `json:"expiresAt,omitempty"`
// IsCurrent is set on the row that issued the caller's own access token —
// its uid matches the caller's Claims.RefreshUID. That covers both a
// session `refresh` row (the dashboard's "this device") and an
// `oauth_refresh` grant (an MCP client / CLI identifying the grant it
// rides on). Always false for `pat` rows, which never back a RefreshUID.
IsCurrent bool `json:"isCurrent,omitempty"`
// CreatedWith surfaces the login-method forensics recorded at token
// creation (properties.created_with) as camelCase fields. Nil when the
// row predates this metadata or carries none (e.g. PATs).
CreatedWith *TokenCreatedWith `json:"createdWith,omitempty"`
Properties map[string]interface{} `json:"properties,omitempty"`
}
TokenInfo represents a user token for listing.
type TokenListResponse ¶
type TokenListResponse struct {
Data []TokenInfo `json:"data"`
}
TokenListResponse contains a list of tokens.
type TwoFAClaims ¶
type TwoFAClaims struct {
UserUID string `json:"userUid"`
OrgSlug string `json:"orgSlug"`
Role string `json:"role"`
Purpose string `json:"purpose"`
// Method carries the FIRST factor across the 2FA hand-off, so the audit
// trail can record "password+totp" rather than losing how the user proved
// themselves before the code prompt. Empty on tokens minted before this
// field existed; withSecondFactor defaults those to password.
Method string `json:"method,omitempty"`
jwt.RegisteredClaims
}
TwoFAClaims represents JWT claims for the temporary 2FA token.
type UpdateOrgProfileRequest ¶
type UpdateOrgProfileRequest struct {
Name *string
Slug *string
LogoURL *string
// LogoURLSet reports that the request carried a logoUrl key at all. With
// LogoURL nil (or empty) it means "clear the logo".
LogoURLSet bool
}
UpdateOrgProfileRequest is the body of PATCH /api/v1/orgs/:org.
Every field is optional with PATCH semantics, which forces a distinction JSON pointers alone cannot express: "logoUrl absent" (leave it alone) versus "logoUrl: null" (clear it). The custom UnmarshalJSON records presence per field, so LogoURLSet is what decides whether the column is touched at all.
func (*UpdateOrgProfileRequest) UnmarshalJSON ¶
func (r *UpdateOrgProfileRequest) UnmarshalJSON(data []byte) error
UnmarshalJSON decodes the request while tracking which keys were present.
type UpdateOrgSettingsRequest ¶
type UpdateOrgSettingsRequest struct {
RegistrationEmailPattern *string `json:"registrationEmailPattern"`
// SessionMaxDurationSeconds, when present: a value <= 0 clears the org
// override (the org falls back to the system-wide value); a positive
// value sets/replaces it. Omit the field entirely to leave the
// override untouched.
SessionMaxDurationSeconds *int `json:"sessionMaxDurationSeconds"`
// DefaultEscalationPolicyUID, when present: an empty string clears the org
// default (checks fall back to no policy); a non-empty UID sets it (the UID
// must be a policy in this org). Omit the field to leave it untouched.
DefaultEscalationPolicyUID *string `json:"defaultEscalationPolicyUid"`
// TracerouteOnFailure sets the org-level path-trace default (spec
// 2026-08-21-10). Omit to leave it unchanged.
TracerouteOnFailure *bool `json:"tracerouteOnFailure"`
// StatusPageAllowedEmbedOrigins replaces the status-page embed allowlist
// (spec 2026-09-25-28). Each entry must be a scheme+host origin such as
// https://intranet.acme.com; an empty array clears it. Omit to leave it
// unchanged.
StatusPageAllowedEmbedOrigins *[]string `json:"statusPageAllowedEmbedOrigins"`
// ReminderIntervalSeconds sets the org default reminder interval (spec
// 2026-10-12-16): 0 turns reminders off, otherwise 900..86400 seconds.
// Omit to leave it unchanged.
ReminderIntervalSeconds *int `json:"reminderIntervalSeconds"`
// BrowserSealingMode sets `optional` or `required` (spec 2026-11-08-01).
// Switching never touches stored checks. Omit to leave it unchanged.
BrowserSealingMode *string `json:"browserSealingMode"`
}
UpdateOrgSettingsRequest contains the request data for updating org settings.
type UpdateProfileRequest ¶
type UpdateProfileRequest struct {
Name *string `json:"name"`
// Email changes the sign-in address (spec 2026-09-30-08). It requires
// CurrentPassword, and is refused for password-less, demo and
// impersonation sessions.
Email *string `json:"email,omitempty"`
CurrentPassword *string `json:"currentPassword,omitempty"`
// Preferences updates the language and timezone of the user's emails,
// field by field (spec 2026-10-21-01).
Preferences *PreferencesRequest `json:"preferences,omitempty"`
}
UpdateProfileRequest contains the fields that can be updated on the user profile.
type UserInfo ¶
type UserInfo struct {
UID string `json:"uid"`
Email string `json:"email"`
Name string `json:"name,omitempty"`
AvatarURL string `json:"avatarUrl,omitempty"`
Role string `json:"role"`
// MustChangePassword is the machine-readable signal that this session may
// do nothing but rotate its password (spec 2026-08-23-04). It rides on every
// login-shaped response and on /auth/me, so a client routes to its
// "set a new password" screen PROACTIVELY instead of discovering the state
// by tripping a 403 it would otherwise render as a dead "Permission denied".
//
// omitempty on purpose: the field is only ever meaningful when true, and
// UserInfo is also used to describe OTHER people (the membership-request
// admin view), where a user's pending-rotation state is none of the
// viewer's business — see newUserInfo's doc.
MustChangePassword bool `json:"mustChangePassword,omitempty"`
// Demo marks this session as the shared public-demo principal (spec
// 2026-09-06-02). Like MustChangePassword it rides on every login-shaped
// response and on /auth/me, so the dashboard shows the "everything here is
// shared and expires" banner and hides the actions the guard would refuse,
// PROACTIVELY, rather than by tripping a 403 it would render as a dead
// "Permission denied".
//
// omitempty for the same reason: it is only meaningful when true, and
// UserInfo also describes OTHER people (the membership-request admin
// view), where it would be noise.
Demo bool `json:"demo,omitempty"`
// MustChangeEmail asks the forced first-login screen to also collect a
// real email (spec 2026-10-13-02). It holds only while the account must
// rotate its password AND still signs in with the published seed address
// (defaults.Email), so a seed made with SP_ADMIN_EMAIL, an ordinary
// forced reset, or an account with a real address never sees it.
// omitempty for the same reason as MustChangePassword.
MustChangeEmail bool `json:"mustChangeEmail,omitempty"`
// Preferences is the language and timezone the server writes to this user
// in (spec 2026-10-21-01). newUserInfo always sets it, {} when nothing is
// stored, so the dashboard knows to report the browser's values. omitempty
// keeps it out of the descriptions of OTHER people.
Preferences *models.UserPreferences `json:"preferences,omitempty"`
}
UserInfo represents user information returned in responses.
type Verify2FARequest ¶
type Verify2FARequest struct {
Code string `json:"code"`
}
Verify2FARequest contains the request data for verifying a 2FA code.
Source Files
¶
- audit.go
- autojoin_regex.go
- contact_notice.go
- demo_guard.go
- device_handler.go
- device_service.go
- discord.go
- discord_link.go
- discord_link_notice.go
- discord_service.go
- email_change.go
- factor_reauth.go
- github.go
- github_service.go
- gitlab.go
- gitlab_service.go
- google.go
- google_service.go
- handler.go
- handoff_exchange.go
- impersonate.go
- impersonation_guard.go
- join_policy.go
- jwt_keys.go
- ldap_service.go
- local_login.go
- mcp_credential_guard.go
- membership_requests.go
- membership_requests_handler.go
- microsoft.go
- microsoft_service.go
- oidc.go
- oidc_groups.go
- oidc_service.go
- org_delete.go
- org_profile.go
- orgaccess.go
- passkey_aaguid.go
- passkey_handler.go
- passkey_notice.go
- passkey_service.go
- passkey_session.go
- passkey_user.go
- password_rotation.go
- pat_cache.go
- pat_guard.go
- personal_org.go
- post_login_redirect.go
- preferences.go
- provider_links.go
- providers_available.go
- registration_ip_limit.go
- saml.go
- saml_service.go
- service.go
- signup_analytics.go
- signup_attribution.go
- slack.go
- slack_service.go
- sso_guard.go
- telegram.go
- telegram_link_notice.go
- telegram_service.go
- totp_replay.go