Documentation
¶
Overview ¶
Package authkit is embeddable authentication for Go backends on net/http, backed by Postgres.
It provides the HTTP handlers for registration with email verification, password and passkey login, TOTP with recovery codes, OAuth2/OIDC providers with explicit account linking, sessions, re-authentication (sudo mode), password reset, email change with a revert link, grace-period deletion and a GDPR data export. The browser talks to it with JSON over fetch; api/openapi.yaml describes every endpoint and the TypeScript client @johnnycube/authkit-client is generated from it.
Ownership ¶
authkit owns the Postgres schema "authkit" (created and migrated by Migrate) and the routes under /auth/ and /account/ (registered by Auth.Mount). The host keeps its domain data in its own schema, references authkit.users(id) with ON DELETE CASCADE and reacts to account events through Hooks, which run inside authkit's transactions. authkit has no process of its own: the host constructs it with New, mounts its handlers, wraps its own routes with Auth.RequireUser and runs the background jobs with Auth.RunJobs.
Security model ¶
Sessions are opaque random tokens in a __Host- cookie, stored as HMAC-SHA256 hashes and revocable at once. State-changing requests must come from Config.FrontendOrigin and carry a CSRF token. Failed logins never lock an account; they escalate to a proof-of-work challenge (ALTCHA) and a per-IP delay. Password hashing (argon2id) runs behind a bounded queue. Mail links carry their token in the URL fragment, tokens are single use and hashed at rest, TOTP secrets are encrypted. Rate limits and failure counters are in-process by default, which suits one replica; pass shared implementations of the ratelimit ports in Deps to scale out.
Configuration ¶
Config holds the environment-driven settings (origins, keys, SMTP sender, trusted proxies) and the code-driven ones (product name, languages, frontend paths, OAuth providers, durations). LoadEnv reads the environment and the [mail.SMTPConfig] in one call. Every key is 32 random bytes, base64 encoded.
Package github.com/johnnycube/authkit/authkittest provides a recording mailer, a clock, a protocol client and fixtures for the host's own tests.
Example ¶
A complete host: configuration from the environment, migrations, the authkit routes, a protected route of the host and the background jobs.
package main
import (
"context"
"embed"
"errors"
"fmt"
"log"
"net/http"
"os/signal"
"syscall"
"time"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/sethvargo/go-envconfig/v2"
"github.com/johnnycube/authkit"
"github.com/johnnycube/authkit/mail"
)
// migrations would hold the host's own goose migrations, e.g. //go:embed migrations/*.sql.
var migrations embed.FS
func main() {
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer stop()
cfg, smtp, err := authkit.LoadEnv(ctx, envconfig.OsLookuper())
if err != nil {
log.Fatal(err)
}
cfg.ProductName = "Example"
pool, err := pgxpool.New(ctx, "postgres://app@localhost/app")
if err != nil {
log.Fatal(err)
}
defer pool.Close()
if err := authkit.Migrate(ctx, pool); err != nil {
log.Fatal(err)
}
if err := authkit.MigrateFS(ctx, pool, "app", migrations); err != nil {
log.Fatal(err)
}
mailer, err := mail.NewSMTP(smtp)
if err != nil {
log.Fatal(err)
}
auth, err := authkit.New(cfg, authkit.Deps{Pool: pool, Mailer: mailer})
if err != nil {
log.Fatal(err)
}
go func() { _ = auth.RunJobs(ctx) }()
mux := http.NewServeMux()
auth.Mount(mux)
mux.Handle("GET /notes", auth.RequireUser(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
user, _ := authkit.UserFromContext(r.Context())
fmt.Fprintf(w, "notes of %s", user.ID)
})))
srv := &http.Server{Addr: ":8080", Handler: auth.CORS(auth.SecurityHeaders(mux))}
go func() {
if err := srv.ListenAndServe(); !errors.Is(err, http.ErrServerClosed) {
log.Fatal(err)
}
}()
<-ctx.Done()
shutdownCtx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
if err := srv.Shutdown(shutdownCtx); err != nil { // finishes in-flight requests first
log.Print(err)
}
if err := auth.Close(shutdownCtx); err != nil { // then drains queued mail and registration work
log.Print(err)
}
}
Output:
Index ¶
- func DefaultPath(kind LinkKind) string
- func Migrate(ctx context.Context, pool *pgxpool.Pool) error
- func MigrateFS(ctx context.Context, pool *pgxpool.Pool, schema string, fsys fs.FS) error
- type Auth
- func (a *Auth) CORS(next http.Handler) http.Handler
- func (a *Auth) ClientIP(r *http.Request) netip.Addr
- func (a *Auth) Close(ctx context.Context) error
- func (a *Auth) Handler() http.Handler
- func (a *Auth) Mount(mux *http.ServeMux)
- func (a *Auth) OptionalUser(next http.Handler) http.Handler
- func (a *Auth) Protect(next http.Handler) http.Handler
- func (a *Auth) RequireUser(next http.Handler) http.Handler
- func (a *Auth) RunJobs(ctx context.Context) error
- func (a *Auth) RunJobsOnce(ctx context.Context) (JobReport, error)
- func (a *Auth) SecurityHeaders(next http.Handler) http.Handler
- type Config
- type Deps
- type Hooks
- type JobReport
- type Key
- type LinkKind
- type OAuthProvider
- type Observer
- type User
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DefaultPath ¶
DefaultPath is the frontend path used when Config.Paths leaves kind out; {lang} is replaced by the language.
Example ¶
Mail links point at pages of the frontend; {lang} becomes the user's language.
package main
import (
"fmt"
"github.com/johnnycube/authkit"
)
func main() {
cfg := authkit.Config{Paths: map[authkit.LinkKind]string{authkit.LinkVerify: "/{lang}/verify"}}
_ = cfg
for _, kind := range authkit.LinkKinds() {
fmt.Println(kind, authkit.DefaultPath(kind))
}
}
Output: verify /verify login /login reset /reset-password email_change /email-change email_revert /email-revert deletion_cancel /cancel-deletion oauth_result /oauth/callback
func MigrateFS ¶
MigrateFS applies the host's goose SQL migrations from fsys the way authkit migrates its own: schema is created if missing, the version table is <schema>.goose_db_version, and a Postgres session lock serialises replicas. Run Migrate first when the host's tables reference authkit.users.
Types ¶
type Auth ¶
type Auth struct {
// contains filtered or unexported fields
}
Auth is a configured authkit instance.
func (*Auth) CORS ¶
CORS allows credentialed requests from FrontendOrigin only; wrap the host's whole mux with it.
func (*Auth) ClientIP ¶
ClientIP returns the client address, honouring X-Forwarded-For only when the peer is a trusted proxy.
func (*Auth) Close ¶
Close waits for queued mails and background registration work (bounded by ctx) and stops background helpers.
func (*Auth) OptionalUser ¶
OptionalUser attaches the user when a valid session exists and enforces Origin and CSRF checks on state-changing requests.
func (*Auth) Protect ¶
Protect enforces the Origin check and the CSRF token on state-changing requests.
func (*Auth) RequireUser ¶
RequireUser answers 401 without a valid session and enforces Origin and CSRF checks on state-changing requests.
func (*Auth) RunJobsOnce ¶
RunJobsOnce purges unverified accounts past UnverifiedTTL and deleted accounts past DeletionGrace, then removes expired sessions, tokens, flows and ALTCHA records. A failing user or step does not stop the others: every step runs, and the joined error and JobReport.PurgeFailed say what failed. It is skipped while another replica holds the lock.
type Config ¶
type Config struct {
// FrontendOrigin is the only origin allowed for CORS and state-changing requests, e.g. https://example.com.
FrontendOrigin string `env:"FRONTEND_ORIGIN, required"`
// PublicAPIURL is the public base URL of the API host, used for OAuth callbacks.
PublicAPIURL string `env:"PUBLIC_API_URL, required"`
// WebAuthnRPID defaults to the host of FrontendOrigin.
WebAuthnRPID string `env:"WEBAUTHN_RP_ID"`
// MailFrom is the sender address, e.g. "Example <noreply@example.com>".
MailFrom string `env:"SMTP_FROM, required"`
// TrustedProxyCIDRs lists the proxies whose X-Forwarded-For is trusted.
TrustedProxyCIDRs []netip.Prefix `env:"TRUSTED_PROXY_CIDRS"`
// SessionKey keys the hashes of session, mail and flow tokens at rest.
SessionKey Key `env:"SESSION_KEY, required"`
// CSRFKey signs CSRF tokens.
CSRFKey Key `env:"CSRF_KEY, required"`
// TOTPEncryptionKey encrypts TOTP secrets at rest (AES-256-GCM).
TOTPEncryptionKey Key `env:"TOTP_ENCRYPTION_KEY, required"`
// AltchaHMACKey signs ALTCHA challenges.
AltchaHMACKey Key `env:"ALTCHA_HMAC_KEY, required"`
// ProductName appears in mails, TOTP issuer and WebAuthn RP name.
ProductName string
// AccentColor is the mail button colour.
AccentColor string
// Languages the host accepts for users; default all of mail.SupportedLanguages().
Languages []string
// DefaultLanguage is used when a request names none; default en.
DefaultLanguage string
// Paths overrides DefaultPath per link kind.
Paths map[LinkKind]string
// Link fully overrides how frontend links are built; it receives the kind and language and returns a URL.
Link func(kind LinkKind, lang string) string
// OAuthProviders lists enabled OAuth2/OIDC providers; none by default.
OAuthProviders []OAuthProvider
SessionTTL time.Duration // default 30 days, sliding
SessionMaxAge time.Duration // default 90 days; absolute lifetime of a session, however active
ReauthWindow time.Duration // default 5 minutes
VerifyTTL time.Duration // default 24 hours
ResetTTL time.Duration // default 1 hour
EmailChangeTTL time.Duration // default 24 hours
RevertTTL time.Duration // default 7 days
UnverifiedTTL time.Duration // default 7 days
DeletionGrace time.Duration // default 14 days
PendingTTL time.Duration // default 5 minutes, for MFA, restore and ceremonies
JobInterval time.Duration // default 1 hour
// AltchaCost is the PBKDF2 iteration count per ALTCHA attempt; default 5000.
AltchaCost int
// AltchaMaxCounter bounds the ALTCHA work counter, drawn from [max/2, max); default 10000.
AltchaMaxCounter int
// AltchaFailures is the number of failed logins per account or IP after which ALTCHA is required; default 3.
AltchaFailures int
// PasswordMinLength defaults to 10; the maximum is 256 bytes.
PasswordMinLength int
// MaxBodyBytes caps request bodies; default 64 KiB.
MaxBodyBytes int64
// MaxConcurrentHashes bounds concurrent argon2id runs (19 MiB each) process-wide; default 4.
MaxConcurrentHashes int
// HashQueueTimeout is how long a request waits for a hashing slot before it gets 503 server_busy; default 3 s.
HashQueueTimeout time.Duration
// DevInsecureCookies drops Secure and the __Host- prefix for plain-HTTP local development. Never in production.
DevInsecureCookies bool `env:"DEV_INSECURE_COOKIES"`
// DevDisableRateLimits turns off rate limits, login backoff and the failed-login ALTCHA for local e2e suites.
// It is refused unless DevInsecureCookies is set too.
DevDisableRateLimits bool `env:"DEV_DISABLE_RATE_LIMITS"`
// MailOverlay may hold <lang>.json and layout files overriding the built-in mail texts.
MailOverlay fs.FS
}
Config configures authkit. Tagged fields load from environment variables with sethvargo/go-envconfig (see LoadEnv); the rest are set in code by the host.
func LoadEnv ¶
LoadEnv reads the environment-backed fields of Config and the SMTP settings in one call, through lookuper (envconfig.OsLookuper() for the process environment). Set the code-only fields afterwards.
Example ¶
LoadEnv reads Config and the SMTP settings in one call; any envconfig.Lookuper works, here a map.
package main
import (
"context"
"encoding/base64"
"fmt"
"log"
"github.com/sethvargo/go-envconfig/v2"
"github.com/johnnycube/authkit"
)
func main() {
key := base64.StdEncoding.EncodeToString(make([]byte, 32)) // real keys: openssl rand -base64 32
env := envconfig.MapLookuper(map[string]string{
"FRONTEND_ORIGIN": "https://example.com",
"PUBLIC_API_URL": "https://api.example.com",
"SMTP_FROM": "Example <noreply@example.com>",
"SMTP_HOST": "smtp.example.com",
"SESSION_KEY": key,
"CSRF_KEY": key,
"TOTP_ENCRYPTION_KEY": key,
"ALTCHA_HMAC_KEY": key,
})
cfg, smtp, err := authkit.LoadEnv(context.Background(), env)
if err != nil {
log.Fatal(err)
}
fmt.Println(cfg.FrontendOrigin, len(cfg.SessionKey))
fmt.Println(smtp.Host, smtp.Port, smtp.TLS)
}
Output: https://example.com 32 smtp.example.com 587 starttls
type Deps ¶
type Deps struct {
// Pool is required; its database must have been migrated with Migrate.
Pool *pgxpool.Pool
// Mailer is required and delivers every transactional mail, e.g. mail.NewSMTP.
Mailer mail.Mailer
// Logger receives JSON audit and error logs; default slog.Default().
Logger *slog.Logger
// Limiter defaults to an in-process limiter (single replica).
Limiter ratelimit.Limiter
// Failures counts failed logins for the ALTCHA threshold and the per-IP backoff; default in-process, 15 minute window.
Failures ratelimit.FailureCounter
// Hooks are optional; the zero value does nothing.
Hooks Hooks
// Observer is optional; the zero value does nothing.
Observer Observer
// Now is the clock; default time.Now.
Now func() time.Time
// HTTPClient is used for OAuth provider calls; default a client with a 10 s timeout.
HTTPClient *http.Client
}
Deps are the collaborators authkit needs.
type Hooks ¶
type Hooks struct {
// OnUserCreated runs in the transaction that inserts the user; registration runs it after the response was sent.
OnUserCreated func(ctx context.Context, tx pgx.Tx, u User) error
// OnDeletionRequested runs in the transaction that locks the account for deletion; hide public data here.
OnDeletionRequested func(ctx context.Context, tx pgx.Tx, u User) error
// OnDeletionCancelled runs in the transaction that restores the account.
OnDeletionCancelled func(ctx context.Context, tx pgx.Tx, u User) error
// OnUserDeleted runs in the purge transaction right before the user row is deleted. An error skips that user
// only; the purge is retried on the next job run while every other user and cleanup step goes on.
OnUserDeleted func(ctx context.Context, tx pgx.Tx, u User) error
// Export returns the host's data of the user for the GDPR export; it must be JSON-encodable.
Export func(ctx context.Context, u User) (any, error)
}
Hooks let the host react to account lifecycle events. Hooks that receive a pgx.Tx run inside the authkit transaction: returning an error rolls it back and the client gets 500 internal. Panics are not recovered.
Example ¶
Hooks run inside authkit's transactions, so host rows change atomically with the account.
package main
import (
"context"
"github.com/jackc/pgx/v5"
"github.com/johnnycube/authkit"
)
func main() {
hooks := authkit.Hooks{
OnUserCreated: func(ctx context.Context, tx pgx.Tx, u authkit.User) error {
_, err := tx.Exec(ctx, `INSERT INTO app.profiles (user_id) VALUES ($1)`, u.ID)
return err
},
OnDeletionRequested: func(ctx context.Context, tx pgx.Tx, u authkit.User) error {
_, err := tx.Exec(ctx, `UPDATE app.profiles SET public = false WHERE user_id = $1`, u.ID)
return err
},
Export: func(ctx context.Context, u authkit.User) (any, error) {
return map[string]any{"notes": []string{}}, nil
},
}
_ = authkit.Deps{Hooks: hooks}
}
Output:
type JobReport ¶
type JobReport struct {
// UnverifiedPurged counts accounts deleted for never verifying their address within UnverifiedTTL.
UnverifiedPurged int64
// DeletedPurged counts accounts deleted after their deletion grace period.
DeletedPurged int64
// PurgeFailed counts users whose purge failed (e.g. OnUserDeleted returned an error); they are retried next run.
PurgeFailed int64
// SessionsExpired counts removed expired sessions.
SessionsExpired int64
// TokensExpired counts removed expired or used mail tokens.
TokensExpired int64
// FlowsExpired counts removed expired multi-step flows (second factor, passkey, OAuth).
FlowsExpired int64
// AltchaExpired counts removed expired ALTCHA replay records.
AltchaExpired int64
// Skipped reports that another instance held the job lock, so nothing ran.
Skipped bool
}
JobReport counts what one job run removed.
type LinkKind ¶
type LinkKind string
LinkKind names a frontend page that mails link to.
const ( LinkVerify LinkKind = "verify" LinkLogin LinkKind = "login" LinkReset LinkKind = "reset" LinkEmailChange LinkKind = "email_change" LinkEmailRevert LinkKind = "email_revert" LinkDeletionCancel LinkKind = "deletion_cancel" LinkOAuthResult LinkKind = "oauth_result" )
Frontend pages authkit links to.
type OAuthProvider ¶
type OAuthProvider struct {
// Name is the URL slug, e.g. google.
Name string `json:"name"`
// DisplayName is shown to users, e.g. Google.
DisplayName string `json:"display_name"`
// ClientID is the OAuth client ID registered with the provider.
ClientID string `json:"client_id"`
// ClientSecret is the OAuth client secret.
ClientSecret string `json:"client_secret"`
// Issuer selects OpenID Connect: endpoints come from its discovery document and ID tokens are verified.
Issuer string `json:"issuer"`
// AuthURL is the authorization endpoint of a plain OAuth2 provider (no Issuer).
AuthURL string `json:"auth_url"`
// TokenURL is the token endpoint of a plain OAuth2 provider (no Issuer).
TokenURL string `json:"token_url"`
// UserInfoURL returns the subject and email claims of a plain OAuth2 provider (no Issuer).
UserInfoURL string `json:"userinfo_url"`
// Scopes requested at the provider; with Issuer the default is openid and email.
Scopes []string `json:"scopes"`
// SubjectClaim names the stable user ID in the userinfo response of a plain OAuth2 provider; default sub.
SubjectClaim string `json:"subject_claim"`
// EmailClaim names the address claim of a plain OAuth2 provider; default email.
EmailClaim string `json:"email_claim"`
// EmailVerifiedClaim names the verified flag of a plain OAuth2 provider; default email_verified.
EmailVerifiedClaim string `json:"email_verified_claim"`
// EmailsURL is a GitHub-style endpoint listing the user's addresses as [{email, primary, verified}]; when set,
// the primary address and its verified flag replace the userinfo email claims.
EmailsURL string `json:"emails_url"`
}
OAuthProvider configures one OAuth2 or OpenID Connect provider. With Issuer set, endpoints come from discovery and the ID token is verified; otherwise AuthURL, TokenURL and UserInfoURL describe a plain OAuth2 provider.
func GitHub ¶
func GitHub(clientID, clientSecret string) OAuthProvider
GitHub returns the provider configuration for GitHub OAuth apps. The account address is the user's primary email, and only when GitHub reports it verified.
Example ¶
GitHub is a preset for a plain OAuth2 provider; OIDC providers only need an Issuer.
package main
import (
"fmt"
"github.com/johnnycube/authkit"
)
func main() {
providers := []authkit.OAuthProvider{
authkit.GitHub("client-id", "client-secret"),
{Name: "google", DisplayName: "Google", ClientID: "id", ClientSecret: "secret", Issuer: "https://accounts.google.com"},
}
for _, p := range providers {
fmt.Println(p.Name, p.Issuer != "")
}
}
Output: github false google true
type Observer ¶
type Observer struct {
// Event receives every audit event name (login, login_failed, rate_limited, user_purged, ...).
Event func(ctx context.Context, event string)
// Mail reports each delivery attempt; mail is at most once, a failed send is not retried.
Mail func(ctx context.Context, kind mail.Kind, err error)
// Jobs reports each RunJobsOnce result that was not skipped.
Jobs func(ctx context.Context, rep JobReport, err error)
}
Observer receives operational signals, e.g. for metrics; every field is optional and must not block.
Example ¶
Observer turns authkit's audit events, mail deliveries and job runs into metrics without a metrics dependency.
package main
import (
"context"
"encoding/json"
"log"
"github.com/johnnycube/authkit"
"github.com/johnnycube/authkit/mail"
)
func main() {
counts := map[string]int{}
obs := authkit.Observer{
Event: func(_ context.Context, event string) { counts[event]++ }, // must not block; use a mutex or atomic counters
Mail: func(_ context.Context, kind mail.Kind, err error) {
if err != nil {
log.Printf("mail %s failed: %v", kind, err)
}
},
Jobs: func(_ context.Context, rep authkit.JobReport, err error) {
b, _ := json.Marshal(rep)
log.Printf("jobs: %s %v", b, err)
},
}
_ = authkit.Deps{Observer: obs}
}
Output:
type User ¶
type User struct {
// ID is stable for the account's lifetime; host tables reference it.
ID uuid.UUID `json:"id"`
// Email is the current, normalised address.
Email string `json:"email"`
// EmailVerified reports whether the address was confirmed by mail or a trusted provider.
EmailVerified bool `json:"email_verified"`
// Language is the user's language for mails, one of Config.Languages.
Language string `json:"language"`
// CreatedAt is when the account was registered.
CreatedAt time.Time `json:"created_at"`
// DeletionRequestedAt is set while the account is in its deletion grace period.
DeletionRequestedAt *time.Time `json:"deletion_requested_at,omitempty"`
}
User is the public view of an authkit account.
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
Package authkittest helps hosts test code that sits behind authkit: a recording mailer with link extraction, a controllable clock, an HTTP client that speaks authkit's Origin, CSRF and ALTCHA protocol, and fixtures that create users and sessions without SQL against authkit's tables (whose layout is not public API).
|
Package authkittest helps hosts test code that sits behind authkit: a recording mailer with link extraction, a controllable clock, an HTTP client that speaks authkit's Origin, CSRF and ALTCHA protocol, and fixtures that create users and sessions without SQL against authkit's tables (whose layout is not public API). |
|
internal
|
|
|
secretbox
Package secretbox encrypts small secrets with AES-256-GCM.
|
Package secretbox encrypts small secrets with AES-256-GCM. |
|
token
Package token generates, parses and hashes opaque random tokens.
|
Package token generates, parses and hashes opaque random tokens. |
|
Package mail renders authkit's transactional mails and delivers them through a pluggable Mailer.
|
Package mail renders authkit's transactional mails and delivers them through a pluggable Mailer. |
|
Package ratelimit defines the rate limiting and failure counting ports authkit uses, with in-process implementations.
|
Package ratelimit defines the rate limiting and failure counting ports authkit uses, with in-process implementations. |