auth

package
v0.8.0 Latest Latest
Warning

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

Go to latest
Published: Sep 23, 2026 License: Apache-2.0 Imports: 31 Imported by: 0

Documentation

Overview

Package auth - Admin authentication service for admin users

Package auth provides authentication services for both users and admins

Package auth - passwordless OAuth/OIDC user authentication service.

OAuth users are the standalone-IdP (ESP User) identities that authenticate via email/phone OTP or social federation, NOT Cognito. They have no password, so every password-shaped operation is unsupported here; identities live in espuser-user-details and tokens are minted/rotated against espuser-refresh-tokens. Spec: espuser/docs/en/specs/auth-flows.md.

Index

Constants

View Source
const FlowTTL = 10 * time.Minute

FlowTTL bounds the whole login (authorize -> OTP -> code exchange).

Variables

View Source
var (
	ErrMissingToken = fmt.Errorf("authorization token is required")
	ErrNotAdmin     = fmt.Errorf("admin privilege required")
)

Sentinel errors from RequireAdmin so callers can map to HTTP status without HTTP types leaking here.

View Source
var (
	ErrInvalidClient   = fmt.Errorf("invalid_client")
	ErrInvalidRedirect = fmt.Errorf("invalid_redirect_uri")
	ErrInvalidRequest  = fmt.Errorf("invalid_request")
	ErrInvalidScope    = fmt.Errorf("invalid_scope")
	ErrInvalidGrant    = fmt.Errorf("invalid_grant")
)

Authorize sentinels. StartAuthFlow's failures pick the handler's surface (error page vs redirect); ExchangeAuthCode collapses every code failure to ErrInvalidGrant (no oracle).

View Source
var ErrContactsOnDifferentUsers = fmt.Errorf("verified contacts resolve to different users")

ErrContactsOnDifferentUsers means the two contacts already belong to separate accounts. Picking one would either strand data or attach this login to the wrong account, so the caller is told.

View Source
var ErrUntrustedIssuer = errors.New("untrusted token issuer")

AuthService resolves and verifies a caller against the provider that issued their token. Both implementations are reached only through the factory, which routes on the token's issuer: OIDC end users to the passwordless service, Cognito admins to the admin one. ErrUntrustedIssuer means the token names no issuer this deployment verifies, so no service can speak for it — an authentication failure, not an authorization one.

Functions

func IsUserAlreadyExistsError

func IsUserAlreadyExistsError(err error) bool

IsUserAlreadyExistsError checks if an error indicates that a user already exists

func IsUserNotConfirmedError

func IsUserNotConfirmedError(err error) bool

func IsUserNotExistsError

func IsUserNotExistsError(err error) bool

IsUserNotExistsError checks if an error indicates that a user does not exist

Types

type AdminAuthService

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

func NewAdminAuthService

func NewAdminAuthService(ctx context.Context) (*AdminAuthService, error)

func (*AdminAuthService) GetUserFromProvider

func (s *AdminAuthService) GetUserFromProvider(ctx context.Context, providerUserID string) (UserInfo, error)

func (*AdminAuthService) GetUserFromProviderUsingToken

func (s *AdminAuthService) GetUserFromProviderUsingToken(ctx context.Context, token string) (UserInfo, error)

func (*AdminAuthService) ParseUserInfoFromToken

func (s *AdminAuthService) ParseUserInfoFromToken(ctx context.Context, token string) (UserInfo, error)

func (*AdminAuthService) VerifyToken

func (s *AdminAuthService) VerifyToken(ctx context.Context, token string) error

func (*AdminAuthService) VerifyTokenPair

func (s *AdminAuthService) VerifyTokenPair(ctx context.Context, accessToken, idToken string) error

VerifyToken validates the Cognito token against the admin pool JWKS only (no live GetUser).

type AuthService

type AuthService interface {
	// GetUserFromProvider resolves a provider identity (OIDC sub, or Cognito username) to a user.
	GetUserFromProvider(ctx context.Context, providerUserID string) (UserInfo, error)

	// GetUserFromProviderUsingToken verifies the token against its provider, then resolves the caller.
	GetUserFromProviderUsingToken(ctx context.Context, token string) (UserInfo, error)

	// VerifyToken validates signature and claims only, resolving no user.
	VerifyToken(ctx context.Context, token string) error

	// VerifyTokenPair validates an access token and an id token and requires both to come
	// from one sign-in, for a caller handed the two halves by different routes.
	VerifyTokenPair(ctx context.Context, accessToken, idToken string) error
}

type AuthServiceFactory

type AuthServiceFactory interface {
	// CreateAuthServiceFromAPIRequest resolves the service + caller identity from the request (OIDC end user or Cognito admin).
	CreateAuthServiceFromAPIRequest(ctx context.Context, request events.APIGatewayProxyRequest) (AuthService, string, error)

	// CreateAuthServiceForToken selects the service verifying a bearer token, routed by the token's iss (OIDC user service, or Cognito admin).
	CreateAuthServiceForToken(ctx context.Context, token string) (AuthService, error)

	CreateUserAuthService(ctx context.Context) AuthService

	CreateAdminAuthService(ctx context.Context) AuthService
}

func NewAuthServiceFactory

func NewAuthServiceFactory() AuthServiceFactory

type AuthorizeRequest

type AuthorizeRequest struct {
	ClientID            string
	RedirectURI         string
	Scope               string
	State               string
	CodeChallenge       string
	CodeChallengeMethod string
}

type DefaultAuthServiceFactory

type DefaultAuthServiceFactory struct{}

func (*DefaultAuthServiceFactory) CreateAdminAuthService

func (f *DefaultAuthServiceFactory) CreateAdminAuthService(ctx context.Context) AuthService

func (*DefaultAuthServiceFactory) CreateAuthServiceForToken

func (f *DefaultAuthServiceFactory) CreateAuthServiceForToken(ctx context.Context, token string) (AuthService, error)

func (*DefaultAuthServiceFactory) CreateAuthServiceFromAPIRequest

func (f *DefaultAuthServiceFactory) CreateAuthServiceFromAPIRequest(ctx context.Context, request events.APIGatewayProxyRequest) (AuthService, string, error)

func (*DefaultAuthServiceFactory) CreateUserAuthService

func (f *DefaultAuthServiceFactory) CreateUserAuthService(ctx context.Context) AuthService

type OAuthUserAuthService

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

OAuthUserAuthService handles authentication for passwordless OIDC users. issuer and jwks are resolved once at construction. There is intentionally no single client id: this service verifies tokens from every registered client (rm_mobile, va-client, mcp-oauth-client, ...); the per-call clientID is passed to the mint/refresh methods.

func NewOAuthUserAuthService

func NewOAuthUserAuthService(ctx context.Context) (*OAuthUserAuthService, error)

func (*OAuthUserAuthService) CompleteAuthFlowForSubject

func (s *OAuthUserAuthService) CompleteAuthFlowForSubject(ctx context.Context, flowID, userID string) (redirectTo string, err error)

func (*OAuthUserAuthService) ExchangeAuthCode

func (s *OAuthUserAuthService) ExchangeAuthCode(ctx context.Context, code, verifier, clientID, redirectURI string) (*UserTokens, error)

ExchangeAuthCode redeems a code for tokens: verify client/redirect/PKCE, consume (single-use), mint. Every failure is ErrInvalidGrant (no oracle).

func (*OAuthUserAuthService) GetUserFromProvider

func (s *OAuthUserAuthService) GetUserFromProvider(ctx context.Context, sub string) (UserInfo, error)

GetUserFromProvider resolves the OIDC provider identity — the `sub`, which is the opaque user_id — to a user. The subject is treated as opaque and never re-derived from email/phone.

func (*OAuthUserAuthService) GetUserFromProviderUsingToken

func (s *OAuthUserAuthService) GetUserFromProviderUsingToken(ctx context.Context, token string) (UserInfo, error)

GetUserFromProviderUsingToken verifies the RS256 access token and resolves its subject to a user.

func (*OAuthUserAuthService) MintTokenSet

func (s *OAuthUserAuthService) MintTokenSet(ctx context.Context, userID, clientID, scope string) (*UserTokens, error)

func (*OAuthUserAuthService) ParseUserInfoFromToken

func (s *OAuthUserAuthService) ParseUserInfoFromToken(ctx context.Context, token string) (UserInfo, error)

ParseUserInfoFromToken verifies our RS256 token and maps its claims to a UserInfo. The token already carries the (scope-gated) sub/email/phone we minted, so no user-details lookup is needed. This is a resource-server path, so only an access token is accepted: an id token (meant for the client) must not be replayable here (RFC 9700 token substitution).

func (*OAuthUserAuthService) RefreshToken

func (s *OAuthUserAuthService) RefreshToken(ctx context.Context, clientID, refreshToken string) (*UserTokens, error)

RefreshToken rotates the opaque refresh token (rotate-on-use + reuse detection); a replayed spent token revokes the whole family.

func (*OAuthUserAuthService) ResolveOrCreateUser

func (s *OAuthUserAuthService) ResolveOrCreateUser(rmngCtx *rmngctx.RmngContext, username string, profile *user_details_db.UpstreamProfile) (string, error)

The contact is what identifies the person, so one verified email reaches the same account whichever provider authenticated it. profile carries claims a federated login brought along and may be nil; they are stored with the account at creation.

func (*OAuthUserAuthService) ResolveOrCreateUserByContacts

func (s *OAuthUserAuthService) ResolveOrCreateUserByContacts(rmngCtx *rmngctx.RmngContext, email, phone string, profile *user_details_db.UpstreamProfile) (string, error)

ResolveOrCreateUserByContacts resolves a login that vouched for an email, a phone, or both. Either contact finds the account, and a contact the account was missing is recorded, so the same person stays one user however they sign in next.

func (*OAuthUserAuthService) RevokeRefreshToken

func (s *OAuthUserAuthService) RevokeRefreshToken(ctx context.Context, refreshToken string) error

RevokeRefreshToken revokes the presented token's whole family (RFC 7009 §2.1: revoking a token MAY revoke the underlying grant — here the login's family), which also ends the session. Errors are swallowed so the endpoint stays a non-oracle 200 (§2.2). Access tokens are stateless RS256 JWTs and cannot be revoked server-side, so the §2.2 SHOULD for access tokens does not apply.

func (*OAuthUserAuthService) StartAuthFlow

func (s *OAuthUserAuthService) StartAuthFlow(ctx context.Context, req AuthorizeRequest) (flowID string, err error)

StartAuthFlow validates the request, writes a LOGIN flow record, and returns its opaque flow id. Errors are typed so the handler knows whether it may redirect (scope) or must render the error page (client/redirect/PKCE).

func (*OAuthUserAuthService) VerifyToken

func (s *OAuthUserAuthService) VerifyToken(ctx context.Context, token string) error

VerifyToken validates the RS256 token against the issuer's JWKS only (no user-details lookup).

func (*OAuthUserAuthService) VerifyTokenPair

func (s *OAuthUserAuthService) VerifyTokenPair(ctx context.Context, accessToken, idToken string) error

VerifyTokenPair verifies the two halves of one sign-in and requires both to name the first-party client. The voice-assistant and MCP audiences are delegated to third parties, so a pair minted for one of them must not be exchanged for credentials, whatever else it is allowed to do. Pinned here rather than in verifyOwnToken because those audiences may legitimately call the ordinary APIs; they just may not vend credentials.

type UserInfo

type UserInfo struct {
	Email           string `json:"email,omitempty"`
	PhoneNumber     string `json:"phone_number,omitempty"`
	CognitoUsername string `json:"cognito_username,omitempty"`
	UserID          string `json:"user_id,omitempty"`
	IsSuperAdmin    bool   `json:"is_super_admin"`
	IsAdmin         bool   `json:"is_admin"`
	Sub             string `json:"sub,omitempty"`

	Name    string `json:"name,omitempty"`
	Locale  string `json:"locale,omitempty"`
	Picture string `json:"picture,omitempty"`
}

UserInfo carries the resolved caller. IsAdmin — set when the caller was resolved through the admin Cognito pool — is the only privilege field any authorisation decision reads. IsSuperAdmin mirrors the pool's `custom:super_admin` attribute so the flag survives on existing accounts, but nothing authorises on it.

func RequireAdmin

func RequireAdmin(ctx context.Context, token string) (UserInfo, error)

RequireAdmin returns the caller's UserInfo if the token verifies against the admin user pool (empty ⇒ ErrMissingToken, anything the admin pool did not issue ⇒ ErrNotAdmin). Membership of the admin pool is the whole privilege: there is no second tier above it.

type UserTokens

type UserTokens struct {
	AccessToken        string `json:"access_token"`
	RefreshToken       string `json:"refresh_token,omitempty"`
	IDToken            string `json:"id_token,omitempty"`
	TokenType          string `json:"token_type"`
	ExpiresIn          int    `json:"expires_in"`
	MustChangePassword bool   `json:"must_change_password,omitempty"`
}

JSON tags are the OAuth 2.0 token-response names (RFC 6749 §5.1); id_token is omitempty since it is present only when openid is in scope.

Jump to

Keyboard shortcuts

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