authadmin

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Dec 6, 2026 License: Apache-2.0 Imports: 18 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.

README

authadmin

Package authadmin is an HTTP API for an application's administrators, human or agent: users with their sessions and delegation trees, agents, revocation, the audit log, and alerts.

The package documentation is in authadmin.go. To read it with the API, run go doc ./authadmin.

Contents

Name What it holds
authadmin.go New, the Authorizer that decides who is an administrator, options, and the package documentation
handlers.go The route table and the handler of each route
json.go The JSON shapes of the API, which match the schemas in openapi.json
alerts.go AlertPolicy, which tunes the alerts that GET /v1/alerts derives from the audit log, and AlertSource, which adds alerts from other state
chain.go WithChainCheck, which sets how often GET /v1/audit/chain verifies the hash chain
directory.go Directory and Profile, for showing the application's own user profiles
openapi.json The OpenAPI document of the API, served by the handler
openapi.go OpenAPI, which returns the document for servers that merge it into their own

The tests are in the *_test.go files next to the code.

See also

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

Examples

Constants

View Source
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.

View Source
const ActionUpdateSignupSettings = "admin.update_signup_settings"

ActionUpdateSignupSettings is the limiter action for changing the signup override.

View Source
const (
	DefaultChainCheckEvery = 5 * time.Minute
)

Defaults for WithChainCheck.

View Source
const (
	DefaultFreshness = 10 * time.Minute
)

Defaults for WithFreshness and paging.

View Source
const ReasonNotAdmin auth.Reason = "not_admin"

ReasonNotAdmin is recorded with access_denied events for requests that the Authorizer refuses.

Variables

View Source
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

func New(svc *auth.Service, authorize Authorizer, opts ...Option) (http.Handler, error)

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

type AlertSource func(ctx context.Context, since, now time.Time) ([]Alert, error)

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

type Authorizer func(r *http.Request, p auth.Principal) error

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"
	CodeUnavailable          Code = "unavailable"
	CodeVersionConflict      Code = "version_conflict"
	CodePreconditionRequired Code = "precondition_required"
)

Error codes.

type Directory

type Directory func(ctx context.Context, users []auth.UserID) (map[auth.UserID]Profile, error)

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

type Error struct {
	Status  int
	Code    Code
	Message string
}

Error is an error response: an HTTP status, a code, and a message that tells the reader how to fix the request.

func (*Error) Error

func (e *Error) Error() string

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

func WithDirectory(d Directory) Option

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

func WithFreshness(d time.Duration) Option

WithFreshness sets how recently a human must have authenticated to make changes. The default is DefaultFreshness.

func WithLogger

func WithLogger(l *slog.Logger) Option

WithLogger logs server errors, such as a store outage. The default discards logs.

func WithRoutes

func WithRoutes(routes ...Route) Option

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.

Jump to

Keyboard shortcuts

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