Documentation
¶
Overview ¶
Package iam is a provider-agnostic, token-format-agnostic authentication and authorization library.
The application talks to the Service interface only. New returns the default, in-process implementation; because every method takes and returns plain data, the same interface can later be served by a remote IAM.
IAM owns sessions, tokens, policy evaluation and audit events. The application owns users: it implements UserStore (subjects, roles and linked identities) and decides how sign-in is presented.
Index ¶
- Variables
- type AuthRequest
- type ClientInfo
- type CompletePasswordResetRequest
- type Config
- type EmailVerificationRequest
- type IdentityStore
- type InviteRequest
- type IssuedInvite
- type IssuedToken
- type LoginResult
- type MFA
- type MFAConfig
- type MFARequest
- type MFARequiredError
- type PasswordResetRequest
- type RateLimitConfig
- type RateLimitError
- type Recovery
- type RecoveryConfig
- type Service
- type SessionInfo
- type SignUpRequest
- type SignupConfig
- type SignupGrant
- type Subject
- type SubjectDeleter
- type SubjectLoader
- type TOTPEnrollment
- type TokenPair
- type UserStore
- type VerifiedEmail
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // ErrUnknownProvider is returned when AuthRequest.Provider is not configured. ErrUnknownProvider = errors.New("iam: unknown provider") // ErrModeNotAllowed is returned when a login asks for a session mode // that is not in Config.AllowedModes. ErrModeNotAllowed = errors.New("iam: session mode not allowed") // ErrSignupClosed is returned by SignUp when the sign-up policy is Closed. ErrSignupClosed = errors.New("iam: sign-up is closed") // ErrInvalidInvite is returned for unknown, used, expired or // mismatched invites. ErrInvalidInvite = invite.ErrInvalid // ErrAlreadyRegistered is returned by SignUp when the identity is // already linked to a subject. ErrAlreadyRegistered = errors.New("iam: identity is already registered") // ErrRateLimited is wrapped by *RateLimitError. ErrRateLimited = errors.New("iam: too many attempts") )
var ( // ErrInvalidCredentials is returned (wrapped) for failed logins. ErrInvalidCredentials = provider.ErrInvalidCredentials // ErrInvalidSession is returned for unknown, expired or revoked session // tokens and refresh tokens. ErrInvalidSession = session.ErrInvalid // ErrRefreshReused is returned when a rotated refresh token is reused; // the session has been revoked. ErrRefreshReused = session.ErrReused // ErrRefreshRaced is returned when a just-rotated refresh token is // reused within the configured grace window; the session is kept. ErrRefreshRaced = session.ErrRaced // subject (for example a database timeout). It says nothing about the // credential: the caller should answer "try again" (HTTP 503), not // treat the request as anonymous. The session is left untouched. ErrUnavailable = errors.New("iam: authentication backend unavailable") )
var ( // ErrMFARequired is wrapped by *MFARequiredError. ErrMFARequired = errors.New("iam: a second factor is required") // ErrMFANotConfigured is returned by MFA methods when Config.MFA.Store // is not set. ErrMFANotConfigured = errors.New("iam: multi-factor authentication is not configured") // ErrInvalidMFACode is returned for a wrong, reused or expired code, a // used recovery code, or an invalid or expired challenge. ErrInvalidMFACode = errors.New("iam: invalid authentication code") // ErrMFAAlreadyEnrolled is returned by BeginTOTPEnrollment when the // subject already has a confirmed factor. Disable it first. ErrMFAAlreadyEnrolled = errors.New("iam: a second factor is already enrolled") // ErrMFANotEnrolled is returned when the subject has no confirmed factor // (or, for ConfirmTOTPEnrollment, no pending one). ErrMFANotEnrolled = errors.New("iam: no second factor is enrolled") )
var ( // ErrRecoveryNotConfigured is returned by Recovery methods when // Config.Recovery.Tokens is not set, or (for password reset) when no // provider can set passwords. ErrRecoveryNotConfigured = errors.New("iam: password reset and email verification are not configured") // ErrInvalidOneTimeToken is returned for unknown, used or expired // password-reset and email-verification tokens, and for a token used // for the wrong purpose or whose subject is gone. ErrInvalidOneTimeToken = onetime.ErrInvalid // ErrInvalidEmail is returned by StartEmailVerification for an address // that cannot be one. ErrInvalidEmail = errors.New("iam: invalid email address") )
var ( // ErrNotFound is returned by stores when a record does not exist. ErrNotFound = errors.New("iam: not found") // ErrConflict is returned by stores when a record already exists. ErrConflict = errors.New("iam: already exists") // ErrIdentityLinked is returned when a provider identity already // belongs to a different subject. ErrIdentityLinked = errors.New("iam: identity is linked to another subject") // ErrUnknownIdentity is returned when a provider identity is valid but // not linked to any subject, and sign-up is not possible. ErrUnknownIdentity = errors.New("iam: identity is not linked to a subject") // ErrSubjectDisabled is returned when the subject exists but is disabled. ErrSubjectDisabled = errors.New("iam: subject is disabled") )
Functions ¶
This section is empty.
Types ¶
type AuthRequest ¶
type AuthRequest struct {
Provider string // provider name
Params map[string]string // provider-specific inputs
Mode session.Mode // empty means the first of Config.AllowedModes
Client ClientInfo
}
AuthRequest represents an authentication attempt. Different providers interpret Params differently.
Examples:
OIDC / Google:
Provider = "google"
Params = { "id_token": "<id token>" }
Password:
Provider = "password"
Params = { "username": "...", "password": "..." }
type ClientInfo ¶
ClientInfo describes the client making a request. The HTTP layer fills it in; IAM uses it for audit events, session listings and rate limiting.
type CompletePasswordResetRequest ¶ added in v2.2.0
type CompletePasswordResetRequest struct {
Token string
NewPassword string
Client ClientInfo
}
CompletePasswordResetRequest sets a new password with a reset token.
type Config ¶
type Config struct {
// Providers authenticate credentials. Names must be unique.
Providers []provider.AuthProvider
// Users resolves identities to subjects and loads roles (application-owned).
Users UserStore
// Sessions persists sessions (memstore.Sessions, a database, Redis, ...).
Sessions session.Store
// Session tunes timeouts and refresh-token reuse handling.
Session session.Config
// AllowedModes lists the session modes clients may request. The first is
// the default. Default: cookie only.
AllowedModes []session.Mode
// TokenIssuer and TokenVerifier mint and check access tokens. Required
// when bearer mode is allowed.
TokenIssuer token.Issuer
TokenVerifier token.Verifier
// VerifySessionOnAccess makes VerifyAccessToken also check that the
// token's session still exists, so revocation is immediate at the cost
// of a store lookup per request. Default false: access tokens stay
// valid until they expire.
VerifySessionOnAccess bool
// LoadSubjectOnAccess makes VerifyAccessToken also load the subject
// from Users, so roles, attributes and Disabled are current on every
// bearer request (as they are in cookie mode) instead of being the ones
// in the token. A revoked role or a disabled subject then takes effect
// immediately rather than when the access token expires, at the cost of
// a LoadSubject call per request. A subject that is gone or disabled
// makes the token invalid and revokes its session. Default false.
LoadSubjectOnAccess bool
// Policy decides authorization. Required: there is no allow-all default.
Policy policy.Engine
// Signup controls SignUp and invites.
Signup SignupConfig
// RateLimit throttles failed logins, and password-reset requests.
RateLimit RateLimitConfig
// Recovery enables password reset and email verification.
Recovery RecoveryConfig
// MFA enables TOTP multi-factor authentication.
MFA MFAConfig
// Audit receives security events. Default: audit.SlogLogger.
Audit audit.Logger
// Metrics receives counters. Default: metrics.Noop.
Metrics metrics.Recorder
// Now returns the current time. Nil means time.Now.
Now func() time.Time
}
Config holds every dependency of the default Service. Dependencies are injected explicitly; that is what makes every part replaceable.
type EmailVerificationRequest ¶ added in v2.2.0
type EmailVerificationRequest struct {
SubjectID string
Email string
Client ClientInfo
}
EmailVerificationRequest asks for an email-verification token.
type IdentityStore ¶
type IdentityStore interface {
// ResolveIdentity returns the subject linked to (provider, providerID),
// or ErrNotFound.
ResolveIdentity(ctx context.Context, provider, providerID string) (subjectID string, err error)
// LinkIdentity links an identity to a subject. It returns ErrConflict if
// the identity is already linked (to any subject).
LinkIdentity(ctx context.Context, subjectID string, id provider.Identity) error
// UnlinkIdentity removes a link. Unlinking a missing link is not an error.
UnlinkIdentity(ctx context.Context, subjectID, provider, providerID string) error
// CreateSubject creates a new subject for a first-time identity and
// returns its canonical ID. It must NOT link the identity; IAM calls
// LinkIdentity afterwards. It is only called when sign-up is allowed.
CreateSubject(ctx context.Context, id provider.Identity, grant SignupGrant) (subjectID string, err error)
}
IdentityStore maps provider identities to subjects (one subject, many identities). It is implemented by the application's user store.
type InviteRequest ¶
type InviteRequest struct {
CreatedBy string // inviter's subject ID, for audit
Email string // optional; binds the invite to this email
Roles []string // granted to the new subject
TTL time.Duration // zero means Config.Signup.InviteTTL
}
InviteRequest describes an invite to create.
IAM does not decide who may invite whom: the application must authorize the inviter (including which Roles they may grant) before calling.
type IssuedInvite ¶
type IssuedInvite struct {
ID string `json:"id"`
Token string `json:"token"`
ExpiresAt time.Time `json:"expires_at"`
}
IssuedInvite is returned once by CreateInvite. Token is the only copy of the secret; deliver it to the invitee (IAM sends no email).
type IssuedToken ¶ added in v2.2.0
type IssuedToken struct {
ID string `json:"-"`
Token string `json:"-"`
SubjectID string `json:"-"`
Login string `json:"-"` // password reset: the normalized login
Email string `json:"-"` // email verification: the normalized address
ExpiresAt time.Time `json:"-"`
}
IssuedToken is returned once by the Start methods. Token is the only copy of the secret: deliver it to the address it belongs to, never to the requester. It has no JSON encoding on purpose.
type LoginResult ¶
type LoginResult struct {
Mode session.Mode `json:"mode"`
SessionToken string `json:"-"`
AccessToken string `json:"access_token,omitempty"`
RefreshToken string `json:"refresh_token,omitempty"`
Subject Subject `json:"subject"`
Session SessionInfo `json:"session"`
}
LoginResult is returned by a successful login.
In cookie mode only SessionToken is set; it belongs in an HttpOnly cookie and is deliberately excluded from JSON. In bearer mode AccessToken and RefreshToken are set.
type MFA ¶ added in v2.2.0
type MFA interface {
// BeginTOTPEnrollment creates a pending TOTP factor and returns its
// secret, to show as a QR code (URI) or text (Secret). It replaces any
// pending factor; a confirmed one gives ErrMFAAlreadyEnrolled.
BeginTOTPEnrollment(ctx context.Context, subjectID, accountName string) (*TOTPEnrollment, error)
// ConfirmTOTPEnrollment checks a first code from the app, turns the
// factor on, and returns recovery codes to show the user once.
ConfirmTOTPEnrollment(ctx context.Context, subjectID, code string) (recoveryCodes []string, err error)
// DisableTOTP removes the subject's factor, pending or confirmed.
DisableTOTP(ctx context.Context, subjectID string) error
// TOTPEnabled reports whether the subject has a confirmed factor.
TOTPEnabled(ctx context.Context, subjectID string) (bool, error)
// CompleteMFA finishes a login that returned *MFARequiredError, with a
// TOTP code or a recovery code, and starts the session. Wrong codes are
// throttled per subject (*RateLimitError).
CompleteMFA(ctx context.Context, req MFARequest) (*LoginResult, error)
// VerifyMFA checks a code for a signed-in subject, as step-up
// authentication before a sensitive action. It is throttled like
// CompleteMFA.
VerifyMFA(ctx context.Context, subjectID, code string, client ClientInfo) error
// RegenerateRecoveryCodes replaces the subject's recovery codes.
RegenerateRecoveryCodes(ctx context.Context, subjectID string) ([]string, error)
}
MFA is TOTP multi-factor authentication. The Service returned by New implements it:
m := svc.(iam.MFA)
It is a separate interface so that adding it did not change Service. Every method that acts for a subject expects the application to have authorized the caller (normally: the subject itself, signed in, and recently re-authenticated for DisableTOTP and RegenerateRecoveryCodes).
type MFAConfig ¶ added in v2.2.0
type MFAConfig struct {
// Store keeps each subject's TOTP factor.
Store mfa.Store
// Key seals TOTP secrets at rest and login challenges; at least 32
// bytes. Changing it makes every enrolled factor unusable, so keep it
// with your other long-lived secrets.
Key []byte
// Issuer names your application in authenticator apps. Required.
Issuer string
// ChallengeTTL is how long a user has to enter their code after the
// first factor. Default 5 minutes, max 15 minutes.
ChallengeTTL time.Duration
// Skew is how many 30-second steps either side of now are accepted.
// Default 1; at most 2.
Skew int
// ExemptProviders are providers whose logins never ask for a code, for
// example an OIDC issuer that enforces its own MFA.
ExemptProviders []string
}
MFAConfig enables TOTP multi-factor authentication (see MFA). It is off until Store is set.
type MFARequest ¶ added in v2.2.0
type MFARequest struct {
Challenge string // from MFARequiredError
Code string // a TOTP code, or a recovery code
Client ClientInfo
}
MFARequest completes a login with a second factor.
type MFARequiredError ¶ added in v2.2.0
type MFARequiredError struct {
Challenge string // opaque, sealed; give it back to CompleteMFA
ExpiresAt time.Time // the code must be entered before this
}
MFARequiredError is returned by Login when the first factor was correct and the subject has TOTP enrolled. No session exists yet: send Challenge to the client, ask for a code, and call MFA.CompleteMFA. It wraps ErrMFARequired, so code unaware of MFA treats it as a failed login.
func (*MFARequiredError) Error ¶ added in v2.2.0
func (e *MFARequiredError) Error() string
func (*MFARequiredError) Unwrap ¶ added in v2.2.0
func (e *MFARequiredError) Unwrap() error
type PasswordResetRequest ¶ added in v2.2.0
type PasswordResetRequest struct {
Login string // the password login (for example an email address)
Client ClientInfo
}
PasswordResetRequest asks for a password-reset token.
type RateLimitConfig ¶
type RateLimitConfig struct {
// Disabled turns throttling off. Only for tests or when an upstream
// component already throttles logins.
Disabled bool
// PerLogin counts failures per provider and login name
// (key "login:<provider>:<login>").
PerLogin ratelimit.Limiter
// PerIP counts failures per client IP (key "ip:<ip>").
PerIP ratelimit.Limiter
// Hooks are told about failures and blocks, for notifications or a
// hard lockout kept by the application.
Hooks ratelimit.LockoutHooks
}
RateLimitConfig throttles failed logins.
When both limiters are nil and Disabled is false, in-memory limiters are used: 5 failures per login and 100 per IP within 15 minutes, then a growing back-off. With several instances, use a shared limiter such as redisstore.Limiter.
type RateLimitError ¶
RateLimitError is returned when an attempt is throttled. It wraps ErrRateLimited and says when to retry.
func (*RateLimitError) Error ¶
func (e *RateLimitError) Error() string
func (*RateLimitError) Unwrap ¶
func (e *RateLimitError) Unwrap() error
type Recovery ¶ added in v2.2.0
type Recovery interface {
// StartPasswordReset issues a single-use, expiring token that lets the
// holder set a new password for req.Login, and invalidates earlier
// reset tokens of that subject.
//
// When no active subject has this login it returns (nil, nil). Answer
// the client the same way in both cases ("if the account exists, we
// sent a link"), and deliver the token outside the request, so that the
// response does not reveal which logins exist. Requests are throttled
// per login and per IP like failed logins (*RateLimitError).
StartPasswordReset(ctx context.Context, req PasswordResetRequest) (*IssuedToken, error)
// CompletePasswordReset sets a new password with a reset token and
// signs the subject out everywhere. The token is only used up once the
// new password passes the provider's policy, so a rejected password can
// be corrected. It returns the subject's ID.
CompletePasswordReset(ctx context.Context, req CompletePasswordResetRequest) (subjectID string, err error)
// StartEmailVerification issues a single-use, expiring token proving
// that the holder receives mail at req.Email, and invalidates the
// subject's earlier verification tokens. The application authorizes the
// request (normally: the subject itself, signed in).
StartEmailVerification(ctx context.Context, req EmailVerificationRequest) (*IssuedToken, error)
// CompleteEmailVerification uses up a verification token and returns
// the verified address. IAM does not store it: the application records
// that the subject's email is verified.
CompleteEmailVerification(ctx context.Context, token string, client ClientInfo) (*VerifiedEmail, error)
}
Recovery is password reset and email verification. The Service returned by New implements it:
rec := svc.(iam.Recovery)
It is a separate interface so that adding it did not change Service. IAM sends no email: the Start methods return a token for the application to deliver, typically as a link.
type RecoveryConfig ¶ added in v2.2.0
type RecoveryConfig struct {
// Tokens stores reset and verification tokens. Required for Recovery.
Tokens onetime.Store
// PasswordProvider names the provider whose passwords are reset. It must
// implement provider.PasswordSetter. Default "password"; when no
// provider has that name, only email verification is available.
PasswordProvider string
// ResetTTL is the lifetime of a password-reset token. Default 1 hour,
// max 24 hours.
ResetTTL time.Duration
// VerificationTTL is the lifetime of an email-verification token.
// Default 48 hours, max 30 days.
VerificationTTL time.Duration
}
RecoveryConfig enables password reset and email verification (see Recovery). Both are off until Tokens is set.
type Service ¶
type Service interface {
// Login authenticates through a provider, resolves the canonical
// subject and starts a session in the requested mode.
Login(ctx context.Context, req AuthRequest) (*LoginResult, error)
// Refresh rotates a bearer-mode refresh token and issues a new access
// token with the subject's current roles. Reusing a rotated refresh
// token revokes the session and returns ErrRefreshReused.
Refresh(ctx context.Context, refreshToken string, client ClientInfo) (*TokenPair, error)
// ValidateSession checks a cookie-mode session token and returns the
// subject, freshly loaded from the application's store.
ValidateSession(ctx context.Context, sessionToken string) (*Subject, *SessionInfo, error)
// VerifyAccessToken validates a bearer access token. The returned
// SessionInfo has at least ID, SubjectID and Mode.
VerifyAccessToken(ctx context.Context, accessToken string) (*Subject, *SessionInfo, error)
// Authorize evaluates whether a subject may perform an action on a
// resource. Engine errors and missing subjects result in a deny.
Authorize(ctx context.Context, subject *Subject, action policy.Action, resource policy.Resource) (*policy.Decision, error)
// Logout ends the session that owns the given session token or refresh
// token. Unknown tokens are not an error.
Logout(ctx context.Context, token string) error
// RotateSession replaces a cookie-mode session token, for example after
// a privilege change. The old token stops working.
RotateSession(ctx context.Context, sessionToken string) (*LoginResult, error)
// ListSessions returns a subject's active sessions.
ListSessions(ctx context.Context, subjectID string) ([]SessionInfo, error)
// RevokeSession ends one of the subject's sessions by public ID.
RevokeSession(ctx context.Context, subjectID, sessionID string) error
// RevokeAllSessions ends all of a subject's sessions except
// exceptSessionID (empty for all): "log out everywhere".
RevokeAllSessions(ctx context.Context, subjectID, exceptSessionID string) (int, error)
// LinkIdentity authenticates req and links the resulting provider
// identity to an existing subject. It fails with ErrIdentityLinked if
// the identity already belongs to a different subject.
LinkIdentity(ctx context.Context, subjectID string, req AuthRequest) error
// SignUp creates a subject for a new identity and starts a session,
// subject to the sign-up policy (closed, invite-only or open).
SignUp(ctx context.Context, req SignUpRequest) (*LoginResult, error)
// CreateInvite issues a single-use, expiring invite. The application
// must authorize the inviter first.
CreateInvite(ctx context.Context, req InviteRequest) (*IssuedInvite, error)
// RevokeInvite deletes an unused invite.
RevokeInvite(ctx context.Context, inviteID string) error
}
Service defines the IAM capability exposed to the application. This interface intentionally hides providers, tokens, sessions, and storage so IAM can later be:
- extracted into a microservice
- replaced with a remote client
- wrapped with HTTP / gRPC
func New ¶
New returns the default Service.
Example ¶
A complete cookie-session lifecycle: invite, sign-up, login, a request, authorization, and logout.
package main
import (
"context"
"errors"
"fmt"
"github.com/kararnab/iam/v2"
"github.com/kararnab/iam/v2/audit"
"github.com/kararnab/iam/v2/memstore"
"github.com/kararnab/iam/v2/password"
"github.com/kararnab/iam/v2/policy"
"github.com/kararnab/iam/v2/provider"
)
func main() {
ctx := context.Background()
users := memstore.NewUsers()
hasher, _ := password.NewArgon2id(password.DefaultParams, 0)
passwords, _ := password.NewProvider(users, hasher, password.DefaultPolicy)
rbac, _ := policy.NewRBAC(map[string][]policy.Permission{
"member": {policy.P("read", "note")},
})
svc, err := iam.New(iam.Config{
Providers: []provider.AuthProvider{passwords},
Users: users,
Sessions: memstore.NewSessions(),
Policy: rbac,
Signup: iam.SignupConfig{Invites: memstore.NewInvites()},
Audit: audit.Func(func(context.Context, audit.Event) error { return nil }), // quiet example
})
if err != nil {
panic(err)
}
// An admin invites a member; the invitee signs up with the token.
inv, _ := svc.CreateInvite(ctx, iam.InviteRequest{Roles: []string{"member"}})
creds := map[string]string{"username": "ana@example.com", "password": "correct horse battery staple"}
_, err = svc.SignUp(ctx, iam.SignUpRequest{InviteToken: inv.Token, Provider: password.ProviderName, Params: creds})
fmt.Println("sign-up:", err)
// Invites are single-use.
_, err = svc.SignUp(ctx, iam.SignUpRequest{InviteToken: inv.Token, Provider: password.ProviderName,
Params: map[string]string{"username": "eve@example.com", "password": "another long password"}})
fmt.Println("reused invite:", errors.Is(err, iam.ErrInvalidInvite))
// Login returns a session token for an HttpOnly cookie (see httpauth).
res, _ := svc.Login(ctx, iam.AuthRequest{Provider: password.ProviderName, Params: creds})
fmt.Println("mode:", res.Mode, "roles:", res.Subject.Roles)
// On each request: validate the cookie, then authorize.
subject, _, _ := svc.ValidateSession(ctx, res.SessionToken)
read, _ := svc.Authorize(ctx, subject, "read", policy.Resource{Type: "note"})
del, _ := svc.Authorize(ctx, subject, "delete", policy.Resource{Type: "note"})
fmt.Println("read:", read.Allowed(), "delete:", del.Allowed())
_ = svc.Logout(ctx, res.SessionToken)
_, _, err = svc.ValidateSession(ctx, res.SessionToken)
fmt.Println("after logout:", errors.Is(err, iam.ErrInvalidSession))
}
Output: sign-up: <nil> reused invite: true mode: cookie roles: [member] read: true delete: false after logout: true
type SessionInfo ¶
type SessionInfo struct {
ID string `json:"id"` // public session ID
SubjectID string `json:"subject_id"`
Mode session.Mode `json:"mode"`
CreatedAt time.Time `json:"created_at,omitzero"`
LastUsedAt time.Time `json:"last_used_at,omitzero"`
ExpiresAt time.Time `json:"expires_at,omitzero"`
IP string `json:"ip,omitempty"`
UserAgent string `json:"user_agent,omitempty"`
Provider string `json:"provider,omitempty"`
// MFA is true when the session was started with a second factor
// (MFA.CompleteMFA). Bearer access tokens do not carry it: it is only
// set for them with Config.VerifySessionOnAccess.
MFA bool `json:"mfa,omitempty"`
}
SessionInfo describes a session without its secret.
type SignUpRequest ¶
type SignUpRequest struct {
InviteToken string // required when the sign-up policy is InviteOnly
Provider string
Params map[string]string
Mode session.Mode
Client ClientInfo
// Profile holds application fields for the new subject (display name,
// locale, ...). IAM passes it to IdentityStore.CreateSubject as
// SignupGrant.Profile without reading it.
Profile map[string]string
}
SignUpRequest creates a new subject and starts a session.
With a provider that implements provider.Registrar (password), new credentials are registered from Params. With other providers (OIDC), the identity is authenticated and must not be linked yet.
type SignupConfig ¶
type SignupConfig struct {
// Policy: invite.Closed, invite.InviteOnly or invite.Open. Default:
// InviteOnly when Invites is set, otherwise Closed.
Policy invite.Policy
// Invites stores invitations. Required for InviteOnly.
Invites invite.Store
// DefaultRoles are granted on open sign-up (invites carry their own).
DefaultRoles []string
// InviteTTL is the default invite lifetime. Default 7 days, max 90 days.
InviteTTL time.Duration
}
SignupConfig controls SignUp and invites.
type SignupGrant ¶
type SignupGrant struct {
Roles []string
InviteID string
// Profile is SignUpRequest.Profile, passed through untouched: fields
// from the sign-up form (display name, locale, ...) that the store can
// save in the same write that creates the subject. IAM never reads it.
Profile map[string]string
}
SignupGrant carries what a sign-up is entitled to, for example roles from an invite, plus the application's own profile fields. The application decides how to apply it.
type Subject ¶
type Subject struct {
ID string `json:"id"` // canonical internal subject ID
Roles []string `json:"roles,omitempty"` // coarse-grained roles, owned by the application
Attrs map[string]string `json:"attrs,omitempty"` // extensible attributes (org, tier, etc)
// Disabled subjects cannot log in, and their sessions stop working.
Disabled bool `json:"-"`
}
Subject represents an authenticated principal in the system. This is the ONLY identity shape business code should see.
ID is the application's canonical subject ID. It is never a provider's user ID: one subject may sign in through several providers (see IdentityStore).
type SubjectDeleter ¶ added in v2.3.0
SubjectDeleter is optionally implemented by a UserStore. When a sign-up fails after CreateSubject succeeded (linking the identity or starting the session failed), SignUp calls DeleteSubject so no subject is left that nobody can sign in to. Without it such a subject remains, and the store has to clean it up itself.
DeleteSubject removes the subject and the identities linked to it. Deleting a missing subject is not an error. A consumed invite is not restored.
type SubjectLoader ¶
type SubjectLoader interface {
// LoadSubject returns ErrNotFound if the subject does not exist.
LoadSubject(ctx context.Context, subjectID string) (*Subject, error)
}
SubjectLoader loads a subject by its canonical ID.
It is implemented by the application's user store. IAM calls it on login, on every refresh, and (in cookie mode) on every request, so roles and the Disabled flag always come from the application.
type TOTPEnrollment ¶ added in v2.2.0
type TOTPEnrollment struct {
Secret string `json:"-"` // base32, for typing into an app
URI string `json:"-"` // otpauth://totp/..., for a QR code
}
TOTPEnrollment is returned by BeginTOTPEnrollment. Secret is shown to the user once; it has no JSON encoding on purpose.
type TokenPair ¶
type TokenPair struct {
AccessToken string `json:"access_token"`
RefreshToken string `json:"refresh_token"`
}
TokenPair is returned by Refresh. The refresh token always rotates.
type UserStore ¶
type UserStore interface {
SubjectLoader
IdentityStore
}
UserStore is the combination IAM needs from the application.
type VerifiedEmail ¶ added in v2.2.0
VerifiedEmail is returned by CompleteEmailVerification.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package audit defines the security events IAM emits (logins, logouts, refreshes, refresh-token reuse, revocations, policy denials, sign-ups, invites, throttling, password resets, email verification, MFA) and the Logger interface that receives them.
|
Package audit defines the security events IAM emits (logins, logouts, refreshes, refresh-token reuse, revocations, policy denials, sign-ups, invites, throttling, password resets, email verification, MFA) and the Logger interface that receives them. |
|
examples
|
|
|
quickstart
command
Command quickstart is the five-minute integration guide from the README: a net/http app with cookie sessions, invite-only sign-up and RBAC, using only the core module (standard library + golang.org/x/crypto).
|
Command quickstart is the five-minute integration guide from the README: a net/http app with cookie sessions, invite-only sign-up and RBAC, using only the core module (standard library + golang.org/x/crypto). |
|
Package httpauth adapts an iam.Service to net/http.
|
Package httpauth adapts an iam.Service to net/http. |
|
Package invite defines single-use, expiring sign-up invitations.
|
Package invite defines single-use, expiring sign-up invitations. |
|
Package memstore provides in-memory reference implementations of every store interface in the library.
|
Package memstore provides in-memory reference implementations of every store interface in the library. |
|
Package metrics defines the counters IAM emits.
|
Package metrics defines the counters IAM emits. |
|
Package mfa implements time-based one-time passwords (TOTP, RFC 6238) and recovery codes, and defines the Store that keeps a subject's factor.
|
Package mfa implements time-based one-time passwords (TOTP, RFC 6238) and recovery codes, and defines the Store that keeps a subject's factor. |
|
Package onetime defines single-use, expiring tokens for account actions: password reset and email verification.
|
Package onetime defines single-use, expiring tokens for account actions: password reset and email verification. |
|
Package passkey defines stored WebAuthn credentials (passkeys and security keys) and the Store that keeps them.
|
Package passkey defines stored WebAuthn credentials (passkeys and security keys) and the Store that keeps them. |
|
Package password hashes and verifies passwords.
|
Package password hashes and verifies passwords. |
|
Package policy decides authorization: may this subject perform this action on this resource?
|
Package policy decides authorization: may this subject perform this action on this resource? |
|
Package provider defines identity providers: components that verify credentials (a password, an OIDC ID token) and return a stable external Identity.
|
Package provider defines identity providers: components that verify credentials (a password, an OIDC ID token) and return a stable external Identity. |
|
Package ratelimit throttles repeated failures, such as failed logins.
|
Package ratelimit throttles repeated failures, such as failed logins. |
|
Package session manages server-side sessions for both session modes:
|
Package session manages server-side sessions for both session modes: |
|
Package storetest is a conformance suite for store implementations.
|
Package storetest is a conformance suite for store implementations. |
|
Package token defines access-token issuing and verification independent of the token format.
|
Package token defines access-token issuing and verification independent of the token format. |
|
jwt
Package jwt issues and verifies JWT access tokens (RFC 7519, RFC 9068) using only the standard library.
|
Package jwt issues and verifies JWT access tokens (RFC 7519, RFC 9068) using only the standard library. |
|
keys
Package keys holds signing and encryption keys for access tokens.
|
Package keys holds signing and encryption keys for access tokens. |