admin

package
v0.0.0-...-6ebc918 Latest Latest
Warning

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

Go to latest
Published: Oct 3, 2026 License: Apache-2.0 Imports: 20 Imported by: ? modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Overview

Package admin provides authentication and a router skeleton for an operator-facing HTTP API, separate from the auth package's end-user sessions. It does not import auth: the two packages sit at the same layer (see the repository's ARCHITECTURE.md) and each is usable without the other.

Sessions

Service issues short-lived JWT sessions (12 hours by default) for admin accounts stored behind AdminStore. MemoryAdminStore is a complete in-memory implementation for tests; admin/pg provides a Postgres-backed one, along with the migrations it needs.

The session lifetime model is absolute only: a token is valid until its exp (iat plus Options.TokenTTL) and no activity extends it. There is no idle timeout, because these tokens carry no activity record to measure idleness against — validation checks signature and expiry, plus the epoch below. End-user sessions under auth's SessionOpaque can enforce both windows (see auth.SessionLimits); an admin deployment that needs idle control must keep TokenTTL short and require re-login. Every refresh issues a full new ttl, so Refresh is not a bounded extension.

Every token carries the admin's session epoch at issue time, and Service.RequireAdmin compares it against the admin's current Admin.SessionEpoch. AdminStore.RevokeSessions moves the stored epoch forward, ending every session belonging to that admin at once: the users list page exposes it as a per-admin revoke button. Tokens minted before epochs existed carry no epoch claim and do not validate.

Options.Secret must be at least 16 bytes, and must be a DIFFERENT secret from whatever auth.Options.Secret this deployment's end-user sessions use. Every token this package issues carries an "aud" claim ("keel:admin") that the sibling auth package's tokens do not share ("keel:auth"), so a token cannot validate against the wrong package even if the two secrets are reused by mistake — but two independent secrets is what actually keeps a compromise of one credential from reaching the other's sessions.

Router

Service.Router returns a chi.Router mounting POST /login (rate-limited via keel's httpx/middleware, with Options.RealIP configuring which forwarding headers it trusts) and, behind Service.RequireAdmin, POST /refresh. It applies its own CORS policy (Options.CORSOrigin), independent of any CORS policy the rest of an API uses, because an admin console is typically served from a different origin than the public API. A caller adds its own operator-only routes to the returned router, protected by the same Service.RequireAdmin middleware.

Audit trail

Service.Audit is middleware that appends one AuditEntry per request — actor, action, target, timestamp, and outcome — to the store in Options.Audit (in-memory by default, Postgres-backed via admin/pg). Mount it inside Service.RequireAdmin on every operator-only route, and review the trail through GET /audit, served by Service.AuditList, narrowed by the action, actor and outcome query parameters.

Browser UI

Service.MountUI serves the operator console in the same style as the example apps' templates: Go html/templates plus htmx, no build step. Pages are the login form, the users list with per-admin session revoke, and the audit trail with its filter; the host app serves htmx itself (see the examples' MountStatic for the conventional path). Form logins run through the same rate-limited Login as the JSON API, and every page except the login form requires a valid admin session — anonymous loads leave for the login page, and admin-only data never renders without one.

Protecting fields that must not reach a public response

CheckNoForbiddenFields inspects an encoded JSON response for a set of key names and reports an error if any are present. It is meant to run inside a test for every public-facing response type in a service that also has an admin-only view of the same data (for example, an internal note or a cost field visible only through this package's routes) — the test fails if a public handler's response ever starts including that field, whether because of a shared struct, a forgotten `json:"-"` tag, or an embedding change.

Seeding an initial account

Seed creates the first admin account against an AdminStore, hashing its password. admin/cmd/seed is a runnable command built on it and admin/pg: it reads the password from ADMIN_SEED_PASSWORD or stdin, never a command-line argument, and refuses to run against a non-empty admin_users table unless passed -force.

Index

Constants

View Source
const (
	AuditOutcomeOK    = "ok"
	AuditOutcomeError = "error"
)

Outcomes recorded on an AuditEntry: "ok" when the audited handler answered with a status below 400, "error" otherwise.

View Source
const (
	DefaultLoginRateLimitRequests = 5
	DefaultLoginRateLimitWindow   = time.Minute
)

DefaultLoginRateLimitRequests and DefaultLoginRateLimitWindow bound how often a single client IP may call POST /login, applied whenever Options.LoginRateLimit leaves Requests or Window at zero. Tighter than a typical end-user login (see auth's DefaultRateLimitRequests): a guessed admin password exposes everything an admin console can see.

View Source
const AdminSessionCookieName = "keel_admin_session"

AdminSessionCookieName carries the admin session token for the browser UI. The JSON API keeps answering bearer tokens; the cookie is the same token in a jar the browser sends on its own, so pages and fragments work from a plain link.

View Source
const DefaultTokenTTL = 12 * time.Hour

DefaultTokenTTL is how long an issued admin session token is valid. Short by default: an admin token is privileged, and expiry is its main lifetime control — revocation ends sessions explicitly (see RevokeSessions), but the console still re-authenticates often rather than carrying a long-lived credential.

Variables

View Source
var ErrAdminNotFound = errors.New("admin: admin not found")

ErrAdminNotFound is returned by an AdminStore when no admin matches the lookup.

View Source
var ErrDuplicateEmail = errors.New("admin: email already registered")

ErrDuplicateEmail is returned by AdminStore.Create when the email is already registered.

View Source
var ErrInvalidToken = errors.New("admin: invalid token")

ErrInvalidToken covers every way a bearer token can fail to validate: bad signature, wrong algorithm, wrong audience, missing or malformed claims, expiry. A caller does not need to know which check failed, and the HTTP response for each is the same 401 regardless.

Functions

func AdminIDFromContext

func AdminIDFromContext(ctx context.Context) string

AdminIDFromContext returns the authenticated admin ID, or "" if none is present.

func CheckNoForbiddenFields

func CheckNoForbiddenFields(body []byte, forbidden ...string) error

CheckNoForbiddenFields decodes body as JSON and reports an error naming the first key in forbidden it finds, at any depth (an object key or, for an array of objects, a key in any element). It reports nil for keys it cannot find and for JSON it cannot parse as an object or array.

This exists to test a boundary that a type system alone does not enforce: a public response type built by embedding, composing, or copying an admin-only type can pick up an admin-only field through no change visible at its own call site. Running this check against a public handler's encoded response, in that handler's own test, catches the field arriving however it arrived — a shared struct, a missing json:"-" tag, a change to an embedded type — rather than only catching the specific mistake someone anticipated.

func Seed

func Seed(ctx context.Context, store AdminStore, email, password, name, role string) (id string, err error)

Seed creates an initial admin account with a hashed password and returns its ID. It returns ErrDuplicateEmail if the email is already registered.

Seed is the function a one-off command or an application's own bootstrap path calls; it does not read flags, environment variables, or a database connection string itself. See admin/cmd/seed for a runnable command built on it.

Types

type Admin

type Admin struct {
	ID           string
	Email        string
	Name         string
	Role         string
	PasswordHash string
	// SessionEpoch counts how many times this admin's sessions were revoked.
	// Every issued token carries the epoch it was born in, and a token whose
	// epoch is older than this field no longer validates. It never leaves the
	// server: the users list renders a view without it, and it has no JSON
	// name.
	SessionEpoch int64 `json:"-"`
	LastLoginAt  time.Time
	CreatedAt    time.Time
}

Admin is an operator account.

type AdminStore

type AdminStore interface {
	// GetByEmail returns ErrAdminNotFound when no admin matches.
	GetByEmail(ctx context.Context, email string) (*Admin, error)
	// GetByID returns ErrAdminNotFound when no admin matches.
	GetByID(ctx context.Context, id string) (*Admin, error)
	// Create inserts a new admin and sets its ID. It returns
	// ErrDuplicateEmail when the email is already registered.
	Create(ctx context.Context, a *Admin) error
	// UpdateLastLogin records the current time as the admin's most recent
	// login. A failure here must not block the login it is recording (see
	// Service.Login); it is logged instead.
	UpdateLastLogin(ctx context.Context, id string) error
	// List returns every admin, ordered by email. The users list page reads
	// through it; it renders a view without PasswordHash or SessionEpoch.
	List(ctx context.Context) ([]Admin, error)
	// RevokeSessions ends every session belonging to id, right now, by
	// moving its SessionEpoch forward: tokens issued before the bump carry
	// an older epoch and stop validating. It returns ErrAdminNotFound when
	// no admin matches.
	RevokeSessions(ctx context.Context, id string) error
}

AdminStore is the storage interface this package depends on.

type AuditEntry

type AuditEntry struct {
	ID        int64     `json:"id"`
	Actor     string    `json:"actor"`
	Action    string    `json:"action"`
	Target    string    `json:"target"`
	Outcome   string    `json:"outcome"`
	CreatedAt time.Time `json:"created_at"`
}

AuditEntry is one row of the admin audit trail: who did what to which target, when, and how it turned out.

type AuditFilter

type AuditFilter struct {
	Action  string
	Actor   string
	Outcome string
}

AuditFilter narrows an audit listing: every non-empty field must match exactly. Empty means unfiltered.

type AuditListResponse

type AuditListResponse struct {
	Entries []AuditEntry `json:"entries"`
}

AuditListResponse is the body of GET /audit.

type AuditStore

type AuditStore interface {
	// Append records one entry, setting its ID and CreatedAt.
	Append(ctx context.Context, e *AuditEntry) error
	// List returns entries oldest first, narrowed by filter and paged by
	// limit and offset.
	List(ctx context.Context, filter AuditFilter, limit, offset int) ([]AuditEntry, error)
}

AuditStore is the storage interface for the audit trail. It is append-only by construction: there is deliberately no update or delete, so the trail is a record of what happened, not a mutable table. MemoryAuditStore is a complete in-memory implementation for tests; admin/pg provides a Postgres-backed one.

type ForbiddenFieldError

type ForbiddenFieldError struct {
	Key string
}

ForbiddenFieldError names the key CheckNoForbiddenFields found.

func (*ForbiddenFieldError) Error

func (e *ForbiddenFieldError) Error() string

type LoginRequest

type LoginRequest struct {
	Email    string `json:"email"`
	Password string `json:"password"`
}

LoginRequest is the body of POST /login.

type MemoryAdminStore

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

MemoryAdminStore is an in-memory AdminStore, safe for concurrent use.

func NewMemoryAdminStore

func NewMemoryAdminStore() *MemoryAdminStore

NewMemoryAdminStore returns an empty MemoryAdminStore.

func (*MemoryAdminStore) Create

func (s *MemoryAdminStore) Create(_ context.Context, a *Admin) error

Create implements AdminStore.

func (*MemoryAdminStore) GetByEmail

func (s *MemoryAdminStore) GetByEmail(_ context.Context, email string) (*Admin, error)

GetByEmail implements AdminStore.

func (*MemoryAdminStore) GetByID

func (s *MemoryAdminStore) GetByID(_ context.Context, id string) (*Admin, error)

GetByID implements AdminStore.

func (*MemoryAdminStore) List

func (s *MemoryAdminStore) List(_ context.Context) ([]Admin, error)

List implements AdminStore, ordered by email so the users list is stable.

func (*MemoryAdminStore) RevokeSessions

func (s *MemoryAdminStore) RevokeSessions(_ context.Context, id string) error

RevokeSessions implements AdminStore.

func (*MemoryAdminStore) UpdateLastLogin

func (s *MemoryAdminStore) UpdateLastLogin(_ context.Context, id string) error

UpdateLastLogin implements AdminStore.

type MemoryAuditStore

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

MemoryAuditStore is an in-memory AuditStore, safe for concurrent use.

func NewMemoryAuditStore

func NewMemoryAuditStore() *MemoryAuditStore

NewMemoryAuditStore returns an empty MemoryAuditStore.

func (*MemoryAuditStore) Append

func (s *MemoryAuditStore) Append(_ context.Context, e *AuditEntry) error

Append implements AuditStore.

func (*MemoryAuditStore) List

func (s *MemoryAuditStore) List(_ context.Context, filter AuditFilter, limit, offset int) ([]AuditEntry, error)

List implements AuditStore.

type Options

type Options struct {
	// Users is required.
	Users AdminStore
	// Secret signs and verifies session tokens. Required, and must be at
	// least minSecretLength bytes.
	Secret string
	// TokenTTL is how long an issued session token is valid. Defaults to
	// DefaultTokenTTL. It is the token's absolute lifetime — exp is always
	// iat plus this duration, and no activity extends it. There is no idle
	// timeout: admin sessions are stateless JWTs with no activity record to
	// measure idleness against. Keep this short (the 12-hour default is
	// already generous for a privileged console) and require re-login rather
	// than relying on Refresh to carry a session indefinitely; every refresh
	// issues a full new ttl.
	TokenTTL time.Duration
	// CORSOrigin is the single origin Router's CORS policy allows, typically
	// the admin console's own origin. Required to allow any cross-origin
	// request; if empty, Router applies no CORS headers at all, which is
	// correct only when the admin console is served from the same origin as
	// this API.
	CORSOrigin string
	// RealIP configures client-address recovery for the login rate limiter.
	// Its zero value ignores forwarding headers, which is correct only when
	// this Router is reachable directly; behind a proxy, set TrustedProxies
	// (or TrustAnyPeer on a platform where nothing else can reach the
	// process) or every client shares one rate-limit bucket.
	RealIP middleware.RealIPOptions
	// LoginRateLimit bounds requests per client IP to POST /login.
	LoginRateLimit middleware.RateLimitOptions
	// Audit is the append-only store the Audit middleware writes to and the
	// AuditList handler reads from. When nil, NewService uses an in-memory
	// store: fine for tests, but a deployment that needs the trail to
	// survive a restart passes the Postgres-backed store from admin/pg.
	Audit AuditStore
	// Logger receives this package's diagnostic output. Defaults to
	// slog.Default(); never overridden globally by this package.
	Logger *slog.Logger
}

Options configures a Service. Users and Secret are required; every other field has a documented default.

Secret MUST be different from whatever secret an auth.Service in the same deployment uses — see auth.Options's doc comment on why a shared secret is a configuration mistake this package's audience check defends against, but two independent secrets is what actually keeps a compromise of one credential from reaching the other's sessions. The app package's CheckSecretSeparation enforces this at startup for deployments that mount both services.

type Service

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

Service holds the wiring for the admin HTTP routes: sessions and password checks. Build one with NewService and mount its Router.

func NewService

func NewService(opts Options) (*Service, error)

NewService validates Options and builds a Service.

func (*Service) Audit

func (s *Service) Audit(action string, target func(*http.Request) string) func(http.Handler) http.Handler

Audit returns middleware that appends one AuditEntry per request to this Service's AuditStore. Mount it inside RequireAdmin so AdminIDFromContext carries the actor:

r.Group(func(r chi.Router) {
    r.Use(svc.RequireAdmin)
    r.Use(svc.Audit("user.disable", func(r *http.Request) string {
        return r.URL.Query().Get("id")
    }))
    r.Post("/users/disable", disableHandler)
})

action names the privileged operation in the caller's own vocabulary; a nil target records the request path instead. The outcome is "ok" when the handler answers below 400 and "error" otherwise. A failing audit write never fails the admin action it records — it is logged instead, the way Login treats its own bookkeeping write.

func (*Service) AuditList

func (s *Service) AuditList(w http.ResponseWriter, r *http.Request)

AuditList serves GET /audit: the audit trail oldest first, narrowed by the action, actor and outcome query parameters and paged by the limit (default 50, capped at 200) and offset query parameters.

func (*Service) Login

func (s *Service) Login(w http.ResponseWriter, r *http.Request)

Login handles POST /login.

func (*Service) MountUI

func (s *Service) MountUI(r chi.Router, basePath string)

MountUI mounts the browser UI under basePath: the login page, the users list with per-admin session revoke, and the filterable audit trail. A nil or empty basePath mounts at "/".

The pages are plain forms that work without script; with htmx served by the host app at /static/vendor/htmx.min.js (the same path the examples' MountStatic serves), the revoke button and the audit filter swap fragments instead of reloading. Every page requires a valid admin session except /login, and no admin-only data renders without one: anonymous page loads leave for the login page, anonymous fragments keep the JSON API's 401.

func (*Service) Refresh

func (s *Service) Refresh(w http.ResponseWriter, r *http.Request)

Refresh handles POST /refresh (requires RequireAdmin).

func (*Service) RequireAdmin

func (s *Service) RequireAdmin(next http.Handler) http.Handler

RequireAdmin is middleware that requires a valid admin bearer session token. It answers a generic 401 for anything wrong with the header, the token, or the admin it names: an unknown admin, a token revoked since it was issued, and a store failure all read the same from outside, so a revoked credential is indistinguishable from a forged one.

func (*Service) Router

func (s *Service) Router() chi.Router

Router returns a chi.Router with:

POST /login     (rate-limited)
POST /refresh   (requires RequireAdmin)
GET  /audit     (requires RequireAdmin; the audit trail, oldest first,
                 narrowed by the action, actor and outcome query parameters)

and this Service's CORS policy applied to every route, including ones a caller adds afterward. A caller mounts its own operator-only routes on the returned router, protecting them with RequireAdmin the same way /refresh is protected:

r := adminService.Router()
r.Group(func(r chi.Router) {
    r.Use(adminService.RequireAdmin)
    r.Get("/listings", listingsHandler)
})

type SessionResponse

type SessionResponse struct {
	Token string `json:"token"`
	Admin struct {
		ID    string `json:"id"`
		Email string `json:"email"`
		Name  string `json:"name"`
		Role  string `json:"role"`
	} `json:"admin"`
}

SessionResponse is returned by Login and Refresh.

Directories

Path Synopsis
cmd
seed command
Command seed creates the first admin account, using admin.Seed against a Postgres-backed admin.AdminStore (admin/pg).
Command seed creates the first admin account, using admin.Seed against a Postgres-backed admin.AdminStore (admin/pg).
Package pg is a Postgres-backed implementation of admin.AdminStore.
Package pg is a Postgres-backed implementation of admin.AdminStore.

Jump to

Keyboard shortcuts

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