Documentation
¶
Overview ¶
Package server starts Hoplock Control from a host binary (M15).
Hoplock Enterprise is a Go program that imports this module, registers its implementations of the interfaces in ext, and starts Control — and this is the package it starts it with. hoplock-control itself is one call to Main with zero Options, so there is one start-up path and not two that drift.
A host gets four things, and nothing else:
- Control's whole command line — the daemon and every subcommand — through Main, so an Enterprise binary can migrate, seed and verify without Control's binary beside it.
- Top-level sections of its own in Control's configuration file (Options.HostSections), handed to it undecoded.
- North-bound routes of its own (Options.Routes), behind Control's authentication, tenant resolution and RBAC, on the north-bound listener and nowhere else (M2, M18): tenant routes, and cross-tenant reads whose set of tenants Control resolves (AccessCrossTenant, M24).
- Control's error envelope (WriteError), with codes it declares (M21).
THIS PACKAGE IS A COMPATIBILITY PROMISE, exactly as ext is: every exported identifier here is something a host builds against, and changing one breaks its build. It is a thin façade — the public types, and forwarding into Control's internals, where every check a host can fail lives.
Example ¶
A host binary's main: register an extension, declare a configuration section and a route of each class, and start Control. A real host calls server.Main instead of server.Run, so that its binary carries Control's subcommands too.
package main
import (
"context"
"encoding/json"
"fmt"
"net/http"
"os"
"os/signal"
"slices"
"gopkg.in/yaml.v3"
"github.com/hoplock/control/ext"
"github.com/hoplock/control/server"
)
// archive is a host's extension: a long-term archive Control does not ship
// (ext.ArchiveStore is disabled when nothing registers one).
type archive struct{ retention string }
func (a *archive) Archive(context.Context, []ext.AuditRecord) error { return nil }
func (a *archive) ArchiveCaptures(context.Context, []ext.Capture) error { return nil }
func (a *archive) Search(context.Context, ext.ArchiveQuery) (ext.ArchivePage, error) {
return ext.ArchivePage{}, nil
}
// archived is what the example's list pages: each tenant's record ids, in
// order.
var archived = map[ext.Tenant][]string{"default": {"r-001", "r-002", "r-003", "r-004", "r-005"}}
// listArchive is a host's list in Control's bounded shape (M26): at most
// ?limit= record ids after the caller's position, in id order, saying where it
// stopped. It reads the tenant from the caller on every page, because the
// cursor carries a position and never a tenant.
func listArchive(w http.ResponseWriter, r *http.Request) {
list, ok := server.ReadList(w, r, "archive", 1)
if !ok {
return // ReadList has answered
}
caller, _ := server.CallerFrom(r.Context())
ids := archived[caller.Tenant]
start := 0
if list.After != nil {
var found bool
if start, found = slices.BinarySearch(ids, list.After[0]); found {
start++
}
}
page := ids[start:min(start+list.Limit, len(ids))]
more := start+len(page) < len(ids)
var last []string
if more {
last = []string{page[len(page)-1]}
}
list.Write(w, r, "records", page, more, last, nil)
}
// A host binary's main: register an extension, declare a configuration section
// and a route of each class, and start Control. A real host calls server.Main instead of
// server.Run, so that its binary carries Control's subcommands too.
func main() {
ctx, stop := signal.NotifyContext(context.Background(), os.Interrupt)
defer stop()
store := &archive{}
registry := ext.NewRegistry()
if err := registry.RegisterArchiveStore(ext.Registration{Provider: "example/archive", Version: "v1.0.0"}, store); err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
config, err := os.Open("config.yaml")
if err != nil {
fmt.Fprintln(os.Stderr, err)
return
}
defer func() { _ = config.Close() }()
err = server.Run(ctx, config, server.Options{
Provider: "example/host",
Registry: registry,
// `example:` in Control's configuration file is this host's. It is
// handed over undecoded, before the registry is sealed.
HostSections: []string{"example"},
HostConfig: func(section string, raw []byte) error {
var cfg struct {
Retention string `yaml:"retention"`
}
if err := yaml.Unmarshal(raw, &cfg); err != nil {
return err
}
store.retention = cfg.Retention
return nil
},
Routes: []server.Route{
// GET /api/v1/hosts/example/host/tenants/{tenant}/archive?limit=&after=,
// a list:
// {"records": [...], "truncated": true, "next": "<cursor>"}.
{
Method: http.MethodGet,
Pattern: "archive",
Permission: "audit:read",
Summary: "archived records, a page at a time",
Handler: http.HandlerFunc(listArchive),
},
// GET /api/v1/hosts/example/host/tenants/{tenant}/archive/{record},
// for a caller holding audit:read in the tenant Control resolved.
{
Method: http.MethodGet,
Pattern: "archive/{record}",
Permission: "audit:read",
Summary: "one archived record",
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
caller, _ := server.CallerFrom(r.Context())
server.WriteError(w, r, http.StatusNotFound, "archive_record_not_found",
map[string]any{"record": r.PathValue("record"), "tenant": string(caller.Tenant)},
"the archive holds no such record")
}),
},
// GET /api/v1/hosts/example/host/cross-tenant/archive/summary, for a
// caller holding audit:read in each tenant it covers. Control resolves the set —
// narrowed by ?tenant=, never widened — and the answer names it.
{
Method: http.MethodGet,
Pattern: "archive/summary",
Permission: "audit:read",
Access: server.AccessCrossTenant,
Summary: "the archive, summarised across tenants",
Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
caller, _ := server.CallerFrom(r.Context())
w.Header().Set("Content-Type", "application/json")
_ = json.NewEncoder(w).Encode(map[string]any{"tenants": caller.Tenants, "records": 0})
}),
},
},
ErrorCodes: []string{"archive_record_not_found"},
})
if err != nil {
fmt.Fprintln(os.Stderr, err)
}
}
Output:
Index ¶
- Constants
- func Main(ctx context.Context, args []string, stdout, stderr io.Writer, o Options) error
- func Run(ctx context.Context, config io.Reader, o Options) error
- func WriteError(w http.ResponseWriter, r *http.Request, status int, code string, ...)
- type Access
- type Caller
- type List
- type Options
- type Route
Examples ¶
Constants ¶
const ( DefaultListLimit = 500 MaxListLimit = 10000 )
DefaultListLimit and MaxListLimit are the bounds of every north-bound list, Control's and a host's (M26).
Variables ¶
This section is empty.
Functions ¶
func Main ¶
Main is Hoplock Control's command line: the daemon and every subcommand (migrate, seed, audit-verify, audit-retention, identity, ca). hoplock-control's main is one call to it with zero Options; a host binary's main is one call to it with its own.
It returns rather than exiting, and it installs no signal handler: the caller owns its exit code and its signals, and cancelling ctx stops the daemon. A host with commands of its own dispatches them before calling Main; Control does not route to them. Every subcommand that reads the configuration accepts the host's sections. The daemon, audit-verify and audit-retention hand them to HostConfig and seal o.Registry, because those three use what a host registers: audit-verify and audit-retention check and sign retention with the host's ext.KeyStore exactly as the daemon does (0024). No other subcommand calls HostConfig.
func Run ¶
Run is the daemon alone: decode the configuration read from config, hand each host section to HostConfig, register Control's defaults into o.Registry, seal it, mount o.Routes, serve both listeners, and return when ctx is done (nil) or a listener fails (the error).
Its structured log goes to standard error, and it becomes slog's default logger, so a host's own lines share its format and level. It is exported for tests and for a host that builds its own command line; Main calls it for the daemon.
func WriteError ¶
func WriteError(w http.ResponseWriter, r *http.Request, status int, code string, params map[string]any, message string)
WriteError answers a host route's request in Control's error envelope (M21): a stable code, typed parameters, an English message, and the correlation id the request is logged under.
{"code": "report_not_found", "message": "...", "parameters": {...}, "correlation_id": "..."}
The code is the thing a client depends on, so it must be one of Control's or one the host declared in Options.ErrorCodes. The message is English for curl and logs; the console builds its own sentence from the code and parameters.
IT FAILS CLOSED. Each of these is a host programming error, answered as `500 internal` with the correlation id and logged as one:
- a call outside a host route;
- a code neither declared nor Control's;
- a status outside 4xx and 5xx;
- a 401, or the code "unauthenticated": on this surface "you are not signed in" is Control's middleware's answer alone (M11);
- the code "internal" with a status that is not 5xx: it always means an outage, never a refusal (M11);
- an empty message.
Types ¶
type Access ¶ added in v0.5.0
type Access int
Access is a host route's class: what Control resolves before Handler runs. Closed set; the zero value is AccessTenant, so a Route written before Access existed is unchanged.
const ( // AccessTenant mounts the route at // /api/v1/hosts/<Provider>/tenants/{tenant}/<Pattern>. Control resolves // exactly one tenant from the caller's scope and checks Permission in // it. Caller.Tenant is that tenant. AccessTenant Access = iota // AccessCrossTenant mounts the route at // /api/v1/hosts/<Provider>/cross-tenant/<Pattern>. // Control resolves every tenant in the caller's scope where it holds // Permission, narrowed by the request's tenant selector and never widened, // and refuses a named tenant that fails rather than dropping it. // Caller.Tenants is that set. Permission must be a read: one the auditor // role holds. Control serves no route of this class of its own (M24). AccessCrossTenant )
type Caller ¶
type Caller struct {
// Tenant is the one tenant Control resolved, from the caller's scope —
// never read from the request. Read the tenant from here and nowhere
// else: the {tenant} in the path is a selector Control has already
// checked, not a value a handler may trust on its own. It is zero on an
// AccessCrossTenant route.
Tenant ext.Tenant
// Tenants is the set Control resolved on an AccessCrossTenant route:
// sorted, never empty, each one in the caller's scope with the route's
// permission. It is nil on an AccessTenant route, where Tenant is the one.
// Read the set from here and nowhere else, and say in the response which
// tenants it covers: that is how a report says "these" rather than "some".
Tenants []ext.Tenant
// Subject is the person behind a session: ID and Groups. It is zero for
// a machine token. Username and ExternalID are always empty: Control's
// principal carries neither, and they are never guessed.
Subject ext.Subject
// Principal is the id of the credential that acted. Safe to log.
Principal string
// BreakGlass reports a credential from the local break-glass path. It
// is asserted when the credential is minted and never inferred (M7).
BreakGlass bool
// CorrelationID is the id the request is logged under (M11).
CorrelationID string
// ActingOperator is the supervising operator a supervisor's call named
// in its Hoplock-Acting-Operator header (0048), decoded. It is the
// supervisor's assertion, not Control's verification: what Control
// verified is Principal, a `sup-` id, and nothing else. It is empty
// unless Principal is a supervisor's and the call named one.
//
// A host records it as the supervisor's word, beside Principal, and
// never authorises on it, matches it, or puts it in Principal's place.
ActingOperator string
}
Caller is who Control authenticated for the request a host route is serving, or a registered report provider is answering.
It is a projection, never the principal itself: which tenants a caller may reach is Control's to know and the middleware's to check. A handler is handed what the request covers — one tenant, or on a cross-tenant read the set — and never asks, because a handler that could ask would be a handler that chose its own set, which is the missing filter M18 exists to rule out.
func CallerFrom ¶
CallerFrom returns who Control authenticated for the request ctx belongs to, in two places: inside a host route, and inside Control's own calls into a registered ext.ReportProvider — its Reports and Generate, on Control's report routes — so a pack can record who generated a report. It is for attribution, never for authorisation: Control has already resolved the tenant and checked the permission. ok is false everywhere else. WriteError still answers only inside a host route: a provider call is not one.
type List ¶ added in v0.17.0
type List struct {
// Limit is 1 to MaxListLimit; DefaultListLimit when the caller named none.
Limit int
// After is the order key of the last item the caller was handed, one
// string per component, exactly as the host passed it to Write. Nil
// starts the list. The host parses it and owns what each component means.
After []string
// contains filtered or unexported fields
}
List is one page a caller asked of a host's list: how many items it may hold, and the position it continues from.
A host's list answers as Control's lists do, so one client reads both (M26):
GET …?limit=100&after=<cursor>
{"requests": [...], "truncated": true, "next": "<cursor>"}
The host reads the request with ReadList, fetches up to Limit items after After in its list's order, plus one more to learn whether the list goes on, and answers with List.Write.
The cursor is opaque to the caller and minted by Control. It binds the list's name, the host's provider and the request's filters, so a cursor from one of Control's lists, from another of the host's or under other filters is refused rather than misread. It never carries the tenant, nor on a cross-tenant read the set of tenants (M18, M24): both are Control's middleware's, resolved from the caller on every request, and the host filters by Caller on every page. A cursor is a position, not a scope.
func ReadList ¶ added in v0.17.0
func ReadList(w http.ResponseWriter, r *http.Request, name string, keyLen int, filters ...string) (List, bool)
ReadList reads ?limit= and ?after= for one of a host's lists.
name names the list among the host's own; Control prefixes it with the host's provider, so a cursor from one of Control's lists or another host's is refused. filters are the request's own filter values as "name=value", which the cursor binds: every query parameter that changes what the list holds or its order belongs here, and nothing Control resolves — never the tenant or the set. keyLen is the number of components in the list's order key.
On a bad limit or cursor it writes Control's 400 refusal and answers false: `400 invalid_request` with `{field: limit, problem: invalid}`, `{field: limit, problem: exceeds_maximum, limit: "10000"}` above MaxListLimit — refused, never clamped — or `{field: after, problem: invalid}`. A client that is refused a cursor drops it and starts again.
IT FAILS CLOSED, as WriteError does. Outside a host route, with an empty name or with a keyLen below 1, it answers `500 internal` with the correlation id and logs it: each is a host programming error.
func (List) Write ¶ added in v0.17.0
func (l List) Write(w http.ResponseWriter, r *http.Request, member string, items any, more bool, last []string, extra map[string]any)
Write answers one page in M26's shape: {member: items, "truncated": more, "next": <cursor after last>, extra...}. last is read only when more is true. items must encode as a JSON array; nil is written as [].
more is true when the list holds an item after this page: read Limit+1 items and answer the first Limit of them. last is then the order key of the page's last item, as After will hand it back. "next" is present exactly when more is true. extra holds members that describe the list rather than the page, the same on every page.
IT FAILS CLOSED, as WriteError does. Each of these is a host programming error, answered as `500 internal` with the correlation id and logged, and never as a page in another shape:
- a call outside a host route, or on a List that ReadList did not return;
- a member that is empty, "truncated" or "next";
- an extra key that is the member, "truncated" or "next";
- items that do not encode as a JSON array;
- more with a nil last, or a last whose length is not ReadList's keyLen.
type Options ¶
type Options struct {
// Provider names the host in the route listing, the start-up log and
// the path of every route it serves, which is under
// /api/v1/hosts/<Provider>/ (see Route). It is <owner>/<name>, each
// lower-case letters, digits and hyphens: "hoplock/enterprise".
// Required when Routes, HostSections or ErrorCodes is non-empty;
// ext.ProviderControl is refused.
Provider string
// Registry is populated by the host and NOT sealed: Control registers
// its own defaults into it and seals it. An extension beats a Control
// default at a single-implementation point, in either order. Nil means
// ext.NewRegistry(), which is Control alone.
Registry *ext.Registry
// HostSections are top-level configuration keys the strict decoder
// accepts without defining them. Each must be a lower-case key like
// Control's own, and a name Control itself defines is refused: a host
// may not shadow `listeners`. Every other unknown key is still an
// error. Declaring sections requires HostConfig.
HostSections []string
// HostConfig is called by Run, and by the audit-verify and
// audit-retention subcommands (see Main), once per section present in
// the file and in file order, with that section re-encoded as YAML —
// before the registry is sealed, so a host may register an extension it
// builds from its section there, and before anything serves. An error
// fails start-up. Absent sections are not called.
HostConfig func(section string, raw []byte) error
// Routes are the host's north-bound routes. See Route.
Routes []Route
// ErrorCodes are the codes the host's handlers may answer with (M21),
// beside Control's own. Each is snake_case and none may be one of
// Control's.
ErrorCodes []string
}
Options is what a host adds to Control. The zero value is Control alone.
Every way a host can get these wrong is refused when Main or Run is called, before the configuration file is read, a database is opened or a port is bound: a host binary that will never start says so at once.
type Route ¶
type Route struct {
// Method is the HTTP method; one per route.
Method string
// Pattern is relative to the prefix Access names, in net/http's
// ServeMux syntax, without the method: "reports/{report}". No leading
// "/", no "{tenant}", no "." or "..".
Pattern string
// Permission is one of Control's permission codes ("audit:read",
// "report:write", ...). A host names a permission and never declares
// one: the roles that grant each are fixed in Control, so what "admin"
// means does not depend on which binary is running.
Permission string
// Access is the route's class. The zero value is AccessTenant.
Access Access
// Summary is one line for the route listing and the start-up log.
Summary string
// Handler serves the request. [CallerFrom] says who is calling, and
// [WriteError] answers a failure. Control's panic recovery, access log,
// body limit and request deadline apply to it exactly as to Control's
// own handlers.
Handler http.Handler
}
Route is a host's north-bound route.
Control mounts it on the north-bound listener only (M2), under the host's own namespace, /api/v1/hosts/<Provider>/, in the subtree its Access names. No route of Control's can match a path there, so a Pattern never takes a path Control serves, today or in a later release, and Control never takes one of the host's (M27). Before Handler runs, Control authenticates the caller and resolves what the request covers from the caller's own scope (M18): on an AccessTenant route exactly one tenant, in which it checks Permission; on an AccessCrossTenant route the set of tenants in which the caller holds Permission. A caller with no credential is answered 401, one without the permission 403, and one naming a tenant outside its scope 403 — and none of them reaches Handler.
There is no cross-tenant write: a write across tenants is one request making changes in several tenants' independent audit chains, with nothing to make them atomic and no answer for a partial outcome (M24).
A route that answers a list is expected to read the page with ReadList and answer it with List.Write, so that it is bounded by its caller and says where it stopped exactly as Control's lists do, and one client reads both (M26). Control cannot see which route is a list, so nothing enforces this: a host's own tests must.
Start-up fails, naming the route, on: an Access that is neither of the two; an empty method or one other than GET, POST, PUT, PATCH or DELETE; a Pattern that starts with "/", names "{tenant}", has a "." or ".." segment or an empty one before its end, or carries a method prefix — so that it can never leave the host's namespace, and is a path the mux serves as written; a Permission that is not one of Control's, or on an AccessCrossTenant route one the auditor role does not hold; a nil Handler; a duplicate of another of the host's routes; and a Pattern the standard library's mux reports as conflicting with another. A Pattern equal to one of Control's, such as "targets/{target}", is the host's own path in its own namespace and is not refused.