auth

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Sep 28, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package auth provides JWT session authentication for the admin console and API. Credentials are a set of username + bcrypt password-hash pairs loaded from config and the JOEI_CONSOLE_AUTH_USERS environment variable; a successful POST /api/auth/login exchanges them 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. The /api/auth/* endpoints (login, refresh, logout, me) and the session-verifying middleware live alongside the credential set in this package. With no users configured the set 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 (
	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 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.

Types

type Claims added in v0.4.0

type Claims struct {
	Sub string `json:"sub"` // username
	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 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). The credential set it verifies against is the same bcrypt Users as before.

func NewSessions added in v0.4.0

func NewSessions(users *Users, signer *Signer, accessTTL, refreshTTL time.Duration) *Sessions

NewSessions wires a credential set to a signer and the two token lifetimes.

func (*Sessions) Authenticate added in v0.4.0

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

Authenticate validates the request's access credential and returns the username. It applies no origin rule, 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 users configured.

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 users configured): 503, handler never runs.
  • Missing/invalid/expired token, or a token for a user who no longer exists: 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.
  • Valid: username into the request context (see UserFromContext).

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, typ string, ttl time.Duration) (string, error)

Issue returns a signed token for username 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 User

type User struct {
	Username     string
	PasswordHash string
}

User is one credential: a username and its bcrypt password hash.

type Users

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

Users is a validated set of credentials. An empty set is the locked state.

func NewUsers

func NewUsers(fileUsers []User, envValue string) (*Users, error)

NewUsers builds the credential set from config-file users and the semicolon-separated JOEI_CONSOLE_AUTH_USERS env value ("username:hash;username:hash"). Whitespace around entries is trimmed. Env entries override file entries with the same username. Every username must be non-empty and every hash must be a valid bcrypt hash, else an error is returned. An empty result is valid and yields the locked state.

func (*Users) Known added in v0.4.0

func (u *Users) Known(username string) bool

Known reports whether username is configured. A token stays cryptographically valid after its user is removed from the config, so every request re-checks the subject against the current set.

func (*Users) Locked

func (u *Users) Locked() bool

Locked reports whether no users are configured (fail-closed state).

func (*Users) Verify

func (u *Users) Verify(username, password string) bool

Verify reports whether username/password match a configured user. For an unknown username it still performs a bcrypt comparison against a dummy hash so timing does not reveal which usernames exist. It is safe to call on a locked (empty) set — it simply returns false.

Jump to

Keyboard shortcuts

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