auth

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Oct 24, 2026 License: MIT Imports: 20 Imported by: 0

Documentation

Overview

Package auth provides JWT session authentication for the admin console and API. Console accounts (username, bcrypt hash, role, disabled flag, token version) live in the users store (internal/users); on first start, with an empty store, cmd/jo-ei creates the initial "admin" account. A successful POST /api/auth/login exchanges a username and password for an HS256-signed session: HttpOnly access/refresh cookies for the browser console, and a bearer access token in the response body for scripts and CI. Every request re-reads its user from the store, so disabling, deleting or bumping a user's token version revokes their sessions at once. The /api/auth/* endpoints (login, refresh, logout, me, password) and the session-verifying middleware live in this package. With no enabled users the console is "locked" (fail-closed): the middleware serves 503 on /api/ and never reaches the wrapped handler — the console shell itself stays public so its login screen can still render.

Index

Constants

View Source
const (
	LoginPairLimit = 5
	LoginIPLimit   = 20
	LoginWindow    = 15 * time.Minute
)

Login throttling limits: failures per (username, client IP) pair and per client IP within a fixed window.

View Source
const (
	AccessCookie      = "joei_at"
	RefreshCookie     = "joei_rt"
	RefreshCookiePath = "/api/auth"
)

Session cookie names and the refresh cookie's path. The refresh cookie is scoped to /api/auth so it never rides along on ordinary API calls: only the endpoints that can spend it ever see it.

View Source
const (
	TypeAccess  = "access"
	TypeRefresh = "refresh"
)

Token types. A refresh token is never accepted where an access token is expected, and vice versa: the type is part of what Verify checks.

View Source
const MinSecretLen = 32

MinSecretLen is the shortest signing secret accepted. HMAC-SHA256 keys shorter than the hash output add no security and a short secret is almost always a placeholder someone forgot to replace.

Variables

View Source
var (
	ErrMalformedToken = errors.New("auth: malformed token")
	ErrBadSignature   = errors.New("auth: bad token signature")
	ErrExpiredToken   = errors.New("auth: token expired")
	ErrWrongTokenType = errors.New("auth: wrong token type")
)

Token verification failures. Callers map all of them to the same 401 — the distinction exists for logs and tests, never for the response body.

Functions

func Recheck added in v0.6.0

func Recheck(ctx context.Context) bool

Recheck reports whether the session that authenticated the request behind ctx is still good: its user exists, is enabled, needs no password change and is at the same token version. Long-lived handlers (the SSE stream) call it periodically and stop when it turns false. Token expiry is not re-checked — a stream outliving its access token is fine; a revoked one is not. Without a re-validator in ctx (no Middleware) it returns true.

func UserFromContext

func UserFromContext(ctx context.Context) (string, bool)

UserFromContext returns the authenticated username stored by Middleware, and false when the request did not pass through the authenticating middleware.

func WithIdentity added in v0.6.0

func WithIdentity(ctx context.Context, id Identity) context.Context

WithIdentity returns ctx carrying id. Middleware uses it; it is exported so handler tests can fake an authenticated request.

func WithRecheck added in v0.6.0

func WithRecheck(ctx context.Context, fn func() bool) context.Context

WithRecheck returns ctx carrying fn as its session re-validator. Middleware uses it; it is exported so handler tests can fake a session that goes bad.

Types

type Claims added in v0.4.0

type Claims struct {
	Sub string `json:"sub"` // username (as stored)
	Ver int64  `json:"ver"` // the user's token_version at issue; a bump revokes the token
	Typ string `json:"typ"` // TypeAccess or TypeRefresh
	IAT int64  `json:"iat"` // issued at, Unix seconds
	Exp int64  `json:"exp"` // expires at, Unix seconds
	JTI string `json:"jti"` // random id, so two tokens issued in the same second differ
}

Claims is the JWT payload. Issuer and audience are omitted: single issuer, single audience, and every claim we do not need is one more thing to check.

type Identity added in v0.6.0

type Identity struct {
	Username           string
	Role               users.Role
	MustChangePassword bool
}

Identity is the authenticated caller, as Middleware puts it in the request context. Username is the stored spelling, whatever case the client used.

func IdentityFromContext added in v0.6.0

func IdentityFromContext(ctx context.Context) (Identity, bool)

IdentityFromContext returns the identity stored by Middleware, and false when the request did not pass through the authenticating middleware.

type LoginLimiter added in v0.6.0

type LoginLimiter struct {
	// contains filtered or unexported fields
}

LoginLimiter throttles console logins. Each key uses a fixed window that starts at the key's first counted attempt. Safe for concurrent use.

Allow reserves the attempt — counts it as a failure in progress — before the caller checks the password, so N parallel requests cannot all slip through a check-then-record gap. Success takes the reservation back.

func NewLoginLimiter added in v0.6.0

func NewLoginLimiter(now func() time.Time) *LoginLimiter

NewLoginLimiter returns a limiter; a nil now defaults to time.Now.

func (*LoginLimiter) Allow added in v0.6.0

func (l *LoginLimiter) Allow(username, ip string) (time.Duration, bool)

Allow reports whether a login attempt may proceed and, if so, counts it against both the pair and the IP until Success takes it back. When blocked it returns the time left until the blocking window ends (the larger one if both block); a blocked attempt is not counted, so waiting out Retry-After is always enough.

func (*LoginLimiter) Success added in v0.6.0

func (l *LoginLimiter) Success(username, ip string)

Success records that the attempt Allow admitted succeeded: the pair's failures are cleared and the attempt's own reservation is taken back from the IP. Earlier failures on the IP are left intact.

type Option added in v0.6.0

type Option func(*Sessions)

Option configures a Sessions.

func WithClientIP added in v0.6.0

func WithClientIP(fn func(*http.Request) string) Option

WithClientIP sets how the client IP is derived from a request, for the login limiter and logs. The default is the host part of RemoteAddr, which is right only when no reverse proxy sits in front.

func WithLogger added in v0.6.0

func WithLogger(l zerolog.Logger) Option

WithLogger sets the logger for login, rate-limit and password-change lines. It is tagged component=auth. The default discards everything.

func WithLoginLimiter added in v0.6.0

func WithLoginLimiter(l *LoginLimiter) Option

WithLoginLimiter sets the limiter that throttles failed logins and failed current-password checks. Without it, Sessions uses its own limiter.

type Sessions added in v0.4.0

type Sessions struct {
	// contains filtered or unexported fields
}

Sessions authenticates console and API requests from JWT sessions. It owns the cookies, the middleware, and the /api/auth handlers (see handlers.go). Every request re-reads its user from the store, so a disabled or deleted user, or a bumped token version, takes effect immediately.

func NewSessions added in v0.4.0

func NewSessions(store UserStore, signer *Signer, accessTTL, refreshTTL time.Duration, opts ...Option) *Sessions

NewSessions wires a user store to a signer and the two token lifetimes.

func (*Sessions) Authenticate added in v0.4.0

func (s *Sessions) Authenticate(r *http.Request) (Identity, bool)

Authenticate validates the request's access credential and returns the caller's identity. It applies neither the origin rule nor the password-change gate, so it suits read-only endpoints that resolve their own caller (GET /api/auth/me).

func (*Sessions) Handler added in v0.4.0

func (s *Sessions) Handler() http.Handler

Handler serves the session endpoints. Mount it at "/api/auth/", outside the authenticating middleware — a client with no session must be able to reach login, and Go's ServeMux prefers the longer pattern, so "/api/auth/login" lands here while "/api/overview" stays gated.

func (*Sessions) Locked added in v0.4.0

func (s *Sessions) Locked() bool

Locked reports the fail-closed state: no enabled users, or the store could not say (an error never opens the console).

func (*Sessions) Middleware added in v0.4.0

func (s *Sessions) Middleware(h http.Handler) http.Handler

Middleware gates a handler on a valid access token.

  • Locked (no enabled users): 503, handler never runs.
  • Missing/invalid/expired token, or a token whose user is gone, disabled or at a newer token version: 401. No WWW-Authenticate header — a Basic challenge would make the browser cover the console's own login screen.
  • Cookie-authenticated state change from another origin: 403.
  • User must change their password first: 403 password_change_required.
  • Valid: Identity into the request context (see IdentityFromContext), with a re-validator for long-lived handlers (see Recheck).

type Signer added in v0.4.0

type Signer struct {
	// contains filtered or unexported fields
}

Signer issues and verifies HS256 tokens against one secret.

func NewSigner added in v0.4.0

func NewSigner(secret []byte) (*Signer, error)

NewSigner returns a Signer over secret, which must be at least MinSecretLen bytes. The secret is copied, so the caller may reuse its buffer.

func (*Signer) Issue added in v0.4.0

func (s *Signer) Issue(username string, ver int64, typ string, ttl time.Duration) (string, error)

Issue returns a signed token for username at token version ver, with the given type and lifetime.

func (*Signer) Verify added in v0.4.0

func (s *Signer) Verify(token, wantType string) (Claims, error)

Verify checks a token's signature, algorithm, type and expiry, and returns its claims. wantType is TypeAccess or TypeRefresh.

type UserStore added in v0.6.0

type UserStore interface {
	Get(username string) (users.User, error)
	HasEnabledUsers() (bool, error)
	TouchLogin(username string, at time.Time) error
	SetPassword(username, hash string, mustChange bool) error
}

UserStore is the slice of the users store that sessions need. *users.Store satisfies it. Get is case-insensitive and returns the stored username.

Jump to

Keyboard shortcuts

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