Documentation
¶
Overview ¶
Package auth is the batteries-included GOWDK authentication addon. It enables the auth feature and ships a working, dependency-free identity implementation: PBKDF2 password hashing, a PasswordHasher replacement point, and signed-cookie or revocable sessions, all on the Go standard library. It builds on the native RBAC guard machinery in runtime/auth. Pages and routes protected with guard role:... or guard permission:... resolve through a session-backed Provider; guard public remains intentionally unauthenticated.
GOWDK still does not own your user store. Look users up however you like, then hand the addon a Principal to issue a session for; the addon owns default hashing helpers, session signing, and request-time principal resolution. Revocable sessions require an application-owned SessionStore.
Index ¶
- Constants
- Variables
- func Addon(options ...Options) gowdk.Addon
- func HashPassword(password string) (string, error)
- func HashPasswordWithIterations(password string, iterations int) (string, error)
- func RequireAuthenticated(provider Provider) guard.Func
- func VerifyPassword(password, encoded string) bool
- type InMemorySessionStore
- func (store *InMemorySessionStore) CreateSession(_ context.Context, record SessionRecord) error
- func (store *InMemorySessionStore) LookupSession(_ context.Context, id string) (SessionRecord, error)
- func (store *InMemorySessionStore) RevokePrincipal(_ context.Context, principalID string) error
- func (store *InMemorySessionStore) RevokeSession(_ context.Context, id string) error
- func (store *InMemorySessionStore) TouchSession(_ context.Context, id string, seenAt time.Time, idleExpiresAt time.Time) error
- func (store *InMemorySessionStore) UpdateSession(_ context.Context, id string, update func(*SessionRecord)) error
- type Options
- type PBKDF2Hasher
- type PasswordHasher
- type Principal
- type Provider
- type ProviderFunc
- type SessionMode
- type SessionRecord
- type SessionStore
- type SessionToucher
- type Sessions
- func (sessions *Sessions) Clear(writer http.ResponseWriter)
- func (sessions *Sessions) ClearCookie() http.Cookie
- func (sessions *Sessions) ClearRequest(writer http.ResponseWriter, request *http.Request) error
- func (sessions *Sessions) Cookie(principal Principal) (http.Cookie, error)
- func (sessions *Sessions) Issue(writer http.ResponseWriter, principal Principal) error
- func (sessions *Sessions) Mode() SessionMode
- func (sessions *Sessions) Principal(request *http.Request) (*Principal, error)
- func (sessions *Sessions) Provider() Provider
- func (sessions *Sessions) Revoke(ctx context.Context, request *http.Request) error
- func (sessions *Sessions) RevokePrincipal(ctx context.Context, principalID string) error
- func (sessions *Sessions) RevokeSession(ctx context.Context, sessionID string) error
- func (sessions *Sessions) Rotate(writer http.ResponseWriter, request *http.Request, principal Principal) error
- type SigningKey
Constants ¶
const ( // DefaultIterations is the PBKDF2 iteration count for new password hashes. // It is encoded into each hash so stored credentials remain verifiable if // this default later increases. DefaultIterations = 600000 // MinIterations is the minimum accepted PBKDF2 iteration count for new and // stored hashes. Keep this separate from DefaultIterations so existing // stored hashes remain verifiable if the default later increases. MinIterations = 600000 // MaxIterations is the maximum accepted PBKDF2 iteration count for new and // stored hashes. It bounds CPU cost when verifying imported or corrupted // hashes while leaving room for future default increases. MaxIterations = 2000000 )
const ( // DefaultSessionCookie is the cookie name used for signed sessions. DefaultSessionCookie = "gowdk_session" // DefaultSessionTTL is how long an issued session remains valid. DefaultSessionTTL = 24 * time.Hour // DefaultSessionSecretEnv is the recommended runtime environment variable // for session signing secrets. DefaultSessionSecretEnv = "GOWDK_AUTH_SESSION_SECRET" // MinSessionSecretBytes is the minimum accepted session signing secret // length. MinSessionSecretBytes = 32 )
const ImportPath = "github.com/cssbruno/gowdk/addons/auth"
ImportPath is the canonical Go import path for the auth addon.
Variables ¶
var ErrInvalidHash = errors.New("gowdk auth: invalid password hash")
ErrInvalidHash reports that an encoded password hash is malformed.
var ErrNoSession = errors.New("gowdk auth: no session")
ErrNoSession reports that a request carries no readable session cookie.
var ErrSessionNotFound = errors.New("gowdk auth: session not found")
ErrSessionNotFound reports that a revocable session ID is unknown to the configured store.
Functions ¶
func HashPassword ¶
HashPassword derives a PBKDF2-HMAC-SHA256 hash of password using a fresh random salt and the default iteration count. The returned value is self-describing and safe to store: pbkdf2-sha256$<iter>$<b64salt>$<b64hash>.
func HashPasswordWithIterations ¶
HashPasswordWithIterations is HashPassword with an explicit work factor.
func RequireAuthenticated ¶ added in v0.7.0
RequireAuthenticated returns an auth.required guard backed by provider. When provider is nil, it falls back to the addon-level Sessions configured by the generated app.
func VerifyPassword ¶
VerifyPassword reports whether password matches encoded. Comparison is constant-time. A malformed encoding returns false rather than an error so callers cannot distinguish "wrong password" from "corrupt record" by timing or control flow.
Types ¶
type InMemorySessionStore ¶ added in v0.12.0
type InMemorySessionStore struct {
// contains filtered or unexported fields
}
InMemorySessionStore is a dependency-free SessionStore for tests, examples, and single-process development. Production apps should use an app-owned durable store so revocation survives restarts and works across instances.
func NewInMemorySessionStore ¶ added in v0.12.0
func NewInMemorySessionStore() *InMemorySessionStore
NewInMemorySessionStore creates an empty in-memory revocation store.
func (*InMemorySessionStore) CreateSession ¶ added in v0.12.0
func (store *InMemorySessionStore) CreateSession(_ context.Context, record SessionRecord) error
CreateSession records a new server-side session.
func (*InMemorySessionStore) LookupSession ¶ added in v0.12.0
func (store *InMemorySessionStore) LookupSession(_ context.Context, id string) (SessionRecord, error)
LookupSession returns the current server-side session state.
func (*InMemorySessionStore) RevokePrincipal ¶ added in v0.12.0
func (store *InMemorySessionStore) RevokePrincipal(_ context.Context, principalID string) error
RevokePrincipal marks every current session for principalID invalid.
func (*InMemorySessionStore) RevokeSession ¶ added in v0.12.0
func (store *InMemorySessionStore) RevokeSession(_ context.Context, id string) error
RevokeSession marks one session ID invalid. It is idempotent.
func (*InMemorySessionStore) TouchSession ¶ added in v0.12.0
func (store *InMemorySessionStore) TouchSession(_ context.Context, id string, seenAt time.Time, idleExpiresAt time.Time) error
TouchSession updates LastSeenAt and IdleExpiresAt for a live session.
func (*InMemorySessionStore) UpdateSession ¶ added in v0.12.0
func (store *InMemorySessionStore) UpdateSession(_ context.Context, id string, update func(*SessionRecord)) error
UpdateSession applies update to one in-memory session record. It is intended for tests and examples that need to model role, permission, or account-state changes without a database.
type Options ¶
type Options struct {
// Secret signs session payloads with HMAC-SHA256. It must be non-empty and
// should be high-entropy and stable across instances.
Secret []byte
// SecretEnv names the environment variable to read instead of Secret. Error
// messages include this name, never the secret value.
SecretEnv string
// KeyID names the current signing key. When set, issued cookies include this
// ID so future managers can accept it through PreviousKeys during rotation.
KeyID string
// PreviousKeys are accepted for verification only. Use them for bounded
// signing-key rotation, then remove them after AcceptUntil passes.
PreviousKeys []SigningKey
// Mode selects the session strategy. The zero value is signed-cookie mode.
Mode SessionMode
// Store is required in revocable mode and is consulted on every protected
// request before returning a principal.
Store SessionStore
// CookieName overrides DefaultSessionCookie.
CookieName string
// TTL overrides DefaultSessionTTL.
TTL time.Duration
// IdleTTL optionally expires revocable sessions when they are unused for this
// duration. The absolute TTL still applies.
IdleTTL time.Duration
// Insecure drops the Secure cookie flag for local HTTP development. Leave
// false in production so the cookie is only sent over HTTPS.
Insecure bool
// Now overrides the clock, for tests.
Now func() time.Time
}
Options configures a Sessions manager. Secret or SecretEnv is required; everything else has a working default.
type PBKDF2Hasher ¶ added in v0.5.0
type PBKDF2Hasher struct {
Iterations int
}
PBKDF2Hasher is the default dependency-free password hasher used by this addon. Iterations defaults to DefaultIterations when omitted.
func (PBKDF2Hasher) HashPassword ¶ added in v0.5.0
func (hasher PBKDF2Hasher) HashPassword(password string) (string, error)
HashPassword derives a PBKDF2-HMAC-SHA256 hash of password using a fresh random salt.
func (PBKDF2Hasher) VerifyPassword ¶ added in v0.5.0
func (hasher PBKDF2Hasher) VerifyPassword(password, encoded string) bool
VerifyPassword reports whether password matches encoded.
type PasswordHasher ¶ added in v0.5.0
type PasswordHasher interface {
HashPassword(password string) (string, error)
VerifyPassword(password, encoded string) bool
}
PasswordHasher hashes and verifies stored password credentials.
type Principal ¶
type Principal = runtimeauth.Principal
Principal is the application identity visible to native RBAC guards. It is re-exported from runtime/auth so callers of this addon need only one import.
type Provider ¶
type Provider = runtimeauth.Provider
Provider resolves the current principal for a request. Register the value returned by Sessions.Provider with the generated RegisterAuthProvider hook.
type ProviderFunc ¶
type ProviderFunc = runtimeauth.ProviderFunc
ProviderFunc adapts a function into a Provider.
type SessionMode ¶ added in v0.12.0
type SessionMode string
SessionMode describes how session cookies are interpreted.
const ( // SessionModeSignedCookie stores the full principal in the signed cookie. // It has no server-side revocation lookup and remains intended for bounded // development, tests, and simple deployments that accept that tradeoff. SessionModeSignedCookie SessionMode = "signed-cookie" // SessionModeRevocable stores only a signed session pointer in the cookie and // resolves the current principal from SessionStore on every request. SessionModeRevocable SessionMode = "revocable" )
type SessionRecord ¶ added in v0.12.0
type SessionRecord struct {
ID string
Principal Principal
AuthorizationVersion string
CreatedAt time.Time
ExpiresAt time.Time
IdleExpiresAt time.Time
LastSeenAt time.Time
Revoked bool
}
SessionRecord is the server-owned state checked for every request in revocable mode. Principal roles and permissions are resolved from this record, not trusted from the signed cookie for the cookie's full lifetime.
type SessionStore ¶ added in v0.12.0
type SessionStore interface {
CreateSession(context.Context, SessionRecord) error
LookupSession(context.Context, string) (SessionRecord, error)
RevokeSession(context.Context, string) error
RevokePrincipal(context.Context, string) error
}
SessionStore is the persistence boundary for revocable sessions. Applications can back it with a database, cache, or another durable service without adding a mandatory dependency to the GOWDK root module.
type SessionToucher ¶ added in v0.12.0
SessionToucher lets a store slide idle expiry after a successful lookup.
type Sessions ¶
type Sessions struct {
// contains filtered or unexported fields
}
Sessions issues and reads signed-cookie sessions and resolves the current Principal for a request. The zero value is not usable; construct one with New. Sessions implements Provider.
func Configure ¶ added in v0.7.0
Configure initializes the process-wide default session manager used by DefaultSessions and generated auth wiring.
func DefaultSessions ¶ added in v0.7.0
DefaultSessions returns the process-wide session manager. When Configure has not been called yet, it creates one from DefaultSessionSecretEnv.
func (*Sessions) Clear ¶
func (sessions *Sessions) Clear(writer http.ResponseWriter)
Clear writes an immediately-expired session cookie, logging the request out.
func (*Sessions) ClearCookie ¶ added in v0.5.0
ClearCookie creates an immediately-expired session cookie.
func (*Sessions) ClearRequest ¶ added in v0.12.0
ClearRequest revokes the current server-side session in revocable mode, then writes an expired cookie. Signed-cookie mode only writes the expired cookie.
func (*Sessions) Issue ¶
func (sessions *Sessions) Issue(writer http.ResponseWriter, principal Principal) error
Issue writes a signed session cookie for principal to the response.
func (*Sessions) Mode ¶ added in v0.12.0
func (sessions *Sessions) Mode() SessionMode
Mode reports the configured session strategy.
func (*Sessions) Principal ¶
Principal resolves the current principal from the request's session cookie. A request with no cookie, or a tampered or expired one, yields a nil principal and no error, meaning unauthenticated.
func (*Sessions) Provider ¶
Provider returns sessions typed as a Provider for registration with the generated RegisterAuthProvider hook.
func (*Sessions) Revoke ¶ added in v0.12.0
Revoke invalidates the session presented by request in revocable mode.
func (*Sessions) RevokePrincipal ¶ added in v0.12.0
RevokePrincipal invalidates all sessions for principalID in the configured revocable store.
func (*Sessions) RevokeSession ¶ added in v0.12.0
RevokeSession invalidates one revocable session ID.
func (*Sessions) Rotate ¶ added in v0.12.0
func (sessions *Sessions) Rotate(writer http.ResponseWriter, request *http.Request, principal Principal) error
Rotate revokes the current revocable session, then issues a fresh cookie for principal. Applications should call this after authentication and sensitive authorization changes.