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 Config
- type IdentityStore
- type InviteRequest
- type IssuedInvite
- type LoginResult
- type RateLimitConfig
- type RateLimitError
- type Service
- type SessionInfo
- type SignUpRequest
- type SignupConfig
- type SignupGrant
- type Subject
- type SubjectLoader
- type TokenPair
- type UserStore
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 )
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 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
// Policy decides authorization. Required: there is no allow-all default.
Policy policy.Engine
// Signup controls SignUp and invites.
Signup SignupConfig
// RateLimit throttles failed logins.
RateLimit RateLimitConfig
// 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 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 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 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 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"`
}
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
}
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 ¶
SignupGrant carries what a sign-up is entitled to, for example roles from an invite. 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 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 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.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package audit defines the security events IAM emits (logins, logouts, refreshes, refresh-token reuse, revocations, policy denials, sign-ups, invites, throttling) 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) 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 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. |