server

package
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Oct 12, 2026 License: Apache-2.0 Imports: 8 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).
  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, 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"
	"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, 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
		},

		// GET /api/v1/tenants/{tenant}/archive/{record}, for a caller holding
		// audit:read in the tenant Control resolved.
		Routes: []server.Route{{
			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")
			}),
		}},
		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 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.
	Tenant 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, and a handler that could ask would be a handler that could write a cross-tenant route (M18).

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
	// 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), at /api/v1/tenants/{tenant}/<Pattern>, as a tenant route: before Handler runs, Control authenticates the caller, resolves exactly one tenant from the caller's own scope (M18) and checks Permission in that tenant. 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 host route outside a tenant and no cross-tenant one: that needs an access class this surface does not have, which is a decision of its own.

Start-up fails, naming the route, on: 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; 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