iam

package module
v2.2.0 Latest Latest
Warning

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

Go to latest
Published: Oct 4, 2026 License: MIT Imports: 24 Imported by: 4 modules, 1 package

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

iam: authentication and authorization for Go web apps

Go Reference CI Go version

Logins, sessions, JWT, RBAC and invites for Go web apps and APIs, with secure defaults. It is one library to import, not another server to run.

iam gives your Go application password and Google/OIDC sign-in, server-side sessions (HttpOnly cookies for browsers, rotating refresh tokens for APIs and mobile), deny-by-default role-based access control, invite-only sign-up, login throttling and audit logs. It works with net/http, keeps your users in your own database, and depends only on the standard library and golang.org/x/crypto.

svc, _ := iam.New(iam.Config{
    Providers: []provider.AuthProvider{passwords},   // + oidc.NewGoogle(...)
    Users:     users,                                // your user table, or pgstore
    Sessions:  memstore.NewSessions(),               // or pgstore / redisstore
    Policy:    rbac,                                 // nothing is allowed until you grant it
})
auth, _ := httpauth.New(httpauth.Config{Service: svc})

mux.Handle("GET /notes", auth.RequirePermission("read", "note", nil)(notes))
http.ListenAndServe(":8080", auth.Protect(mux))      // sessions, CSRF, cross-origin checks

Try it in ten seconds, with no clone needed:

go run github.com/kararnab/iam/v2/examples/quickstart@latest

Why iam?

You could combine a JWT library, a session manager, an OAuth helper and a policy engine, and then write the glue that gets security wrong: refresh-token reuse, CSRF on cookie sessions, user enumeration, roles that go stale after a refresh. iam is that glue, designed together and tested together.

Login providers Sessions Access tokens Authorization Runs as
iam password, passkeys, Google, OIDC (+ TOTP MFA) ✅ cookie + bearer, rotation ✅ JWT (+ JWKS), PASETO ✅ RBAC + your rules a library
golang-jwt/jwt – – ✅ JWT – a library
alexedwards/scs – ✅ cookie – – a library
markbates/goth ✅ many OAuth – – – a library
casbin – – – ✅ many models a library
Ory Kratos, Keycloak, Zitadel ✅ ✅ ✅ partly a separate server

Those are excellent tools; choose them when you need only their part, or when you want a separate identity server. What iam deliberately does not do is listed in SECURITY.md.

Features

  • 🍪 Two session modes: HttpOnly, __Host- cookie sessions for browsers (the default), and short-lived access tokens with rotating refresh tokens for APIs and mobile apps. One service can serve both.
  • 🔁 Refresh-token reuse detection: replaying an old refresh token revokes the whole session.
  • 🔑 Sign-in: argon2id passwords (bcrypt hashes are upgraded automatically), passkeys and security keys (WebAuthn), Google and any OpenID Connect issuer (with a ready-made authorization-code flow: PKCE, state and nonce), plus identity linking: one user, many ways to sign in.
  • 🛡️ Deny-by-default RBAC, composable with your own rules (for example "owners can edit").
  • ✉️ Invite-only sign-up with single-use, expiring invites, switchable to open or closed.
  • 📱 TOTP multi-factor authentication with recovery codes, replay protection and step-up checks; logins fail closed until the code is given.
  • 🔐 Password reset and email verification with single-use, expiring tokens, without revealing which accounts exist.
  • 🚦 Login throttling per account and per IP, on by default.
  • 🧾 Audit events (logins, reuse detection, lockouts, denials) through log/slog, and Prometheus metrics.
  • 👀 Session management: list devices, revoke one, "log out everywhere else".
  • 🧩 Pluggable everything: providers, stores (memory, PostgreSQL, Redis, yours), policy engines, token formats (JWT, PASETO), audit sinks.
  • 🪶 Small core: standard library and golang.org/x/crypto only. Integrations are opt-in modules.
Built to be trusted
  • A threat model with documented defaults, and a list of what the library deliberately does not do.
  • Fuzz tests for every parser this library implements for untrusted input: JWT, PASETO, session cookies, password hashes. They run weekly in CI.
  • A store conformance suite that the memory, PostgreSQL and Redis stores all pass, including concurrent-rotation races.
  • go test -race, golangci-lint (including gosec and staticcheck) and govulncheck on every module, with Go 1.26 and 1.27.
  • End-to-end tests of every flow in the demo app, on PostgreSQL.

Install

go get github.com/kararnab/iam/v2

Add only the integrations you use:

Module Adds Dependencies
github.com/kararnab/iam/v2 service, sessions, JWT, passwords, policy, invites, rate limiting, httpauth, in-memory stores stdlib, golang.org/x/crypto
github.com/kararnab/iam/oidc/v2 Google and OpenID Connect sign-in coreos/go-oidc
github.com/kararnab/iam/paseto/v2 PASETO v4 access tokens aidanwoods.dev/go-paseto
github.com/kararnab/iam/pgstore/v2 PostgreSQL stores and migrations jackc/pgx/v5
github.com/kararnab/iam/redisstore/v2 Redis session store and shared rate limiter redis/go-redis/v9
github.com/kararnab/iam/prometheus/v2 Prometheus metrics prometheus/client_golang
github.com/kararnab/iam/webauthn/v2 passkeys and security keys go-webauthn/webauthn

Requires Go 1.26 or later. Versions follow semantic versioning. The first release is v2.0.0 because this repository's earlier tags belonged to the demo application. See the changelog.

The complete program is examples/quickstart.

import (
    "github.com/kararnab/iam/v2"
    "github.com/kararnab/iam/v2/httpauth"
    "github.com/kararnab/iam/v2/memstore"
    "github.com/kararnab/iam/v2/password"
    "github.com/kararnab/iam/v2/policy"
    "github.com/kararnab/iam/v2/provider"
)

1. Users and passwords. Users belong to your application. memstore keeps them in memory; use pgstore or implement iam.UserStore over your own tables.

users := memstore.NewUsers()
hasher, _ := password.NewArgon2id(password.DefaultParams, 0)
passwords, _ := password.NewProvider(users, hasher, password.DefaultPolicy)

2. A policy. Roles grant actions on resource types. Anything not granted is denied.

rbac, _ := policy.NewRBAC(map[string][]policy.Permission{
    "admin":  {policy.P(policy.Wildcard, policy.Wildcard)},
    "member": {policy.P("read", "note")},
})

3. The service. Cookie sessions are the default mode, and sign-up is invite-only once an invite store is configured.

svc, err := iam.New(iam.Config{
    Providers: []provider.AuthProvider{passwords},
    Users:     users,
    Sessions:  memstore.NewSessions(),
    Policy:    rbac,
    Signup:    iam.SignupConfig{Invites: memstore.NewInvites()},
})

4. HTTP. httpauth sets the session cookie (HttpOnly, SameSite=Lax, __Host- prefix, Secure), checks CSRF tokens and authorizes requests.

auth, _ := httpauth.New(httpauth.Config{
    Service: svc,
    Cookie:  httpauth.CookieConfig{Insecure: true}, // plain-HTTP localhost only!
})

mux := http.NewServeMux()
mux.HandleFunc("POST /signup", func(w http.ResponseWriter, r *http.Request) {
    // ...decode username, password and invite...
    res, err := svc.SignUp(r.Context(), iam.SignUpRequest{
        InviteToken: c.Invite,
        Provider:    password.ProviderName,
        Params:      map[string]string{"username": c.Username, "password": c.Password},
        Client:      auth.ClientInfo(r),
    })
    if err != nil { /* 403 */ }
    csrf := auth.StartSession(w, res) // sets the cookie
    // ...send csrf to the page; it must accompany POST/PUT/DELETE...
})
// POST /login is the same with svc.Login; POST /logout calls auth.EndSession.

mux.Handle("GET /notes", auth.RequirePermission("read", "note", nil)(notesHandler))

inv, _ := svc.CreateInvite(ctx, iam.InviteRequest{Roles: []string{"member"}})
log.Printf("invite token: %s", inv.Token)

srv := &http.Server{Addr: "localhost:8080", Handler: auth.Protect(mux), ReadHeaderTimeout: 5 * time.Second}
log.Fatal(srv.ListenAndServe())

5. Try it.

go run github.com/kararnab/iam/v2/examples/quickstart@latest   # prints an invite token
INVITE=...                                                      # paste it

curl -c jar localhost:8080/signup \
  -d "{\"username\":\"ana@example.com\",\"password\":\"correct horse battery staple\",\"invite\":\"$INVITE\"}"
# {"csrf_token":"…","subject":{"id":"J7NS…","roles":["member"]}}

curl -b jar localhost:8080/notes                            # {"hello":"J7NS…"}
curl -b jar -X POST localhost:8080/logout                    # 403: CSRF token required
curl -b jar -c jar -X POST -H "X-CSRF-Token: …" localhost:8080/logout   # 200
curl -b jar localhost:8080/notes                            # 401

Set ADDR if port 8080 is taken. To allow anyone to register, use Signup: iam.SignupConfig{Policy: invite.Open, DefaultRoles: []string{"member"}}.

Adding bearer tokens for API clients

Allow the mode, add a token issuer and verifier, and accept bearer credentials in httpauth:

kp := keys.NewMemoryProvider(keys.Key{ID: "k1", Alg: keys.HS256, Secret: secret32bytes})
jc := jwt.Config{Issuer: "my-app", Audience: "my-api"}
issuer, _ := jwt.NewIssuer(kp, jc)
verifier, _ := jwt.NewVerifier(kp, jc)

svc, _ := iam.New(iam.Config{
    // ...as above...
    AllowedModes:  []session.Mode{session.ModeCookie, session.ModeBearer},
    TokenIssuer:   issuer,
    TokenVerifier: verifier,
})
auth, _ := httpauth.New(httpauth.Config{Service: svc, Modes: []session.Mode{session.ModeCookie, session.ModeBearer}})

svc.Login(ctx, iam.AuthRequest{..., Mode: session.ModeBearer}) then returns an access token (10 minutes by default) and a refresh token. Every svc.Refresh rotates the refresh token. Presenting an old refresh token again revokes the whole session.

Concepts

  • Subject: the canonical user. Subject.ID is your application's ID, never a provider's. One subject can sign in through several providers (IdentityStore, Service.LinkIdentity). Roles always come from your store.
  • Session: server-side, in both modes. Clients only ever hold a random 256-bit secret; stores keep its SHA-256 hash. Sessions have idle and absolute timeouts, can be listed, and can be revoked one by one or all at once ("log out everywhere").
  • Policy: an Engine decides; RBAC covers roles. policy.AnyOf and policy.AllOf combine it with your own rules, for example resource ownership. Every denial is audited.
  • Audit and metrics: security events (logins, refreshes, reuse detection, lockouts, denials, sign-ups) go to an audit.Logger, and counters go to a metrics.Recorder.
  • No HTTP in the core service: iam.Service takes and returns plain data, so it can later sit behind gRPC or become a remote service. httpauth adapts it to net/http.

Documentation

The demo app

examples/demo is a books API that uses the library the way any consumer would: cookie and bearer endpoints, invite-only sign-up, RBAC, session management, throttling, Prometheus, and optional PostgreSQL. See its README and OpenAPI spec.

Roadmap

Everything on the previous roadmap shipped in v2.2.0: the OIDC authorization-code flow, password reset and email verification, TOTP multi-factor authentication, passkeys, and JWKS publishing. Ideas for what comes next are tracked as issues; upvotes and comments help decide.

iam will not become an OAuth 2.0 authorization server; see SECURITY.md.

Contributing

Issues and pull requests are welcome, especially new stores, providers, and examples for other routers (chi, echo, gin). Please open an issue before large changes. Report security problems privately as described in SECURITY.md.

./scripts/each-module.sh go test -race ./...         # every module
./scripts/each-module.sh golangci-lint run ./...    # lint (config: .golangci.yml)

# Integration tests for pgstore, redisstore and the demo on PostgreSQL:
export IAM_TEST_POSTGRES_DSN='postgres://postgres:pw@localhost:5432/iamtest?sslmode=disable'
export IAM_TEST_REDIS_ADDR='localhost:6379'

go test ./token/jwt -run '^$' -fuzz FuzzVerify    # fuzzing (see .github/workflows/fuzz.yml)

If iam saves you time, a ⭐ helps other Go developers find it.

License

MIT

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

Examples

Constants

This section is empty.

Variables

View Source
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")
)
View Source
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

	// ErrUnavailable wraps a store failure while checking a session or a
	// 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")
)
View Source
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")
)
View Source
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")
)
View Source
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

type ClientInfo struct {
	IP        string
	UserAgent string
}

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

	// 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

type RateLimitError struct {
	RetryAfter time.Duration
}

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

func New(cfg Config) (Service, error)

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
}

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
}

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 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

type VerifiedEmail struct {
	SubjectID string `json:"subject_id"`
	Email     string `json:"email"`
}

VerifiedEmail is returned by CompleteEmailVerification.

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.

Jump to

Keyboard shortcuts

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