Documentation
¶
Overview ¶
Package api is the HTTP control plane. This file is the request/response plumbing every route shares: the JSON envelope, query variables, cookies, the base URL, and the byte-level helpers the terminal and the tuning knobs need. Routes live in routes.go; the principal and the gate in principal.go.
THE PERMISSION TABLE: which role may reach which route, in ONE ordered table consulted in ONE place, and DEFAULT-DENY.
── WHY A TABLE AND NOT A CHECK IN EACH HANDLER ─────────────────────────────────────────────────
A check inside each handler is a rule you have to remember to write. Forgetting is silent, and it is not hypothetical: `POST /api/users` shipped reachable by ANY authenticated principal and — the route passing no role, so the insert fell through to `COALESCE(?, 'admin')` — always created an ADMIN. Any account on the host could mint itself a second, fully privileged one. Nothing in the code looked wrong, because the missing check was invisible.
So the rule lives here instead, and a route with NO ENTRY requires root. Forgetting to add an entry costs an operator a 403 and one commit; forgetting a handler check costs the host. The fallback and a deliberate root-only row are the SAME expression — `who.Allows("")`, an unrankable minimum nobody but root meets — so there is no third behaviour to get wrong.
── THE SAME REGEXES routes.go DISPATCHES ON ────────────────────────────────────────────────────
Every row points at the compiled pattern the chain itself matches (`deploymentRe`, `notifierRe`, …), never a second copy of it. Two patterns for one route is a drift bug with a fuse in it: the day someone widens the dispatch pattern, the gate keeps matching the old one and the new shape of the route is ungated. permissions_test.go walks the source of the chain and fails if a matcher or a literal path it dispatches on has no row here.
── THE FOUR ROLES, AND THE TWO PRINCIPALS THAT ARE NOT ROLES ───────────────────────────────────
viewer < developer < maintainer < admin (internal/auth). Above them, `root` — the PSTACK_TOKEN bearer — passes everything.
A SHARE PRINCIPAL SKIPS THIS TABLE ENTIRELY, and that is not a hole. `shareAllows` (principal.go) has already run, BEFORE any route: GET only, its own deployment only, only the routes its views name, everything else refused (invariant 16). Ranking a share here would be a second, weaker copy of that gate; denying it here would break every share link on every host. It is decided before it arrives, so this table lets it pass and `auth.Principal.Allows` refuses it at every rank in case anyone ever reaches for it directly.
── WHERE A ROW IS A DECISION, NOT A DEDUCTION ──────────────────────────────────────────────────
Three rows below are worth stating out loud, because each looks wrong at a glance:
- `WS /api/deployments/:id/terminal` is DEVELOPER, not admin. A developer can already run arbitrary compose through `up` — including a service that mounts the docker socket — so refusing them the shell is theatre while the larger door stays open. Close the larger door first and this row can follow it.
- `GET /api/swarm/join` is MAINTAINER, where it used to be admin. It is a host-configuration read, and it sits with the other ones. It is still a real credential (the token joins a machine to the cluster), so it stops at maintainer and goes no lower.
- `PUT/DELETE /api/sso/config*` is ADMIN even though every other host-configuration write is maintainer, because a provider's `defaultRole` MINTS ACCOUNTS at whatever role it names. A maintainer able to point SSO at an identity provider they control could sign in through it as an admin — that is a promotion path, so it belongs with people, not with configuration. The matching READ stays maintainer: it returns a mask, never the client secret.
The two routes that carry a host's whole configuration — `GET /api/config` exports it, `POST /api/config` applies one. Everything else in this package is a route over ONE thing; these two are a route over EVERY secret the host holds, so the rules below are not the same rules.
── ROOT TOKEN ONLY. NOT AN ADMIN SESSION. THIS IS DELIBERATE ────────────────────────────────────
`mayMoveConfig` admits `auth.KindRoot` and nothing else. Every other admin-gated route in this package admits an admin browser session too — see the join-token check in routes.go, which reads `who.Kind != auth.KindRoot && !(who.Kind == auth.KindUser && who.User.Role == "admin")`. Copying that shape here would be the single worst change anyone could make to this file:
- GET returns argon2 password hashes, API-token hashes, every host secret, every notifier signing secret, the SSO client secret and every registry password, in plaintext. Reachable from a session cookie, one XSS in the UI — or one stolen laptop with a live session — is a complete credential exfiltration of the host, silently, from the victim's own browser.
- POST writes registry credentials, so the same cookie repoints where this host pulls images from.
The cost is real and was accepted: there is no button in the UI, and there never should be. A browser session is a human at a keyboard; `PSTACK_TOKEN` is the machine credential an operator deliberately put on a machine. Only the second one moves credentials. If you are here to "fix the inconsistency" with the other admin routes: the inconsistency is the security control.
── THE OTHER HALF OF THE GATE IS INVARIANT 9 ───────────────────────────────────────────────────
`principal()` returns `KindRoot` for EVERY request when `s.opts.Token == ""` — the loopback dev mode. On this route that means an unauthenticated GET returns the whole credential dump. What stops that being a hole is invariant 9 in `internal/cli`: with no `PSTACK_TOKEN` the listener is forced to 127.0.0.1, and an explicit non-loopback `PSTACK_HOST` is a hard exit 3 rather than a silent downgrade. This is the route where that interlock is the ONLY thing between an anonymous request and every secret on the host. Weaken it and you weaken this.
── WHAT REACHES A NOTIFIER, AND WHAT NEVER DOES ────────────────────────────────────────────────
Both routes emit, so a credential dump is visible rather than silent — that is the point of the events, and they are emitted BEFORE the response is written so a client that disconnects mid-body cannot suppress them (`Emit` is synchronous, in-order, and individually recovered).
The payloads carry COUNTS AND IDENTITIES ONLY. `Document.Trusts()` returns credentials — for a chat notifier the webhook URL *is* the secret — so it goes in the HTTP response body, which travels over TLS to a caller that already holds the plaintext, and NEVER into an event. An event body is POSTed to every subscribed notifier; putting a Slack URL in one is invariant 15's named failure (`docs/secret-exposure.md`), and `events.Event.Data`'s own comment says nothing secret goes in. Registry HOSTNAMES and notifier names/types are in the import event on purpose: they are what an operator needs to notice a hostile file, and neither is a credential.
The two host settings an operator may change at RUNTIME: `GET /api/settings` and `PUT /api/settings/<key>`. internal/settings owns the keys, the validation and the precedence; this file is the HTTP surface and the two things that happen the moment a value changes.
── THE READ SAYS WHERE THE VALUE CAME FROM ─────────────────────────────────────────────────────
Every row carries `source`: "db" (someone set it here), "env" (PSTACK_MAX_JOBS) or "default" (what the binary ships with). Without it a box saying 4 is unexplainable — an operator who typed 8 into it and still sees 4 has no way to tell a rejected write from a stale page from a value their environment is overriding, and "why did my change not stick" is unanswerable.
The SOURCE is computed here, per key, mirroring internal/settings' own predicate for "is this stored row usable" — that package resolves a VALUE and exposes no Source(key). It is a small duplication and it is deliberate; the alternative (comparing the resolved value with the stored text) lies about a hand-edited "008", which Atoi accepts and string equality does not.
── A WRITE APPLIES NOW, AND LOWERING THE CAP CANCELS NOTHING ───────────────────────────────────
PUT max_jobs calls jobs.Registry.SetMaxRunning, so the new cap is in force for the next dispatch without restarting the container — the whole point of the feature. Jobs already RUNNING run to completion, so the response says so in words: an operator who types 1 while four jobs run must not read the 200 as "three were just cancelled".
── THE PERMISSION IS PER KEY, AND LIVES IN permissions.go ──────────────────────────────────────
max_jobs is operational (MAINTAINER, with host configuration); default_role is user management by another name (ADMIN, with the promotion paths). The two rows are exact paths, so a key nobody listed is root's by the table's default-deny — and the chain 404s it, because this file dispatches on the two literals only. `minRole` in the read is taken FROM that table rather than written down again here: a second copy is the drift permissions.go's header exists to prevent.
Server: the control plane's remote surface. The route table is api.ts's header comment; the rules that matter are in AGENTS.md.
THIS API MUST NEVER MANAGE THE STACK IT RUNS IN (invariant 12). VARIABLES are merged from the request's `?query` (and a PUT's `env`) over the process env, once, at resolve time. SECURITY: every route but health/login/logout/bootstrap/sso is behind the principal gate, and behind THAT a second one — permissions.go, a single ordered (path, method, minimum role) table consulted once at the top of routes(), default-deny, so a route nobody listed is root's. Responses are built field by field and never echo a resolved Stack.Env.
Index ¶
Constants ¶
const ( ReadinessTimeoutMinS = 5 ReadinessTimeoutMaxS = 3600 )
Bounds of the `?timeout=` watch deadline, shared by `POST …/up` and `GET …/readiness`. The max is the job cap: a watch that could outlive every job would report on a stack nothing is driving. The min is over two poll intervals (readiness.PollMs is 2s): the up route's watch runs with Emit:true, and a deadline shorter than the first poll times out a SUCCESSFUL deploy into every notifier.
const WakeRetryMs = 60_000
WakeRetryMs: after a failed wake, how long a request to the hostname waits before trying again.
Variables ¶
This section is empty.
Functions ¶
func CrToNl ¶
CrToNl is CR → NL for terminal input. With no pty there is no line discipline, so this is the only thing standing between "Enter" and a shell that never runs anything. CRLF collapses to ONE NL, or every Enter from a client that sends both would run the line and then an empty one. Same rule for text and binary frames.
Types ¶
type Options ¶
type Options struct {
// DataDir is the registry root; deployments live under <DataDir>/deployments.
DataDir string
Port int
Host string
Token string
// RoutingDir is Traefik's dynamic-config directory. Default: the in-container mount path
// /etc/traefik/dynamic; on a host-side run, <dataDir>/control/traefik-dynamic.
RoutingDir string
// RegistryDir is the DOCKER_CONFIG directory holding private-registry credentials. Default:
// $DOCKER_CONFIG, else /docker-config.
RegistryDir string
// TerminalArgv opens a container shell. Default: docker exec -i <id> <shell>. Injectable for
// the same reason Runner is: the machine this is developed on has no Docker.
TerminalArgv func(containerID, shell string) []string
// Readiness tuning; zero means the defaults (2s / 180s / 3 restarts).
ReadinessPollMs int64
ReadinessTimeoutMs int64
// ReadinessRestartLoop is the crash-loop threshold. Raise it on a SWARM host: without
// `depends_on`, a dependent legitimately restarts while its database converges.
ReadinessRestartLoop int64
// MaxJobs is how many lifecycle jobs RUN AT ONCE across every stack (PSTACK_MAX_JOBS); zero
// means jobs.DefaultMaxRunning. Over the cap an accepted job WAITS for a slot — it is never
// refused. Not to be confused with jobs.MaxJobs, which bounds retained transcripts and is not
// tunable; the env name is the one the operator-facing contract fixed.
//
// It is now the DEFAULT rather than the authority: a `max_jobs` row in the settings table
// outranks it (internal/settings), so an operator who set the cap in the UI is not overridden
// by the container's environment on the next restart, and one who never opened the UI keeps
// exactly this value. PUT /api/settings/max_jobs applies without a restart.
MaxJobs int
// Domain is the preview domain (PSTACK_DOMAIN): share links and the SSO callback are built on
// control.<domain>; without it the request's own origin is used.
Domain string
// MetricsURL is Traefik's Prometheus endpoint (PSTACK_TRAEFIK_METRICS). What sleep.idle reads.
MetricsURL string
// Scheduler tuning — a minute on a host, milliseconds in a test.
SchedulerTickMs int64
SchedulerFetch scheduler.Fetcher
// SSO: how long a half-finished sign-in is remembered (default 300s) and how long a provider's
// discovery document is trusted (default 1h). Zero = default.
SSOStateTTLS int64
SSODiscoveryTTLS int64
// Bus defaults to events.Default.
Bus *events.Bus
// Env is the process environment the server hands to hooks and reads variables from; nil
// means os.Environ().
Env map[string]string
// Log receives the scheduler's and the SSO adoption lines (stderr on a host).
Log func(string)
// Version is what /api/health reports.
Version string
// UIHTML and ShareHTML are the two embedded pages.
UIHTML string
}
Options configure a server.
type Server ¶
type Server struct {
// contains filtered or unexported fields
}
Server is one running control plane.
Owner of writeMu: the registry/spec mutations that were racy check-then-acts in the reference (PUT/DELETE deployment, DELETE spec, the sleep record). Everything else has its own owner.
type Tuning ¶
type Tuning struct {
ReadinessPollMs float64
ReadinessTimeoutMs float64
ReadinessRestartLoop float64
SSOStateTTLS float64
SSODiscoveryTTLS float64
// MaxJobs is PSTACK_MAX_JOBS: how many lifecycle jobs RUN AT ONCE across every stack, zero
// meaning jobs.DefaultMaxRunning. It is NOT jobs.MaxJobs — that one bounds how many finished
// transcripts are kept and is not tunable. One letter apart in name, nothing in common.
MaxJobs float64
}
Tuning is what `serve` reads from the environment: the same knobs a test passes as options, so a black-box harness driving the real CLI can reach the expiry paths. `??` semantics — unset means the default, and a value that is not a positive number is ignored rather than turning a timeout into NaN.