Documentation
¶
Overview ¶
Package authadmin is an HTTP API for an application's administrators, human or agent. It lists users with their sessions and delegation trees, lists agents, revokes sessions, users, and agents, pages through the audit log, and derives alerts from it.
Mount the handler behind [authhttp.Middleware], which authenticates the request, and supply an Authorizer that decides who is an administrator:
admin, err := authadmin.New(svc, func(r *http.Request, p auth.Principal) error {
if !isAdmin(r.Context(), p.User) {
return authadmin.ErrNotAdmin
}
return nil
})
mux.Handle("/admin/", authhttp.Middleware(svc)(http.StripPrefix("/admin", admin)))
Every request needs a principal that the Authorizer accepts. Requests that change something also need a human who authenticated within the freshness window (see WithFreshness), pass the service's auth.Limiter, and record the administrator as the auth.Actor of the change, in the same transaction as the change. Agents are never fresh, so they can read but not change.
Routes are versioned under /v1, and /v1/openapi.json serves an OpenAPI 3.1 document that describes them. Responses never contain tokens or token hashes.
Index ¶
- Constants
- Variables
- func New(svc *auth.Service, authorize Authorizer, opts ...Option) (http.Handler, error)
- func OpenAPI() []byte
- func WriteError(w http.ResponseWriter, e *Error) error
- func WriteJSON(w http.ResponseWriter, status int, v any) error
- type Alert
- type AlertPolicy
- type AlertSource
- type Authorizer
- type Code
- type Directory
- type Error
- type Option
- func WithAlertPolicy(p AlertPolicy) Option
- func WithAlertSource(source AlertSource) Option
- func WithChainCheck(every time.Duration, ...) Option
- func WithDirectory(d Directory) Option
- func WithFreshness(d time.Duration) Option
- func WithLogger(l *slog.Logger) Option
- func WithRoutes(routes ...Route) Option
- type Profile
- type Route
Examples ¶
Constants ¶
const ( ActionRevokeSession = "admin.revoke_session" ActionRevokeUser = "admin.revoke_user" ActionRevokeAgent = "admin.revoke_agent" )
Actions recorded for the routes that change something, and passed to the limiter.
const ActionUpdateSignupSettings = "admin.update_signup_settings"
ActionUpdateSignupSettings is the limiter action for changing the signup override.
const (
DefaultChainCheckEvery = 5 * time.Minute
)
Defaults for WithChainCheck.
const (
DefaultFreshness = 10 * time.Minute
)
Defaults for WithFreshness and paging.
const ReasonNotAdmin auth.Reason = "not_admin"
ReasonNotAdmin is recorded with access_denied events for requests that the Authorizer refuses.
Variables ¶
var ErrNotAdmin = &Error{ Status: http.StatusForbidden, Code: CodeForbidden, Message: "This principal isn't an administrator of this application. Ask an administrator for access.", }
ErrNotAdmin is the error an Authorizer returns to refuse a principal.
Functions ¶
func New ¶
New returns the admin API for svc. authorize is required.
Example ¶
package main
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
auth "tensile.tools/auth"
"tensile.tools/auth/authadmin"
"tensile.tools/auth/authhttp"
"tensile.tools/auth/memstore"
)
func main() {
svc, err := auth.New(memstore.New())
if err != nil {
panic(err)
}
admins := map[auth.UserID]bool{"alice": true}
admin, err := authadmin.New(svc, func(_ *http.Request, p auth.Principal) error {
if !admins[p.User] {
return authadmin.ErrNotAdmin
}
return nil
})
if err != nil {
panic(err)
}
mux := http.NewServeMux()
mux.Handle("/admin/", authhttp.Middleware(svc)(http.StripPrefix("/admin", admin)))
ctx := context.Background()
tok, _, err := svc.StartSession(ctx, "alice", auth.StartOptions{})
if err != nil {
panic(err)
}
req := httptest.NewRequestWithContext(ctx, http.MethodGet, "/admin/v1/users/alice", http.NoBody)
req.Header.Set("Authorization", "Bearer "+tok.Reveal())
rec := httptest.NewRecorder()
mux.ServeHTTP(rec, req)
fmt.Println(rec.Code, rec.Body.String()[:40])
}
Output: 200 {"user":{"id":"alice","live_sessions":1,
func OpenAPI ¶
func OpenAPI() []byte
OpenAPI returns the OpenAPI 3.1 document of the routes New serves, with paths relative to where the handler is mounted. The tensile-auth server merges it, under /admin, into the document it publishes.
func WriteError ¶
func WriteError(w http.ResponseWriter, e *Error) error
WriteError writes e as an error response. Routes added with WithRoutes use it to answer in the same format.
func WriteJSON ¶
func WriteJSON(w http.ResponseWriter, status int, v any) error
WriteJSON writes v as a JSON response with the given status. Routes added with WithRoutes use it to answer in the same format. It returns the error from writing the body, when the client has gone.
Types ¶
type Alert ¶
type Alert struct {
// Kind names the alert, in lowercase letters, digits, and
// underscores, for example "webhook_late".
Kind string
// Severity is "high", "medium", or "low".
Severity string
// Message says what happened and what to do, in one or two sentences.
Message string
// Key tells apart alerts of one kind that start at the same time. It
// can be empty.
Key string
// Count is how many occurrences the alert stands for; 0 counts as 1.
Count int
// FirstAt and LastAt bound the alert. FirstAt is required; the alert's
// id derives from Kind, Key, and FirstAt, so it stays the same while
// the condition lasts. A zero LastAt is FirstAt.
FirstAt, LastAt time.Time
}
Alert is an alert that an AlertSource raises.
type AlertPolicy ¶
type AlertPolicy struct {
// Window is how far back the scan reaches when the request doesn't
// set since.
Window time.Duration
// MaxWindow is the furthest back a request may set since.
MaxWindow time.Duration
// BurstWindow and BurstThreshold define a burst of failures: at least
// BurstThreshold failed attempts from one client, or against one user,
// within BurstWindow.
BurstWindow time.Duration
BurstThreshold int
// MaxScan is the most events one request reads. A scan that stops
// early says so with "truncated": true.
MaxScan int
// SignupWindow and SignupThreshold define a signup spike: at least
// SignupThreshold agents registering themselves within SignupWindow,
// from every client together. The limiter already caps each client.
SignupWindow time.Duration
SignupThreshold int
// ExpiryWarning is how long before its claim deadline an unclaimed
// agent is reported as close to expiry.
ExpiryWarning time.Duration
// MaxAgents is the most unclaimed agents one request reads.
MaxAgents int
}
AlertPolicy tunes the alerts that GET /v1/alerts derives from the audit log.
func DefaultAlertPolicy ¶
func DefaultAlertPolicy() AlertPolicy
DefaultAlertPolicy scans the last 24 hours by default and at most 30 days, flags 20 failures within 5 minutes as a burst and 50 signups within 10 minutes as a spike, reports unclaimed agents within 24 hours of their claim deadline, and reads at most 10,000 events and 10,000 unclaimed agents.
type AlertSource ¶
AlertSource returns alerts from state outside the audit log. GET /v1/alerts calls it on every request with the start of the scan and the service's time, and adds what it returns to the alerts it derives. An error fails the request with 503 unavailable.
type Authorizer ¶
Authorizer decides whether p may use the admin API. It runs on every request. Return nil to allow it, ErrNotAdmin (or an error that wraps it) to refuse it with 403, or an *Error to send that response instead. Any other error is treated as an outage: the client gets 503, and the error is logged.
type Code ¶
type Code string
Code is a machine-readable error code. The set of codes is fixed within /v1.
const ( CodeInvalidRequest Code = "invalid_request" CodeInvalidCursor Code = "invalid_cursor" CodeUnauthenticated Code = "unauthenticated" CodeForbidden Code = "forbidden" // CodeStepUpRequired means a change came from a session that didn't // authenticate recently enough. CodeStepUpRequired Code = "step_up_required" // CodeStrongerFactorRequired means a change came from a session whose // factors are too weak, such as a recovery code alone. CodeStrongerFactorRequired Code = "stronger_factor_required" // CodeHumanRequired means a change came from an agent or a token. CodeHumanRequired Code = "human_required" CodeNotFound Code = "not_found" CodeMethodNotAllowed Code = "method_not_allowed" CodeThrottled Code = "throttled" CodeVersionConflict Code = "version_conflict" CodePreconditionRequired Code = "precondition_required" )
Error codes.
type Directory ¶
Directory returns the profiles of users, keyed by user ID. It may leave out users it doesn't know. The admin API calls it with at most one page of users at a time.
type Error ¶
Error is an error response: an HTTP status, a code, and a message that tells the reader how to fix the request.
type Option ¶
type Option func(*config)
Option configures New.
func WithAlertPolicy ¶
func WithAlertPolicy(p AlertPolicy) Option
WithAlertPolicy replaces DefaultAlertPolicy.
func WithAlertSource ¶
func WithAlertSource(source AlertSource) Option
WithAlertSource adds the alerts that source raises to GET /v1/alerts, for state that the audit log doesn't hold, such as a webhook that has failed for 15 minutes. See AlertSource.
func WithChainCheck ¶
func WithChainCheck(every time.Duration, checkpoints func(context.Context) ([]auth.ChainHead, error)) Option
WithChainCheck sets how often GET /v1/audit/chain verifies the whole audit chain, and the trusted checkpoints to verify it against. The route answers from the last check and starts a new one in the background when the last is older than every, so reading the status never waits for a full verification after the first. checkpoints may be nil; otherwise it returns the heads of the checkpoints you trust, read from where you store them. The default checks every DefaultChainCheckEvery with no checkpoints.
func WithDirectory ¶
WithDirectory adds the application's profiles to users in responses: the user list, a user's summary, and the caller's own session. When the directory fails, responses leave profiles out and the error is logged, so an outage of the directory never hides sessions or agents.
func WithFreshness ¶
WithFreshness sets how recently a human must have authenticated to make changes. The default is DefaultFreshness.
func WithLogger ¶
WithLogger logs server errors, such as a store outage. The default discards logs.
func WithRoutes ¶
WithRoutes adds routes, for example settings that another package owns.
type Profile ¶
type Profile struct {
// Name is the name to show, for example a display name or an email
// address.
Name string
// Email is the user's email address, if the application has one.
Email string
// Admin reports whether the application treats the user as an
// administrator.
Admin bool
// Disabled reports whether the application has disabled the account.
Disabled bool
}
Profile is what the application's user directory says about a user. The library owns no accounts, so it shows profiles only when the application passes a Directory.
type Route ¶
type Route struct {
// Method is the HTTP method, for example http.MethodPost.
Method string
// Path is the path under /v1/, with ServeMux wildcards, for example
// "/v1/agents/{agent}/claim".
Path string
// Action names the route for the limiter and the audit log, for
// example "admin.claim_agent".
Action string
// Changes marks a route that changes something. It then needs a fresh
// human session, passes the limiter, and runs with [auth.WithActor].
Changes bool
// Handler serves the request. [auth.FromContext] returns the
// administrator.
Handler http.Handler
}
Route is a route that WithRoutes adds to the API. It passes the same checks as the built-in routes.