Architecture
High-level overview and design principles.
Source: docs/ARCHITECTURE.md
OneAuth Architecture ¶
Overview ¶
OneAuth is a Go authentication library that provides unified local and OAuth-based authentication, multi-tenant JWT management, and federated auth for distributed services. It’s designed as an embeddable library (not a standalone service) that integrates directly into Go applications. A reference server (cmd/oneauth-server/) is provided for standalone deployment.
Go version: 1.24.0+
Core Design Principles ¶
- Separation of Concerns: Users, Identities, and Channels as distinct layers
- Framework Agnostic: Works with net/http and any router
- Storage Agnostic: Interface-based stores with multiple implementations
- Callback-Based: Application controls session management, email delivery, etc.
Three-Layer Data Model ¶
flowchart TD
User["User<br/>- Unique account in the system<br/>- Contains profile data<br/>- Has multiple identities"]
User --> Id1["Identity<br/>email:...<br/>(verified)"]
User --> Id2["Identity<br/>phone:...<br/>(unverified)"]
User --> Id3["Identity<br/>email:...<br/>(verified)"]
Id1 --> Ch1["Channel<br/>local<br/>(password)"]
Id3 --> Ch2["Channel<br/>google<br/>(oauth)"]
Id3 --> Ch3["Channel<br/>github<br/>(oauth)"]
- User: Unique account identified by user ID. Contains profile information.
- Identity: Contact method (email, phone) with verification status. Shared across auth channels.
- Channel: Authentication mechanism (local, google, github) with provider-specific credentials.
- UsernameStore (Optional): Username uniqueness enforcement and username-based login.
Multiple channels can point to the same user via shared email identity, enabling multi-provider login.
Three Authentication Modes ¶
OneAuth supports three authentication modes, each targeting a different client type:
| Mode | What it covers |
|---|---|
Browser Auth (LocalAuth) |
Form login/signup · Email verify · Password reset · Session cookies |
API Auth (APIAuth) |
JWT access tokens · Refresh tokens · API keys · Scope enforcement |
Federated Auth (AppRegistrar + MintResourceToken) |
App registers, mints scoped JWTs, resource server validates via KeyStore |
Each mode has its own detailed documentation:
- Browser Auth — Form-based login/signup, OAuth integration, channel linking, email verification, password reset, session management, validation, and error handling
- API Auth — JWT access tokens, refresh tokens with rotation and theft detection, API keys, scope-based access control, custom claims, multi-tenant JWT validation via KeyStore
- Federated Auth — App Registration API (AdminAuth, AppRegistrar), resource token minting (MintResourceToken), multi-service architecture with shared KeyStore
- Auth Flows — Detailed decision trees for login/signup, provider linking matrix, user journeys, edge cases
Package Organization ¶
flowchart TD
core["core/<br/>Foundation types, interfaces,<br/>zero internal deps"]
keys["keys/<br/>Key mgmt"]
localauth["localauth/<br/>Local auth"]
admin["admin/<br/>Admin API"]
apiauth["apiauth/<br/>JWT auth"]
httpauth["httpauth/<br/>HTTP middleware, CSRF, session mux"]
core --- keys
core --- apiauth
core --- localauth
keys --- admin
keys --- apiauth
apiauth --- httpauth
Each subpackage has a SUMMARY.md for quick orientation.
Store Architecture ¶
flowchart TD
subgraph Interfaces["Interfaces"]
direction TB
CoreIf["core/ — Store Interfaces<br/>UserStore | IdentityStore | ChannelStore | TokenStore<br/>RefreshTokenStore | APIKeyStore | UsernameStore (opt)"]
KeysIf["keys/ — Key Interfaces<br/>KeyStorage | KeyLookup (multi-tenant JWT + kid lookup)"]
CoreIf ~~~ KeysIf
end
Interfaces --> FS["stores/fs<br/>File-based<br/>Development"]
Interfaces --> Gorm["stores/gorm<br/>SQL (GORM)<br/>Production"]
Interfaces --> Gae["stores/gae<br/>Datastore<br/>Google Cloud"]
For store interfaces, implementations, and KeyStore details, see Stores.
Demos ¶
See DEMOS.md for runnable demos that exercise key scenarios end-to-end, including what each demo simplifies vs. production usage.
Client SDK ¶
For CLI tools and programmatic clients consuming oneauth-protected APIs:
flowchart LR
AuthClient["AuthClient"] --> LoginLogout["Login/Logout"] --> CredentialStore["CredentialStore<br/>(persists tokens)"]
AuthClient --> HTTPClient["HTTPClient()"] --> RefreshTransport["refreshTransport<br/>(auto-refresh on 401)"]
See Client SDK for full details.
Security Architecture ¶
Password Security ¶
- bcrypt hashing with cost 10
- Constant-time comparison
Token Security ¶
- Cryptographically secure random generation (32 bytes)
- Single-use verification tokens (deleted after use)
- Expiry enforcement with lazy cleanup
JWT Security ¶
- HS256, RS256, and ES256 signing (per-app algorithm choice, all coexist in the same KeyStore)
- Asymmetric signing: apps keep private keys, register only public keys; resource servers verify without knowing signing secrets
- JWKS endpoint (
/.well-known/jwks.json) for public key discovery — resource servers can fetch asymmetric keys via HTTP instead of sharing database access JWKSKeyStore— read-only KeyStore that fetches from a remote JWKS URL with background refresh, caching, and resilience- Protected Resource Metadata (
/.well-known/oauth-protected-resource, RFC 9728) — resource servers advertise their capabilities for client auto-discovery - Audience and issuer validation (string and array
audper RFC 7519 §4.1.3) kid(Key ID) in all JWT headers — RFC 7638 thumbprint enables JWKS-based key discovery- Algorithm confusion prevention via
KeyRecord.Algorithmcheck utils.DecodeVerifyKeyconverts stored PEM bytes tocrypto.PublicKeyat read time
Key ID (kid) in JWTs ¶
- All minted JWTs include
kidheader (RFC 7638 thumbprint computed from key material) APIMiddlewaretries kid-based lookup first (GetKeyByKid), falls back toclient_idclaim (GetKey)KidStoreretains old keys during rotation with configurable grace periodCompositeKeyLookupchains multipleKeyLookupsources (KeyStorage for current + KidStore for rotated)- Cross-app token forgery prevented via
KeyRecord.ClientIDcross-check againstclient_idclaim
Encryption at Rest ¶
EncryptedKeyStorage— decorator that wraps anyKeyStorageto encrypt sensitive key material at rest using AES-256-GCM- Master key: 32-byte hex string (
ONEAUTH_MASTER_KEYenv var), derived via HKDF-SHA256 with a versioned info string - Encrypted: HMAC client secrets (HS256/HS384/HS512) — identified by Algorithm; and PEM blocks whose header type contains
PRIVATE(PRIVATE KEY,RSA PRIVATE KEY,EC PRIVATE KEY,OPENSSH PRIVATE KEY) — identified by content. Content-driven so private keys persisted under non-JWT Algorithm strings (e.g.,ssh-ed25519via thesshkeyssubmodule) are still covered. - Plaintext: public PEMs that back JWKS exposure, and any non-PEM non-HMAC payload that’s not sensitive
- Migration: stored bytes starting with
-----BEGIN(pre-encryption legacy or public PEMs) are returned as-is; non-PEM bytes with a failing GCM tag fall back to plaintext with a log warning (backward compat with pre-encryption HMAC data) - Optional: no master key configured = no encryption (with log warning)
PKCE (Proof Key for Code Exchange) ¶
- All OAuth2 flows use PKCE (RFC 7636) by default — prevents authorization code interception
code_challenge(S256) sent with authorization URL,code_verifiersent on token exchange- Verifier stored in HttpOnly cookie during the OAuth round-trip
DisablePKCEopt-out for providers that don’t support PKCE (logs warning)- Required by OAuth 2.1 for all clients (not just public)
CSRF Protection ¶
CSRFMiddleware— double-submit cookie pattern, opt-in per-endpoint- Constant-time token comparison (
crypto/subtle) - Bearer-token requests exempt by default
- Per-session tokens (not per-request) for back button / multi-tab compatibility
Refresh Token Security ¶
- Rotation on use
- Family-based theft detection (reuse → revoke entire family)
- Immediate revocation capability
Extension Points ¶
| Extension | Purpose | Doc |
|---|---|---|
SignupPolicy |
Configurable signup requirements | Browser Auth |
OnSignupError / OnLoginError |
Custom error handlers | Browser Auth |
ValidateSignup (legacy) |
Custom signup validation | Browser Auth |
GetUserScopes |
Custom scope resolution | API Auth |
CustomClaimsFunc |
Inject custom JWT claims | API Auth |
EmailSender |
Custom email delivery | Browser Auth |
AdminAuth |
Pluggable admin authentication | Federated Auth |
| Store interfaces | Custom database backends | Stores |
Positioning ¶
OneAuth differentiates from alternatives by being:
- Embeddable library (not a service to run)
- Go-native (not language-agnostic)
- Simple model (User → Identity → Channel)
- Multiple store options (file, SQL, NoSQL)
- Callback-based (app controls sessions)
- Federated-ready (multi-tenant KeyStore, app registration, resource token minting)
- Standards-compliant (RFC 7662 introspection, RFC 8414 AS discovery, RFC 9728 PRM, RFC 8252 native app auth, RFC 7636 PKCE)
- Keycloak-tested (interop test suite validates against real IdP)
Closest alternatives:
go-pkgz/auth— Similar middleware focus, less flexible modelOry Kratos— Full IAM platform, more complexAuthelia— Reverse proxy companion, different architecture
Documentation Index ¶
| Document | Description |
|---|---|
| ARCHITECTURE.md | This file — high-level overview |
| BROWSER_AUTH.md | Browser-based authentication (LocalAuth, OAuth, sessions) |
| API_AUTH.md | API authentication (JWT, refresh tokens, API keys, KeyStore) |
| FEDERATED_AUTH.md | Federated auth (AppRegistrar, MintResourceToken, AdminAuth) |
| AUTH_FLOWS.md | Detailed decision trees, user journeys, edge cases |
| CLIENT_SDK.md | Client SDK for CLI/programmatic access |
| STORES.md | Store interfaces and implementations |
| GETTING_STARTED.md | Quick start guide |
| USER_GUIDE.md | User guide |
| DEVELOPER_GUIDE.md | Developer guide |
| DEMOS.md | Runnable demos & production vs. demo comparison |
| TESTING.md | Testing guide |
| GRPC.md | gRPC integration |