server

package
v0.6.0 Latest Latest
Warning

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

Go to latest
Published: Oct 14, 2026 License: Apache-2.0 Imports: 9 Imported by: 1 module, 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 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:

  1. 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.
  2. Top-level sections of its own in Control's configuration file (Options.HostSections), handed to it undecoded.
  3. 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).
  4. 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"

	"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) Search(context.Context, ext.ArchiveQuery) (ext.ArchivePage, error) {
	return ext.ArchivePage{}, 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/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/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)
	}
}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Main

func Main(ctx context.Context, args []string, stdout, stderr io.Writer, o Options) error

Main is Hoplock Control's command line: the daemon and every subcommand (migrate, seed, audit-verify, 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, and none but the daemon hands them to HostConfig.

func Run

func Run(ctx context.Context, config io.Reader, o Options) error

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/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/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
}

Caller is who Control authenticated for the request a host route is serving.

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

func CallerFrom(ctx context.Context) (Caller, bool)

CallerFrom returns who Control authenticated for the request a host route is serving. ok is false outside a host route.

type Options

type Options struct {
	// Provider names the host in the route listing and the start-up log
	// (e.g. "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, 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, in net/http's ServeMux syntax, without the
	// method: "reports/{report}". No leading "/", no "{tenant}", no "..".
	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 prefix its Access names, and before Handler runs it 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).

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}", climbs with "..", or carries a method prefix; 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 any route, Control's or a host's; a Pattern on a path Control already serves; and a Pattern the standard library's mux reports as conflicting with another.

Jump to

Keyboard shortcuts

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