oficina / alta Public

carlosop: 522 config doors, host-scoped restart, fake console

An in-memory Admin client for alta-adopt. It covers 522 Plan 1 config
reads, effective view and conditional PUT with receipts, instance
reads, and the narrowed restart door only. Also EnvDigest, and
fakecarlos with per-host layer chains and adverse hooks.
ChannelDigest is deferred until the platform offers a read for it.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
Paul Campbell pushed by paul@keymail.dev 60f4299a09b2a980d427c53aa58358e9b903c89c parent 61009c8
5 files changed, +1,827 −0
  • carlosop/client.go +623 −0
  • carlosop/client_test.go +473 −0
  • carlosop/digest.go +39 −0
  • carlosop/digest_test.go +14 −0
  • carlosop/fakecarlos/fakecarlos.go +678 −0
diff --git a/carlosop/client.go b/carlosop/client.go
new file mode 100644
index 0000000..1b5fd02
--- /dev/null
+++ b/carlosop/client.go
@@ -0,0 +1,623 @@
+// Package carlosop is alta-adopt's CARLOS console client. It reads and
+// writes an app's config through carlos/platform 522 Plan 1's doors
+// (versions, digests, conditional writes and receipts; config-receipts
+// design §4), reads instance records, and restarts one host through the
+// narrowed restart door. It is never imported by the served `alta`.
+//
+// It holds one short-lived Admin credential, in memory only (Paul's Q1
+// ruling, 2026-11-16). The token comes from a file descriptor, never the
+// environment or disk; it is never logged, and Close zeroes it.
+//
+// Nothing this package returns as an error carries the token, a config
+// value, a digest or a version: errors name the door, the HTTP status and
+// a fixed reason. The console's own error sentence is dropped, because it
+// can quote what it was sent.
+package carlosop
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/url"
+ "strings"
+ "sync"
+ "time"
+)
+
+// The errors callers act on. These are the only declarations; package
+// adopt reuses them rather than declaring its own.
+var (
+ // ErrVersionMismatch is a conditional write's 412: the layer was not at
+ // the version sent, at the door's read or at its write. Nothing was
+ // written.
+ ErrVersionMismatch = errors.New("carlosop: the layer is not at the version sent, so nothing was written")
+ // ErrNoConditional is a 400 to a conditional write: a console whose
+ // store has no atomic conditional write refuses if_version this way.
+ // Every Put is conditional, so every 400 to one reads as this.
+ ErrNoConditional = errors.New("carlosop: the console refused the conditional write")
+ // ErrNotFound is the console's 404: no such account, app, host or
+ // record, which the console deliberately does not tell apart.
+ ErrNotFound = errors.New("carlosop: not found")
+ // ErrNoScopedRestart is a 404 from the narrowed restart door: a
+ // console that predates it. Nothing was restarted, and nothing falls
+ // back to the app-wide door.
+ ErrNoScopedRestart = errors.New("carlosop: the console has no host-scoped restart")
+)
+
+// StatusError is any other non-2xx answer, a redirect included. Door is
+// the method and path template ("GET /config"), never a value.
+type StatusError struct {
+ Door string
+ Code int
+}
+
+func (e *StatusError) Error() string {
+ return fmt.Sprintf("carlosop: %s answered %d", e.Door, e.Code)
+}
+
+// Var is one variable of one stored layer. Value is set only for kind
+// "env"; a secret is its key, kind and digest.
+type Var struct{ Key, Kind, Value, Digest string }
+
+// Layer is one stored config bundle: "default", or a named environment.
+type Layer struct {
+ Bundle, Version string
+ Vars []Var
+}
+
+// EffectiveVar is one key of a host's merged config: From is the layer
+// whose value the host gets, Shadows the lower layers that also set it,
+// nearest first. No value: the effective view is compared by digest.
+type EffectiveVar struct {
+ Key, Kind, Digest, From string
+ Shadows []string
+}
+
+// Effective is GET /config/effective for one host. Layers maps "default"
+// (absent for an owned environment), "environment" (absent for a host
+// bound to none) and "overlay" to their versions.
+type Effective struct {
+ Host, Environment string
+ Owned bool
+ Layers map[string]string
+ Vars []EffectiveVar
+}
+
+// Receipt is a successful PUT's description of what it wrote (522 §4.6).
+// Others names other layers' versions either side of the write: the
+// default bundle's, for a write to a named environment.
+type Receipt struct {
+ Bundle, VersionBefore, VersionAfter string
+ Changed bool
+ Set, Unset, UnsetAbsent []string
+ Digests map[string]string
+ Others map[string]struct{ Before, After string }
+}
+
+// Instance is the part of an instance record adoption compares. Move,
+// ReplicaAssignment and Seed are the record's JSON as stored, nil when
+// absent.
+type Instance struct {
+ Host, PublicHost, Account, App, Slug, Environment, Channel, Region string
+ CreatedAt time.Time
+ RecordSeq uint64
+ Move, ReplicaAssignment, Seed json.RawMessage
+}
+
+// PutRequest is one conditional write. Set holds plain values only; the
+// runner never sends a secret.
+type PutRequest struct {
+ Environment string // "" = the default bundle
+ Set map[string]string
+ Unset []string
+ IfVersion string
+}
+
+// RestartRoute is one route a restart addresses.
+type RestartRoute struct {
+ Host, Environment, Unit string
+ Hibernate bool
+}
+
+// Client is one console, one account (by sqid) and one Admin token.
+type Client struct {
+ mu sync.Mutex
+ base string
+ baseErr error
+ account string
+ token []byte
+ closed bool
+ http *http.Client
+}
+
+// New builds a client. It takes token and does not copy it: Close zeroes
+// that slice in place, so the caller must not keep or reuse it. The token
+// is read from a file descriptor (Q1), never from the environment or disk.
+//
+// console must be https; plain http is admitted only to a loopback
+// address, for tests.
+func New(console, account string, token []byte) *Client {
+ c := &Client{account: account, token: token, http: &http.Client{
+ Timeout: 60 * time.Second,
+ // Never follow: a redirect is answered as the 3xx it is, so the
+ // token is never sent to a second origin.
+ CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse },
+ }}
+ u, err := url.Parse(console)
+ switch {
+ case err != nil || u.Host == "" || u.User != nil || u.RawQuery != "" || u.Fragment != "":
+ c.baseErr = errors.New("carlosop: the console address is not a plain https URL")
+ case u.Scheme == "https":
+ case u.Scheme == "http" && loopback(u.Hostname()):
+ default:
+ c.baseErr = errors.New("carlosop: the console must be https (plain http only to loopback)")
+ }
+ if c.baseErr == nil {
+ c.base = strings.TrimRight(u.String(), "/")
+ }
+ return c
+}
+
+func loopback(host string) bool {
+ if host == "localhost" {
+ return true
+ }
+ ip := net.ParseIP(host)
+ return ip != nil && ip.IsLoopback()
+}
+
+// Close zeroes the token and refuses every later call. Idempotent. A
+// request already in flight keeps the header it was built with.
+func (c *Client) Close() {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ clear(c.token)
+ c.closed = true
+ c.http.CloseIdleConnections()
+}
+
+func (c *Client) bearer() (string, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ switch {
+ case c.closed:
+ return "", errors.New("carlosop: the client is closed")
+ case c.baseErr != nil:
+ return "", c.baseErr
+ case len(c.token) == 0:
+ return "", errors.New("carlosop: no token")
+ case c.account == "":
+ return "", errors.New("carlosop: no account")
+ }
+ return "Bearer " + string(c.token), nil
+}
+
+// do sends one request to path under the app; door is its fixed
+// template, for errors, and decodes a 2xx answer into out. Any other status is a
+// *StatusError.
+func (c *Client) do(ctx context.Context, method, app, door, path string, body, out any) error {
+ auth, err := c.bearer()
+ if err != nil {
+ return err
+ }
+ if app == "" {
+ return errors.New("carlosop: no app")
+ }
+ var rd io.Reader
+ if body != nil {
+ b, err := json.Marshal(body)
+ if err != nil {
+ return fmt.Errorf("carlosop: %s: could not encode the request", door)
+ }
+ rd = bytes.NewReader(b)
+ }
+ u := c.base + "/api/cli/apps/" + url.PathEscape(c.account) + "/" + url.PathEscape(app) + path
+ req, err := http.NewRequestWithContext(ctx, method, u, rd)
+ if err != nil {
+ return fmt.Errorf("carlosop: %s: could not build the request", door)
+ }
+ req.Header.Set("Authorization", auth)
+ req.Header.Set("Accept", "application/json")
+ if body != nil {
+ req.Header.Set("Content-Type", "application/json")
+ }
+ resp, err := c.http.Do(req)
+ if err != nil {
+ // A *url.Error names the URL (account, app, host) and the cause;
+ // the token is a header and never part of it.
+ return fmt.Errorf("carlosop: %s: %w", door, err)
+ }
+ defer resp.Body.Close()
+ raw, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
+ if err != nil {
+ return fmt.Errorf("carlosop: %s: could not read the answer", door)
+ }
+ if resp.StatusCode < 200 || resp.StatusCode > 299 {
+ return &StatusError{Door: door, Code: resp.StatusCode}
+ }
+ if out != nil {
+ // The decoder's own error can quote the answer; it is dropped.
+ if json.Unmarshal(raw, out) != nil {
+ return fmt.Errorf("carlosop: %s: unreadable answer", door)
+ }
+ }
+ return nil
+}
+
+// as maps a status to the error callers act on, wrapping the status.
+func as(err error, by map[int]error) error {
+ var se *StatusError
+ if errors.As(err, &se) {
+ if e, ok := by[se.Code]; ok {
+ return fmt.Errorf("%w (%s answered %d)", e, se.Door, se.Code)
+ }
+ }
+ return err
+}
+
+var notFound = map[int]error{http.StatusNotFound: ErrNotFound}
+
+func malformed(door, why string) error {
+ return fmt.Errorf("carlosop: %s answered %s", door, why)
+}
+
+// Config reads one stored layer: the default bundle for env "", else the
+// named environment. An absent layer is version "none" with no vars.
+func (c *Client) Config(ctx context.Context, app, env string) (Layer, error) {
+ const door = "GET /config"
+ path := "/config"
+ if env != "" {
+ path += "?environment=" + url.QueryEscape(env)
+ }
+ var w struct {
+ Bundle string `json:"bundle"`
+ Version string `json:"version"`
+ Vars []struct {
+ Key string `json:"key"`
+ Kind string `json:"kind"`
+ Value *string `json:"value"`
+ Digest string `json:"digest"`
+ } `json:"vars"`
+ }
+ if err := c.do(ctx, http.MethodGet, app, door, path, nil, &w); err != nil {
+ return Layer{}, as(err, notFound)
+ }
+ want := env
+ if want == "" {
+ want = "default"
+ }
+ if w.Bundle != want {
+ return Layer{}, malformed(door, "another bundle")
+ }
+ if !validVersion(w.Version) {
+ return Layer{}, malformed(door, "a malformed version")
+ }
+ l := Layer{Bundle: w.Bundle, Version: w.Version, Vars: make([]Var, 0, len(w.Vars))}
+ seen := map[string]bool{}
+ for _, v := range w.Vars {
+ switch {
+ case v.Key == "" || seen[v.Key]:
+ return Layer{}, malformed(door, "an empty or repeated key")
+ case v.Kind != "env" && v.Kind != "secret":
+ return Layer{}, malformed(door, "an unknown kind")
+ case v.Kind == "secret" && v.Value != nil:
+ // Never hold a secret's plaintext, even if a console sent it.
+ return Layer{}, malformed(door, "a secret with a value")
+ case !validDigest(v.Digest):
+ return Layer{}, malformed(door, "a malformed digest")
+ }
+ seen[v.Key] = true
+ out := Var{Key: v.Key, Kind: v.Kind, Digest: v.Digest}
+ if v.Value != nil {
+ out.Value = *v.Value
+ }
+ l.Vars = append(l.Vars, out)
+ }
+ return l, nil
+}
+
+// Effective reads one host's merged config: each key's kind, digest, the
+// layer it comes from and the layers it shadows. Values are not read.
+func (c *Client) Effective(ctx context.Context, app, host string) (Effective, error) {
+ const door = "GET /config/effective"
+ if strings.TrimSpace(host) == "" {
+ return Effective{}, errors.New("carlosop: Effective needs a host")
+ }
+ var w struct {
+ Host string `json:"host"`
+ Environment string `json:"environment"`
+ Owned bool `json:"owned"`
+ Layers map[string]struct {
+ Name string `json:"name"`
+ Version string `json:"version"`
+ } `json:"layers"`
+ Vars []struct {
+ Key string `json:"key"`
+ Kind string `json:"kind"`
+ Digest string `json:"digest"`
+ From string `json:"from"`
+ Shadows []string `json:"shadows"`
+ } `json:"vars"`
+ }
+ if err := c.do(ctx, http.MethodGet, app, door, "/config/effective?host="+url.QueryEscape(host), nil, &w); err != nil {
+ return Effective{}, as(err, notFound)
+ }
+ if w.Host != host {
+ return Effective{}, malformed(door, "another host")
+ }
+ e := Effective{Host: w.Host, Environment: w.Environment, Owned: w.Owned, Layers: map[string]string{}}
+ for name, l := range w.Layers {
+ if name != "default" && name != "environment" && name != "overlay" {
+ return Effective{}, malformed(door, "an unknown layer")
+ }
+ if !validVersion(l.Version) {
+ return Effective{}, malformed(door, "a malformed version")
+ }
+ e.Layers[name] = l.Version
+ }
+ _, hasDefault := e.Layers["default"]
+ _, hasEnv := e.Layers["environment"]
+ _, hasOverlay := e.Layers["overlay"]
+ switch {
+ case !hasOverlay:
+ return Effective{}, malformed(door, "no overlay layer")
+ case hasEnv != (w.Environment != "") || (hasEnv && w.Layers["environment"].Name != w.Environment):
+ return Effective{}, malformed(door, "an environment layer that disagrees with the binding")
+ case w.Owned == hasDefault:
+ return Effective{}, malformed(door, "a default layer that disagrees with ownership")
+ }
+ seen := map[string]bool{}
+ for _, v := range w.Vars {
+ if v.Key == "" || seen[v.Key] || !validDigest(v.Digest) || (v.Kind != "env" && v.Kind != "secret") {
+ return Effective{}, malformed(door, "a malformed var")
+ }
+ if _, ok := e.Layers[v.From]; !ok {
+ return Effective{}, malformed(door, "a var from no listed layer")
+ }
+ for _, s := range v.Shadows {
+ if _, ok := e.Layers[s]; !ok || s == v.From {
+ return Effective{}, malformed(door, "a var shadowing no listed layer")
+ }
+ }
+ seen[v.Key] = true
+ e.Vars = append(e.Vars, EffectiveVar{Key: v.Key, Kind: v.Kind, Digest: v.Digest, From: v.From, Shadows: append([]string{}, v.Shadows...)})
+ }
+ return e, nil
+}
+
+// Put makes one conditional write: Set's plain values and Unset's
+// removals in one request, if the layer is at IfVersion. It answers the
+// write's receipt.
+//
+// A 412 is ErrVersionMismatch and a 400 is ErrNoConditional; nothing was
+// written for either. IfVersion is required, travels as one JSON string in
+// the body (there is no If-Match), and is never combined with
+// exec_delivery.
+func (c *Client) Put(ctx context.Context, app string, r PutRequest) (Receipt, error) {
+ const door = "PUT /config"
+ switch {
+ case r.IfVersion == "":
+ return Receipt{}, errors.New("carlosop: every config write is conditional; IfVersion is required")
+ case !validVersion(r.IfVersion):
+ return Receipt{}, errors.New("carlosop: IfVersion is not a layer version")
+ case len(r.Set) == 0 && len(r.Unset) == 0:
+ return Receipt{}, errors.New("carlosop: nothing to write")
+ }
+ for _, k := range r.Unset {
+ if _, both := r.Set[k]; both || k == "" {
+ return Receipt{}, errors.New("carlosop: a key is empty, or in both set and unset")
+ }
+ }
+ body := map[string]any{"if_version": r.IfVersion}
+ if r.Environment != "" {
+ body["environment"] = r.Environment
+ }
+ if len(r.Set) > 0 {
+ set := make(map[string]any, len(r.Set))
+ for k, v := range r.Set {
+ if k == "" {
+ return Receipt{}, errors.New("carlosop: a key is empty, or in both set and unset")
+ }
+ set[k] = map[string]string{"kind": "env", "value": v}
+ }
+ body["set"] = set
+ }
+ if len(r.Unset) > 0 {
+ body["unset"] = r.Unset
+ }
+ var w struct {
+ Receipt *struct {
+ Bundle string `json:"bundle"`
+ VersionBefore string `json:"version_before"`
+ VersionAfter string `json:"version_after"`
+ Changed bool `json:"changed"`
+ Set []string `json:"set"`
+ Unset []string `json:"unset"`
+ UnsetAbsent []string `json:"unset_absent"`
+ Digests map[string]string `json:"digests"`
+ Others map[string]struct {
+ Before string `json:"before"`
+ After string `json:"after"`
+ } `json:"others"`
+ } `json:"receipt"`
+ }
+ if err := c.do(ctx, http.MethodPut, app, door, "/config", body, &w); err != nil {
+ return Receipt{}, as(err, map[int]error{
+ http.StatusPreconditionFailed: ErrVersionMismatch,
+ http.StatusBadRequest: ErrNoConditional,
+ http.StatusNotFound: ErrNotFound,
+ })
+ }
+ rc := w.Receipt
+ want := r.Environment
+ if want == "" {
+ want = "default"
+ }
+ switch {
+ case rc == nil:
+ return Receipt{}, malformed(door, "no receipt")
+ case rc.Bundle != want:
+ return Receipt{}, malformed(door, "a receipt for another bundle")
+ case !validVersion(rc.VersionBefore) || !validVersion(rc.VersionAfter):
+ return Receipt{}, malformed(door, "a malformed version")
+ }
+ for _, d := range rc.Digests {
+ if !validDigest(d) {
+ return Receipt{}, malformed(door, "a malformed digest")
+ }
+ }
+ out := Receipt{Bundle: rc.Bundle, VersionBefore: rc.VersionBefore, VersionAfter: rc.VersionAfter, Changed: rc.Changed,
+ Set: rc.Set, Unset: rc.Unset, UnsetAbsent: rc.UnsetAbsent, Digests: rc.Digests}
+ if len(rc.Others) > 0 {
+ out.Others = map[string]struct{ Before, After string }{}
+ for k, p := range rc.Others {
+ // A side the console could not read is empty, and compares
+ // unequal to any version.
+ if (p.Before != "" && !validVersion(p.Before)) || (p.After != "" && !validVersion(p.After)) {
+ return Receipt{}, malformed(door, "a malformed version")
+ }
+ out.Others[k] = struct{ Before, After string }{p.Before, p.After}
+ }
+ }
+ return out, nil
+}
+
+type wireInstance struct {
+ Host string `json:"host"`
+ PublicHost string `json:"public_host"`
+ Account string `json:"account"`
+ App string `json:"app"`
+ Slug string `json:"slug"`
+ Environment string `json:"environment"`
+ Channel string `json:"channel"`
+ Region string `json:"region"`
+ CreatedAt time.Time `json:"created_at"`
+ RecordSeq uint64 `json:"record_seq"`
+ Move json.RawMessage `json:"move"`
+ ReplicaAssignment json.RawMessage `json:"replica_assignment"`
+ Seed json.RawMessage `json:"seed"`
+}
+
+func rawOrNil(m json.RawMessage) json.RawMessage {
+ if len(m) == 0 || string(m) == "null" {
+ return nil
+ }
+ return append(json.RawMessage{}, m...)
+}
+
+func (c *Client) instance(door, app string, w wireInstance) (Instance, error) {
+ if w.Host == "" || w.App != app || w.Account != c.account {
+ return Instance{}, malformed(door, "a record of another app or account")
+ }
+ return Instance{Host: w.Host, PublicHost: w.PublicHost, Account: w.Account, App: w.App, Slug: w.Slug,
+ Environment: w.Environment, Channel: w.Channel, Region: w.Region, CreatedAt: w.CreatedAt, RecordSeq: w.RecordSeq,
+ Move: rawOrNil(w.Move), ReplicaAssignment: rawOrNil(w.ReplicaAssignment), Seed: rawOrNil(w.Seed)}, nil
+}
+
+// maxPages bounds the instance list's cursor walk.
+const maxPages = 100
+
+// Instances lists every record of app, following the list's cursor. A
+// list the console says is truncated is refused: a record left out could
+// be the one that would inherit a key.
+func (c *Client) Instances(ctx context.Context, app string) ([]Instance, error) {
+ const door = "GET /instances"
+ var out []Instance
+ cursor := ""
+ for range maxPages {
+ path := "/instances"
+ if cursor != "" {
+ path += "?cursor=" + url.QueryEscape(cursor)
+ }
+ var w struct {
+ Instances []wireInstance `json:"instances"`
+ Truncated bool `json:"truncated"`
+ NextCursor string `json:"next_cursor"`
+ }
+ if err := c.do(ctx, http.MethodGet, app, door, path, nil, &w); err != nil {
+ return nil, as(err, notFound)
+ }
+ if w.Truncated {
+ return nil, malformed(door, "a truncated list")
+ }
+ for _, wi := range w.Instances {
+ in, err := c.instance(door, app, wi)
+ if err != nil {
+ return nil, err
+ }
+ out = append(out, in)
+ }
+ if w.NextCursor == "" {
+ return out, nil
+ }
+ if w.NextCursor == cursor {
+ return nil, malformed(door, "a cursor that does not move")
+ }
+ cursor = w.NextCursor
+ }
+ return nil, malformed(door, "more pages than the walk allows")
+}
+
+// Instance reads one record. An unknown host is ErrNotFound.
+func (c *Client) Instance(ctx context.Context, app, host string) (Instance, error) {
+ const door = "GET /instances/{host}"
+ if strings.TrimSpace(host) == "" {
+ return Instance{}, errors.New("carlosop: Instance needs a host")
+ }
+ var w wireInstance
+ if err := c.do(ctx, http.MethodGet, app, door, "/instances/"+url.PathEscape(host), nil, &w); err != nil {
+ return Instance{}, as(err, notFound)
+ }
+ if w.Host != host {
+ return Instance{}, malformed(door, "another host")
+ }
+ return c.instance(door, app, w)
+}
+
+// RestartHost asks the narrowed restart door to cycle exactly host, or
+// with dryRun to say what it would cycle. It never calls the app-wide
+// door: a 404 is ErrNoScopedRestart (a console that predates the narrowed
+// door) and nothing falls back. An empty host is refused here, since the
+// narrowed door reads no selector as the whole app.
+//
+// Only adopt.RestartCanonical calls this.
+func (c *Client) RestartHost(ctx context.Context, app, host string, dryRun bool) ([]RestartRoute, error) {
+ const door = "POST /restart/scope"
+ if strings.TrimSpace(host) == "" || host != strings.TrimSpace(host) {
+ return nil, errors.New("carlosop: a restart names exactly one host")
+ }
+ var w struct {
+ Scope struct {
+ Kind string `json:"kind"`
+ Value string `json:"value"`
+ } `json:"scope"`
+ DryRun bool `json:"dry_run"`
+ Requested bool `json:"requested"`
+ Routes []struct {
+ Host string `json:"host"`
+ Environment string `json:"environment"`
+ Unit string `json:"unit"`
+ Hibernate bool `json:"hibernate"`
+ } `json:"routes"`
+ }
+ body := map[string]any{"host": host, "dry_run": dryRun}
+ if err := c.do(ctx, http.MethodPost, app, door, "/restart/scope", body, &w); err != nil {
+ return nil, as(err, map[int]error{http.StatusNotFound: ErrNoScopedRestart})
+ }
+ switch {
+ case w.Scope.Kind != "host" || w.Scope.Value != host:
+ return nil, malformed(door, "a scope other than the host")
+ case w.DryRun != dryRun || w.Requested == dryRun:
+ return nil, malformed(door, "a dry run or request it was not asked for")
+ }
+ out := make([]RestartRoute, 0, len(w.Routes))
+ for _, r := range w.Routes {
+ out = append(out, RestartRoute{Host: r.Host, Environment: r.Environment, Unit: r.Unit, Hibernate: r.Hibernate})
+ }
+ return out, nil
+}
diff --git a/carlosop/client_test.go b/carlosop/client_test.go
new file mode 100644
index 0000000..5d781cd
--- /dev/null
+++ b/carlosop/client_test.go
@@ -0,0 +1,473 @@
+package carlosop_test
+
+import (
+ "context"
+ "encoding/json"
+ "errors"
+ "io"
+ "maps"
+ "net/http"
+ "net/http/httptest"
+ "slices"
+ "strings"
+ "sync/atomic"
+ "testing"
+ "time"
+
+ "amadan.net/oficina/alta/carlosop"
+ "amadan.net/oficina/alta/carlosop/fakecarlos"
+)
+
+const acct = "bds"
+
+var ctx = context.Background()
+
+func newFake(t *testing.T) (*fakecarlos.Fake, *carlosop.Client) {
+ t.Helper()
+ f := fakecarlos.New(acct)
+ t.Cleanup(f.Close)
+ c := carlosop.New(f.URL(), acct, f.Token())
+ t.Cleanup(c.Close)
+ return f, c
+}
+
+func canonical(f *fakecarlos.Fake, app string) string {
+ host := "oficina-" + app + "." + acct + ".oncarlos.com"
+ f.AddInstance(carlosop.Instance{Host: host, PublicHost: app + ".oficina.works", Account: acct, App: app, Slug: "s-" + app,
+ Channel: "stable", Region: "eu", CreatedAt: time.Date(2026, 10, 1, 0, 0, 0, 0, time.UTC), RecordSeq: 3})
+ return host
+}
+
+// rawConsole is a console that records each request and answers with
+// answer. It is for wire-level assertions the fake does not expose.
+type seen struct {
+ Method, Path, Query string
+ Header http.Header
+ Body []byte
+}
+
+func rawConsole(t *testing.T, answer func(w http.ResponseWriter, r *http.Request)) (*httptest.Server, *[]seen) {
+ t.Helper()
+ var log []seen
+ srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ b, _ := io.ReadAll(r.Body)
+ log = append(log, seen{r.Method, r.URL.Path, r.URL.RawQuery, r.Header.Clone(), b})
+ answer(w, r)
+ }))
+ t.Cleanup(srv.Close)
+ return srv, &log
+}
+
+func writeJSON(w http.ResponseWriter, status int, v any) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ _ = json.NewEncoder(w).Encode(v)
+}
+
+const v1 = "cv1:1111111111111111111111111111111111111111111111111111111111111111"
+const v2 = "cv1:2222222222222222222222222222222222222222222222222222222222222222"
+const d1 = "vd1:3333333333333333333333333333333333333333333333333333333333333333"
+
+func TestPutSendsIfVersionInBodyOnly(t *testing.T) {
+ srv, log := rawConsole(t, func(w http.ResponseWriter, r *http.Request) {
+ writeJSON(w, 200, map[string]any{"result": "ok", "removed": 0, "receipt": map[string]any{
+ "bundle": "default", "version_before": v1, "version_after": v2, "changed": true,
+ "set": []string{"DOCS_AGENT_ISSUER"}, "unset": []string{}, "unset_absent": []string{},
+ "digests": map[string]string{"DOCS_AGENT_ISSUER": d1}}})
+ })
+ c := carlosop.New(srv.URL, acct, []byte("svc_token"))
+ defer c.Close()
+
+ // No version: refused before anything is sent.
+ if _, err := c.Put(ctx, "docs", carlosop.PutRequest{Set: map[string]string{"DOCS_AGENT_ISSUER": "https://connect.oficina.works"}}); err == nil {
+ t.Fatalf("Put without IfVersion was not refused")
+ }
+ if len(*log) != 0 {
+ t.Fatalf("Put without IfVersion reached the console")
+ }
+
+ rc, err := c.Put(ctx, "docs", carlosop.PutRequest{Set: map[string]string{"DOCS_AGENT_ISSUER": "https://connect.oficina.works"}, IfVersion: v1})
+ if err != nil {
+ t.Fatalf("Put: %v", err)
+ }
+ if rc.VersionBefore != v1 || rc.VersionAfter != v2 || !rc.Changed || !slices.Equal(rc.Set, []string{"DOCS_AGENT_ISSUER"}) || rc.Digests["DOCS_AGENT_ISSUER"] != d1 {
+ t.Fatalf("receipt not decoded field for field")
+ }
+ if len(*log) != 1 {
+ t.Fatalf("want one request, got %d", len(*log))
+ }
+ got := (*log)[0]
+ if got.Method != http.MethodPut || got.Path != "/api/cli/apps/bds/docs/config" || got.Query != "" {
+ t.Fatalf("wrong door: %s %s?%s", got.Method, got.Path, got.Query)
+ }
+ if len(got.Header.Values("If-Match")) != 0 || len(got.Header.Values("If-None-Match")) != 0 {
+ t.Fatalf("a precondition header was sent")
+ }
+ if got.Header.Get("Authorization") != "Bearer svc_token" || !strings.HasPrefix(got.Header.Get("Content-Type"), "application/json") {
+ t.Fatalf("missing bearer or JSON content type")
+ }
+ var body map[string]json.RawMessage
+ if err := json.Unmarshal(got.Body, &body); err != nil {
+ t.Fatalf("body is not one JSON object")
+ }
+ if string(body["if_version"]) != `"`+v1+`"` {
+ t.Fatalf("if_version is not the version as one JSON string")
+ }
+ for _, k := range []string{"exec_delivery", "environment", "unset"} {
+ if _, ok := body[k]; ok {
+ t.Fatalf("body carries %s", k)
+ }
+ }
+ var set map[string]map[string]string
+ if err := json.Unmarshal(body["set"], &set); err != nil || len(set) != 1 || set["DOCS_AGENT_ISSUER"]["kind"] != "env" || set["DOCS_AGENT_ISSUER"]["value"] != "https://connect.oficina.works" {
+ t.Fatalf("set is not the plain var sent")
+ }
+}
+
+func TestPut412IsVersionMismatch(t *testing.T) {
+ f, c := newFake(t)
+ f.SetVar("docs", "", "LOG_LEVEL", "info")
+ l, err := c.Config(ctx, "docs", "")
+ if err != nil {
+ t.Fatalf("Config: %v", err)
+ }
+ f.PlatformWrite("docs", "", "DOCS_SMTP_HOST", "smtp.example")
+ _, err = c.Put(ctx, "docs", carlosop.PutRequest{Set: map[string]string{"DOCS_AGENT_TEAM": "tsqid"}, IfVersion: l.Version})
+ if !errors.Is(err, carlosop.ErrVersionMismatch) {
+ t.Fatalf("stale if_version: want ErrVersionMismatch, got %v", err)
+ }
+ if vars, _, _ := f.Layer("docs", ""); vars["DOCS_AGENT_TEAM"].Kind != "" {
+ t.Fatalf("a refused write was stored")
+ }
+ // The same refusal when a writer lands between the door's read and its
+ // write, through BeforePut.
+ l, _ = c.Config(ctx, "docs", "")
+ f.BeforePut = func(app string) { f.PlatformWrite(app, "", "DOCS_SMTP_PORT", "587") }
+ if _, err := c.Put(ctx, "docs", carlosop.PutRequest{Set: map[string]string{"DOCS_AGENT_TEAM": "tsqid"}, IfVersion: l.Version}); !errors.Is(err, carlosop.ErrVersionMismatch) {
+ t.Fatalf("racing writer: want ErrVersionMismatch, got %v", err)
+ }
+ f.BeforePut = nil
+ // And a matching version lands, with its receipt.
+ l, _ = c.Config(ctx, "docs", "")
+ rc, err := c.Put(ctx, "docs", carlosop.PutRequest{Set: map[string]string{"DOCS_AGENT_TEAM": "tsqid"}, IfVersion: l.Version})
+ if err != nil || rc.VersionBefore != l.Version || rc.Digests["DOCS_AGENT_TEAM"] != carlosop.EnvDigest("tsqid") {
+ t.Fatalf("a current if_version did not land with its receipt: %v", err)
+ }
+}
+
+func TestPut400OnConditionalIsNoConditional(t *testing.T) {
+ f, c := newFake(t)
+ f.SetVar("docs", "", "LOG_LEVEL", "info")
+ l, _ := c.Config(ctx, "docs", "")
+ f.NoConditional()
+ _, err := c.Put(ctx, "docs", carlosop.PutRequest{Set: map[string]string{"DOCS_AGENT_TEAM": "tsqid"}, IfVersion: l.Version})
+ if !errors.Is(err, carlosop.ErrNoConditional) {
+ t.Fatalf("a console refusing if_version: want ErrNoConditional, got %v", err)
+ }
+ if _, ver, _ := f.Layer("docs", ""); ver != l.Version {
+ t.Fatalf("the refused write moved the layer")
+ }
+}
+
+func TestRestartHostUsesScopeDoorOnly(t *testing.T) {
+ f, c := newFake(t)
+ host := canonical(f, "docs")
+ other := "beta-docs." + acct + ".oncarlos.com"
+ f.AddInstance(carlosop.Instance{Host: other, Account: acct, App: "docs", Environment: "beta"})
+
+ if _, err := c.RestartHost(ctx, "docs", "", true); err == nil {
+ t.Fatalf("an empty host (the whole app) was not refused")
+ }
+ if len(f.Requests()) != 0 {
+ t.Fatalf("an empty host reached the console")
+ }
+ routes, err := c.RestartHost(ctx, "docs", host, true)
+ if err != nil || len(routes) != 1 || routes[0].Host != host {
+ t.Fatalf("dry run did not resolve exactly the host: %v", err)
+ }
+ if f.RestartCount(host) != 0 {
+ t.Fatalf("a dry run restarted")
+ }
+ if _, err := c.RestartHost(ctx, "docs", host, false); err != nil {
+ t.Fatalf("RestartHost: %v", err)
+ }
+ if f.RestartCount(host) != 1 || f.RestartCount(other) != 0 || f.AppWideRestarts() != 0 {
+ t.Fatalf("restart was not exactly the one host")
+ }
+ for _, r := range f.Requests() {
+ if r != "POST /restart/scope" {
+ t.Fatalf("a door other than restart/scope was called: %s", r)
+ }
+ }
+}
+
+func TestRestartHostOldConsoleFailsClosed(t *testing.T) {
+ f, c := newFake(t)
+ host := canonical(f, "docs")
+ f.NoScopedRestart()
+ for _, dry := range []bool{true, false} {
+ if _, err := c.RestartHost(ctx, "docs", host, dry); !errors.Is(err, carlosop.ErrNoScopedRestart) {
+ t.Fatalf("old console (dry=%v): want ErrNoScopedRestart, got %v", dry, err)
+ }
+ }
+ if f.RestartCount(host) != 0 || f.AppWideRestarts() != 0 {
+ t.Fatalf("an old console's 404 was answered with a restart")
+ }
+ for _, r := range f.Requests() {
+ if r != "POST /restart/scope" {
+ t.Fatalf("fell back to another door: %s", r)
+ }
+ }
+
+ f2, c2 := newFake(t)
+ host2 := canonical(f2, "docs")
+ f2.FailRestart(http.StatusServiceUnavailable)
+ _, err := c2.RestartHost(ctx, "docs", host2, true)
+ if err == nil || errors.Is(err, carlosop.ErrNoScopedRestart) {
+ t.Fatalf("503: want a plain failure, got %v", err)
+ }
+ if f2.RestartCount(host2) != 0 || f2.AppWideRestarts() != 0 {
+ t.Fatalf("a 503 was answered with a restart")
+ }
+}
+
+func TestClientNeverFollowsRedirect(t *testing.T) {
+ var hits atomic.Int32
+ target := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ hits.Add(1)
+ writeJSON(w, 200, map[string]any{"bundle": "default", "version": "none", "vars": []any{}})
+ }))
+ defer target.Close()
+ for _, code := range []int{301, 302, 307, 308} {
+ srv, _ := rawConsole(t, func(w http.ResponseWriter, r *http.Request) {
+ http.Redirect(w, r, target.URL+r.URL.Path, code)
+ })
+ c := carlosop.New(srv.URL, acct, []byte("svc_token"))
+ if _, err := c.Config(ctx, "docs", ""); err == nil {
+ t.Fatalf("%d: a redirect was answered as success", code)
+ }
+ if _, err := c.Put(ctx, "docs", carlosop.PutRequest{Set: map[string]string{"K": "v"}, IfVersion: v1}); err == nil {
+ t.Fatalf("%d: a redirected PUT was answered as success", code)
+ }
+ c.Close()
+ }
+ if hits.Load() != 0 {
+ t.Fatalf("a redirect was followed %d times", hits.Load())
+ }
+}
+
+func TestErrorsCarryNoTokenOrValue(t *testing.T) {
+ const token, value, number = "svc_SECRETTOKEN", "PLAINVALUE42", "987654321987"
+ for _, status := range []int{200, 400, 401, 404, 409, 412, 500, 503} {
+ srv, _ := rawConsole(t, func(w http.ResponseWriter, r *http.Request) {
+ if status == 200 {
+ // Unreadable: a number where a door expects a string, list
+ // or object, and a value where a time belongs (the time
+ // parser's error quotes it).
+ w.Header().Set("Content-Type", "application/json")
+ _, _ = io.WriteString(w, `{"bundle":`+number+`,"host":"oficina-docs.bds.oncarlos.com","created_at":"`+value+`","instances":`+number+`,"scope":`+number+`,"receipt":`+number+`}`)
+ return
+ }
+ writeJSON(w, status, map[string]any{"error": "refused " + token + " " + value, "version": value})
+ })
+ c := carlosop.New(srv.URL, acct, []byte(token))
+ var errs []error
+ _, err := c.Config(ctx, "docs", "")
+ errs = append(errs, err)
+ _, err = c.Effective(ctx, "docs", "oficina-docs.bds.oncarlos.com")
+ errs = append(errs, err)
+ _, err = c.Put(ctx, "docs", carlosop.PutRequest{Set: map[string]string{"DOCS_AGENT_TEAM": value}, IfVersion: v1})
+ errs = append(errs, err)
+ _, err = c.Instances(ctx, "docs")
+ errs = append(errs, err)
+ _, err = c.Instance(ctx, "docs", "oficina-docs.bds.oncarlos.com")
+ errs = append(errs, err)
+ _, err = c.RestartHost(ctx, "docs", "oficina-docs.bds.oncarlos.com", true)
+ errs = append(errs, err)
+ c.Close()
+ for i, err := range errs {
+ if err == nil {
+ t.Fatalf("status %d call %d: no error", status, i)
+ }
+ if s := err.Error(); strings.Contains(s, token) || strings.Contains(s, value) || strings.Contains(s, number) {
+ t.Fatalf("status %d call %d: error carries the token or a value", status, i)
+ }
+ }
+ }
+ // A transport failure, too: the token is never in a URL.
+ c := carlosop.New("http://127.0.0.1:1", acct, []byte(token))
+ defer c.Close()
+ if _, err := c.Config(ctx, "docs", ""); err == nil || strings.Contains(err.Error(), token) {
+ t.Fatalf("transport failure: %v", err != nil)
+ }
+}
+
+func TestTokenZeroedOnClose(t *testing.T) {
+ srv, log := rawConsole(t, func(w http.ResponseWriter, r *http.Request) {
+ writeJSON(w, 200, map[string]any{"bundle": "default", "version": "none", "vars": []any{}})
+ })
+ tok := []byte("svc_zero_me")
+ c := carlosop.New(srv.URL, acct, tok)
+ if _, err := c.Config(ctx, "docs", ""); err != nil {
+ t.Fatalf("Config: %v", err)
+ }
+ c.Close()
+ for _, b := range tok {
+ if b != 0 {
+ t.Fatalf("Close left the token in memory")
+ }
+ }
+ // Refused as closed, not merely failed on a zeroed header.
+ if _, err := c.Config(ctx, "docs", ""); err == nil || !strings.Contains(err.Error(), "closed") {
+ t.Fatalf("a closed client was not refused as closed: %v", err)
+ }
+ if len(*log) != 1 {
+ t.Fatalf("a closed client sent a request")
+ }
+ c.Close() // idempotent
+}
+
+func TestPlainHTTPOnlyToLoopback(t *testing.T) {
+ c := carlosop.New("http://192.0.2.1", acct, []byte("svc_token"))
+ defer c.Close()
+ done := make(chan error, 1)
+ go func() { _, err := c.Config(ctx, "docs", ""); done <- err }()
+ select {
+ case err := <-done:
+ // The refusal names https; a dial error would not.
+ if err == nil || !strings.Contains(err.Error(), "https") {
+ t.Fatalf("plain http to a non-loopback console was not refused before dialling: %v", err)
+ }
+ case <-time.After(2 * time.Second):
+ t.Fatalf("the client dialled a plain-http console")
+ }
+}
+
+func TestReadsRefuseMalformedAnswers(t *testing.T) {
+ host := "oficina-docs.bds.oncarlos.com"
+ config := func(c *carlosop.Client) error { _, err := c.Config(ctx, "docs", ""); return err }
+ effective := func(c *carlosop.Client) error { _, err := c.Effective(ctx, "docs", host); return err }
+ instances := func(c *carlosop.Client) error { _, err := c.Instances(ctx, "docs"); return err }
+ instance := func(c *carlosop.Client) error { _, err := c.Instance(ctx, "docs", host); return err }
+ restart := func(c *carlosop.Client) error { _, err := c.RestartHost(ctx, "docs", host, true); return err }
+ put := func(c *carlosop.Client) error {
+ _, err := c.Put(ctx, "docs", carlosop.PutRequest{Set: map[string]string{"K": "v"}, IfVersion: v1})
+ return err
+ }
+ receipt := map[string]any{"bundle": "default", "version_before": v1, "version_after": v2, "changed": true,
+ "set": []string{"K"}, "unset": []string{}, "unset_absent": []string{}, "digests": map[string]string{"K": d1}}
+ layers := map[string]any{"default": map[string]any{"version": v1}, "overlay": map[string]any{"version": "none"}}
+ cases := []struct {
+ name string
+ call func(*carlosop.Client) error
+ answer any
+ }{
+ {"bad version", config, map[string]any{"bundle": "default", "version": "cv1:abc", "vars": []any{}}},
+ {"bad digest", config, map[string]any{"bundle": "default", "version": v1, "vars": []any{map[string]any{"key": "A", "kind": "env", "value": "x", "digest": "vd1:XYZ"}}}},
+ {"secret value", config, map[string]any{"bundle": "default", "version": v1, "vars": []any{map[string]any{"key": "A", "kind": "secret", "value": "x", "digest": d1}}}},
+ {"other bundle", config, map[string]any{"bundle": "beta", "version": v1, "vars": []any{}}},
+ {"effective other host", effective, map[string]any{"host": "x.bds.oncarlos.com", "layers": layers, "vars": []any{}}},
+ {"effective from unlisted layer", effective, map[string]any{"host": host, "layers": layers, "vars": []any{map[string]any{"key": "A", "kind": "env", "digest": d1, "from": "environment", "shadows": []string{}}}}},
+ {"truncated list", instances, map[string]any{"instances": []any{}, "truncated": true}},
+ {"list row of another app", instances, map[string]any{"instances": []any{map[string]any{"host": host, "app": "sheets", "account": acct}}}},
+ {"record of another account", instance, map[string]any{"host": host, "app": "docs", "account": "zzz"}},
+ {"restart of the whole app", restart, map[string]any{"scope": map[string]any{"kind": "app", "value": ""}, "dry_run": true, "routes": []any{}}},
+ {"put with no receipt", put, map[string]any{"result": "ok", "removed": 0}},
+ {"put receipt for another bundle", put, map[string]any{"result": "ok", "receipt": func() map[string]any {
+ r := maps.Clone(receipt)
+ r["bundle"] = "beta"
+ return r
+ }()}},
+ {"restart requested on a dry run", restart, map[string]any{"scope": map[string]any{"kind": "host", "value": host}, "dry_run": true, "requested": true, "routes": []any{}}},
+ }
+ for _, tc := range cases {
+ srv, _ := rawConsole(t, func(w http.ResponseWriter, r *http.Request) { writeJSON(w, 200, tc.answer) })
+ c := carlosop.New(srv.URL, acct, []byte("svc_token"))
+ if err := tc.call(c); err == nil {
+ t.Fatalf("%s: accepted", tc.name)
+ }
+ c.Close()
+ }
+}
+
+func TestEffectiveShowsLayersAndShadows(t *testing.T) {
+ f, c := newFake(t)
+ host := canonical(f, "docs")
+ bound := "beta-docs." + acct + ".oncarlos.com"
+ f.AddInstance(carlosop.Instance{Host: bound, Account: acct, App: "docs", Environment: "beta"})
+ f.SetVar("docs", "", "LOG_LEVEL", "info")
+ f.SetVar("docs", "", "SHARED", "d")
+ f.SetSecret("docs", "", "DOCS_DEK")
+ f.SetVar("docs", "beta", "SHARED", "e")
+ f.SetOverlay("docs", bound, "SHARED", "o")
+
+ e, err := c.Effective(ctx, "docs", host)
+ if err != nil {
+ t.Fatalf("Effective: %v", err)
+ }
+ if e.Host != host || e.Environment != "" || e.Owned || e.Layers["default"] == "" || e.Layers["overlay"] != "none" || len(e.Vars) != 3 {
+ t.Fatalf("default-bound effective view wrong: %+v", e.Layers)
+ }
+ e, err = c.Effective(ctx, "docs", bound)
+ if err != nil {
+ t.Fatalf("Effective: %v", err)
+ }
+ var shared carlosop.EffectiveVar
+ for _, v := range e.Vars {
+ if v.Key == "SHARED" {
+ shared = v
+ }
+ }
+ if e.Environment != "beta" || shared.From != "overlay" || !slices.Equal(shared.Shadows, []string{"environment", "default"}) {
+ t.Fatalf("overlay did not shadow environment and default: from %q shadows %v", shared.From, shared.Shadows)
+ }
+
+ f.Own("docs", "beta", "alta")
+ e, _ = c.Effective(ctx, "docs", bound)
+ if _, ok := e.Layers["default"]; !e.Owned || ok || len(e.Vars) != 1 {
+ t.Fatalf("an owned environment folded the default in")
+ }
+ if _, err := c.Effective(ctx, "docs", "nope.bds.oncarlos.com"); !errors.Is(err, carlosop.ErrNotFound) {
+ t.Fatalf("unknown host: want ErrNotFound, got %v", err)
+ }
+}
+
+func TestInstancesFollowsCursor(t *testing.T) {
+ f, c := newFake(t)
+ for _, h := range []string{"a", "b", "c", "d", "e"} {
+ f.AddInstance(carlosop.Instance{Host: h + "-docs.bds.oncarlos.com", Account: acct, App: "docs"})
+ }
+ f.AddInstance(carlosop.Instance{Host: "x-sheets.bds.oncarlos.com", Account: acct, App: "sheets"})
+ f.PageSize = 2
+ got, err := c.Instances(ctx, "docs")
+ if err != nil || len(got) != 5 {
+ t.Fatalf("Instances: %d, %v", len(got), err)
+ }
+ host := canonical(f, "docs")
+ in, err := c.Instance(ctx, "docs", host)
+ if err != nil || in.Slug != "s-docs" || in.PublicHost != "docs.oficina.works" || in.RecordSeq != 3 || in.Move != nil {
+ t.Fatalf("Instance not decoded: %v", err)
+ }
+ if _, err := c.Instance(ctx, "docs", "nope.bds.oncarlos.com"); !errors.Is(err, carlosop.ErrNotFound) {
+ t.Fatalf("unknown host: want ErrNotFound, got %v", err)
+ }
+}
+
+func TestFakeLostAnswerLandsAndResealMovesDigest(t *testing.T) {
+ f, c := newFake(t)
+ f.SetSecret("docs", "", "DOCS_DEK")
+ before, _ := c.Config(ctx, "docs", "")
+ f.SetSecret("docs", "", "DOCS_DEK")
+ after, _ := c.Config(ctx, "docs", "")
+ if before.Vars[0].Digest == after.Vars[0].Digest || before.Version == after.Version || after.Vars[0].Value != "" {
+ t.Fatalf("a reseal did not move the digest and version, or showed a value")
+ }
+ f.LoseNextAnswer()
+ if _, err := c.Put(ctx, "docs", carlosop.PutRequest{Set: map[string]string{"DOCS_AGENT_TEAM": "tsqid"}, IfVersion: after.Version}); err == nil {
+ t.Fatalf("a lost answer read as success")
+ }
+ vars, _, _ := f.Layer("docs", "")
+ if fakecarlos.Digest(vars["DOCS_AGENT_TEAM"]) != carlosop.EnvDigest("tsqid") {
+ t.Fatalf("the write behind a lost answer did not land")
+ }
+}
diff --git a/carlosop/digest.go b/carlosop/digest.go
new file mode 100644
index 0000000..8246463
--- /dev/null
+++ b/carlosop/digest.go
@@ -0,0 +1,39 @@
+package carlosop
+
+import (
+ "crypto/sha256"
+ "encoding/hex"
+ "regexp"
+)
+
+// EnvDigest is carlos/platform 522's `vd1:` digest (spec §4.3) of a plain
+// var holding value: SHA-256 over the four stored fields of a var, kind
+// "env", the value, and an empty envelope and sealed-to fingerprint,
+// NUL-separated under the scheme's domain string.
+//
+// It is applied only to the two agent keys' values, which the runner itself
+// sends. Never to a secret: a secret's digest is over its envelope, and the
+// runner never holds a secret's plaintext. Like the value, the result is not
+// to be printed or logged.
+func EnvDigest(value string) string {
+ h := sha256.New()
+ for i, f := range []string{"carlos.config.var.v1", "env", value, "", ""} {
+ if i > 0 {
+ h.Write([]byte{0})
+ }
+ h.Write([]byte(f))
+ }
+ return "vd1:" + hex.EncodeToString(h.Sum(nil))
+}
+
+var (
+ versionShape = regexp.MustCompile(`^cv1:[0-9a-f]{64}$`)
+ digestShape = regexp.MustCompile(`^vd1:[0-9a-f]{64}$`)
+)
+
+// validVersion admits a 522 layer version: "none" for an absent layer, or
+// "cv1:" and 64 lowercase hex.
+func validVersion(v string) bool { return v == "none" || versionShape.MatchString(v) }
+
+// validDigest admits a 522 var digest: "vd1:" and 64 lowercase hex.
+func validDigest(d string) bool { return digestShape.MatchString(d) }
diff --git a/carlosop/digest_test.go b/carlosop/digest_test.go
new file mode 100644
index 0000000..9799303
--- /dev/null
+++ b/carlosop/digest_test.go
@@ -0,0 +1,14 @@
+package carlosop
+
+import "testing"
+
+// The golden value is carlos/platform internal/appconfig TestDigestPinned's
+// vector, Digest(Var{Kind: "env", Value: "info"}), at config-receipts-1 head
+// c5d5a930048e14657ca51205eb4cf46e50978726 (522 Plan 1, not yet merged).
+// Re-pin to the merge commit once 522 Plan 1 lands on platform main.
+func TestEnvDigestMatchesPlatformVector(t *testing.T) {
+ const want = "vd1:3c7b54021558dfc18bc509a47f6103bb9f4942be75c7ca3d23483c89664375e2"
+ if got := EnvDigest("info"); got != want {
+ t.Fatalf("EnvDigest(info) does not match the platform's pinned vector")
+ }
+}
diff --git a/carlosop/fakecarlos/fakecarlos.go b/carlosop/fakecarlos/fakecarlos.go
new file mode 100644
index 0000000..cde85f2
--- /dev/null
+++ b/carlosop/fakecarlos/fakecarlos.go
@@ -0,0 +1,678 @@
+// Package fakecarlos is an in-memory CARLOS console as an account's Admin
+// credential meets it through carlos/platform 522 Plan 1 (config-receipts
+// design §4) and the narrowed restart door (internal/console/
+// apirestartscope.go). It keeps each app's layers as stored bytes, so a
+// layer's `cv1:` version is a hash of exactly what is stored and a var's
+// `vd1:` digest is §4.3's, a secret's over its envelope:
+//
+// - the default bundle, apps/<acct>/<app>/config.json;
+// - named environments, standalone when owned by a scope;
+// - per-host instance overlays, written by the platform only.
+//
+// A host resolves default, then its environment, then its overlay; an
+// owned environment never folds the default in. Instance records are the
+// routes the restart door resolves.
+//
+// Hooks for adverse tests: BeforePut, LoseNextAnswer, SetSecret,
+// PlatformWrite, NoConditional, FailRestart, NoScopedRestart, and the
+// counters RestartCount and AppWideRestarts.
+package fakecarlos
+
+import (
+ "bytes"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "encoding/json"
+ "io"
+ "net/http"
+ "net/http/httptest"
+ "regexp"
+ "sort"
+ "strconv"
+ "strings"
+ "sync"
+
+ "amadan.net/oficina/alta/carlosop"
+)
+
+// Var is one stored var, the four fields 522's digest covers.
+type Var struct {
+ Kind string `json:"kind"`
+ Value string `json:"value,omitempty"`
+ Envelope string `json:"envelope,omitempty"`
+ SealedTo string `json:"sealed_to,omitempty"`
+}
+
+// manifest is a stored layer's shape. It marshals deterministically
+// (MarshalIndent sorts map keys), as the platform's does.
+type manifest struct {
+ Schema int `json:"schema"`
+ App string `json:"app"`
+ OwnerScope string `json:"owner_scope,omitempty"`
+ Vars map[string]Var `json:"vars"`
+}
+
+type app struct {
+ def []byte // nil: absent
+ envs map[string][]byte // name -> stored bytes
+ overlays map[string][]byte // host -> stored bytes
+ recs map[string]carlosop.Instance
+}
+
+// Fake is the console.
+type Fake struct {
+ mu sync.Mutex
+ account string
+ token string
+ apps map[string]*app
+ srv *httptest.Server
+
+ // BeforePut runs on each PUT /config before the door reads the layer,
+ // outside the fake's lock, so it may call PlatformWrite or SetSecret:
+ // a platform writer landing between the caller's read and the write.
+ BeforePut func(app string)
+ // PageSize, when set, pages GET /instances by that many rows.
+ PageSize int
+
+ lose bool
+ noCond bool
+ noScope bool
+ failRestart int
+ restarts map[string]int
+ appWide int
+ requests []string
+}
+
+// New builds a console for account (a sqid) with one Admin token.
+func New(account string) *Fake {
+ b := make([]byte, 24)
+ _, _ = rand.Read(b)
+ f := &Fake{account: account, token: "svc_" + base64.RawURLEncoding.EncodeToString(b), apps: map[string]*app{}, restarts: map[string]int{}}
+ f.srv = httptest.NewServer(http.HandlerFunc(f.serve))
+ return f
+}
+
+func (f *Fake) Close() { f.srv.Close() }
+func (f *Fake) URL() string { return f.srv.URL }
+
+// Token is a fresh copy of the Admin token, for carlosop.New (which zeroes
+// what it is given on Close).
+func (f *Fake) Token() []byte { return []byte(f.token) }
+
+func (f *Fake) app(name string) *app {
+ a := f.apps[name]
+ if a == nil {
+ a = &app{envs: map[string][]byte{}, overlays: map[string][]byte{}, recs: map[string]carlosop.Instance{}}
+ f.apps[name] = a
+ }
+ return a
+}
+
+func decode(raw []byte, appName string) manifest {
+ m := manifest{Schema: 1, App: appName}
+ if raw != nil {
+ _ = json.Unmarshal(raw, &m)
+ }
+ if m.Vars == nil {
+ m.Vars = map[string]Var{}
+ }
+ return m
+}
+
+func encode(m manifest) []byte {
+ b, _ := json.MarshalIndent(m, "", " ")
+ return b
+}
+
+// Version is 522's cv1: over the stored bytes; "none" for an absent layer.
+func Version(raw []byte) string {
+ if raw == nil {
+ return "none"
+ }
+ s := sha256.Sum256(raw)
+ return "cv1:" + hex.EncodeToString(s[:])
+}
+
+// Digest is 522 §4.3's vd1: over a var's four stored fields.
+func Digest(v Var) string {
+ h := sha256.New()
+ for i, s := range []string{"carlos.config.var.v1", v.Kind, v.Value, v.Envelope, v.SealedTo} {
+ if i > 0 {
+ h.Write([]byte{0})
+ }
+ h.Write([]byte(s))
+ }
+ return "vd1:" + hex.EncodeToString(h.Sum(nil))
+}
+
+// layer is the stored bytes of env ("" = default); nil when absent.
+func (a *app) layer(env string) []byte {
+ if env == "" {
+ return a.def
+ }
+ return a.envs[env]
+}
+
+func (a *app) store(env string, raw []byte) {
+ if env == "" {
+ a.def = raw
+ } else {
+ a.envs[env] = raw
+ }
+}
+
+func (f *Fake) write(appName, env, key string, v Var) {
+ a := f.app(appName)
+ m := decode(a.layer(env), appName)
+ m.Vars[key] = v
+ a.store(env, encode(m))
+}
+
+// SetVar seeds a plain var into a bundle (env "" = default), creating it.
+func (f *Fake) SetVar(appName, env, key, value string) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.write(appName, env, key, Var{Kind: "env", Value: value})
+}
+
+// PlatformWrite is a platform writer (mail, relay, scan, storage) setting
+// a plain var in a bundle: it moves the bundle's version like any write.
+func (f *Fake) PlatformWrite(appName, env, key, value string) { f.SetVar(appName, env, key, value) }
+
+// SetSecret seals key afresh into a bundle: a new random envelope, so a
+// new digest, whatever the plaintext. The fake holds no plaintext.
+func (f *Fake) SetSecret(appName, env, key string) {
+ b := make([]byte, 32)
+ _, _ = rand.Read(b)
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.write(appName, env, key, Var{Kind: "secret", Envelope: base64.StdEncoding.EncodeToString(b), SealedTo: "fp-test"})
+}
+
+// Unset removes key from a bundle, as a person's or a platform's write.
+func (f *Fake) Unset(appName, env, key string) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ a := f.app(appName)
+ m := decode(a.layer(env), appName)
+ delete(m.Vars, key)
+ a.store(env, encode(m))
+}
+
+// Own marks a named environment as owned by scope: standalone, never
+// folding the default in. Creates it if absent.
+func (f *Fake) Own(appName, env, scope string) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ a := f.app(appName)
+ m := decode(a.layer(env), appName)
+ m.OwnerScope = scope
+ a.store(env, encode(m))
+}
+
+// SetOverlay is the platform's instance overlay for host.
+func (f *Fake) SetOverlay(appName, host, key, value string) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ a := f.app(appName)
+ m := decode(a.overlays[host], appName)
+ m.Vars[key] = Var{Kind: "env", Value: value}
+ a.overlays[host] = encode(m)
+}
+
+// AddInstance stores a record; in.App names the app, and the record is
+// one route of it on this console's box.
+func (f *Fake) AddInstance(in carlosop.Instance) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ if in.Account == "" {
+ in.Account = f.account
+ }
+ f.app(in.App).recs[in.Host] = in
+}
+
+// Layer is a copy of a bundle's vars and its version; ok is false when the
+// bundle is absent.
+func (f *Fake) Layer(appName, env string) (map[string]Var, string, bool) {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ raw := f.app(appName).layer(env)
+ m := decode(raw, appName)
+ return m.Vars, Version(raw), raw != nil
+}
+
+// LoseNextAnswer applies the next PUT /config and then drops the
+// connection without an answer.
+func (f *Fake) LoseNextAnswer() { f.mu.Lock(); f.lose = true; f.mu.Unlock() }
+
+// NoConditional makes the console one whose store has no atomic
+// conditional write: if_version is refused with 400 before any read.
+func (f *Fake) NoConditional() { f.mu.Lock(); f.noCond = true; f.mu.Unlock() }
+
+// NoScopedRestart makes the console predate the narrowed restart door:
+// POST /restart/scope is a 404.
+func (f *Fake) NoScopedRestart() { f.mu.Lock(); f.noScope = true; f.mu.Unlock() }
+
+// FailRestart makes every POST /restart/scope answer status, with nothing
+// restarted; 0 restores it.
+func (f *Fake) FailRestart(status int) { f.mu.Lock(); f.failRestart = status; f.mu.Unlock() }
+
+// RestartCount is how many narrowed restarts were requested for host.
+func (f *Fake) RestartCount(host string) int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.restarts[host]
+}
+
+// AppWideRestarts is how many times the app-wide POST /restart was called.
+func (f *Fake) AppWideRestarts() int {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return f.appWide
+}
+
+// Requests is every authenticated request as "METHOD /door", in order.
+func (f *Fake) Requests() []string {
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ return append([]string{}, f.requests...)
+}
+
+// ---- the doors ----
+
+var pathRE = regexp.MustCompile(`^/api/cli/apps/([^/]+)/([^/]+)(/.*)$`)
+
+func writeJSON(w http.ResponseWriter, status int, v any) {
+ w.Header().Set("Content-Type", "application/json")
+ w.WriteHeader(status)
+ _ = json.NewEncoder(w).Encode(v)
+}
+
+func refuse(w http.ResponseWriter, status int, msg string) {
+ writeJSON(w, status, map[string]string{"error": msg})
+}
+
+func (f *Fake) serve(w http.ResponseWriter, r *http.Request) {
+ m := pathRE.FindStringSubmatch(r.URL.Path)
+ if m == nil {
+ http.NotFound(w, r)
+ return
+ }
+ account, appName, rest := m[1], m[2], m[3]
+ if r.Header.Get("Authorization") != "Bearer "+f.token {
+ refuse(w, 401, "not signed in")
+ return
+ }
+ door := rest
+ if strings.HasPrefix(rest, "/instances/") {
+ door = "/instances/{host}"
+ }
+ if r.Method == http.MethodPut && rest == "/config" && f.BeforePut != nil {
+ f.BeforePut(appName)
+ }
+ f.mu.Lock()
+ defer f.mu.Unlock()
+ f.requests = append(f.requests, r.Method+" "+door)
+ a := f.apps[appName]
+ if account != f.account || a == nil {
+ http.NotFound(w, r)
+ return
+ }
+ raw, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20))
+ switch {
+ case r.Method == http.MethodGet && rest == "/config":
+ f.getConfig(w, r, appName, a)
+ case r.Method == http.MethodGet && rest == "/config/effective":
+ f.effective(w, r, appName, a)
+ case r.Method == http.MethodPut && rest == "/config":
+ f.putConfig(w, r, appName, a, raw)
+ case r.Method == http.MethodGet && rest == "/instances":
+ f.list(w, r, a)
+ case r.Method == http.MethodGet && strings.HasPrefix(rest, "/instances/"):
+ in, ok := a.recs[strings.TrimPrefix(rest, "/instances/")]
+ if !ok {
+ http.NotFound(w, r)
+ return
+ }
+ writeJSON(w, 200, record(in))
+ case r.Method == http.MethodPost && rest == "/restart/scope":
+ f.restartScope(w, r, appName, a, raw)
+ case r.Method == http.MethodPost && rest == "/restart":
+ // The app-wide door: counted, so a test can assert it is never
+ // called.
+ f.appWide++
+ writeJSON(w, 200, map[string]any{"result": "requested"})
+ default:
+ refuse(w, 405, "not a door this fake serves")
+ }
+}
+
+func record(in carlosop.Instance) map[string]any {
+ out := map[string]any{"schema": 1, "host": in.Host, "slug": in.Slug, "app": in.App, "account": in.Account,
+ "channel": in.Channel, "created_at": in.CreatedAt, "gated": false}
+ for k, v := range map[string]string{"public_host": in.PublicHost, "environment": in.Environment, "region": in.Region} {
+ if v != "" {
+ out[k] = v
+ }
+ }
+ if in.RecordSeq != 0 {
+ out["record_seq"] = in.RecordSeq
+ }
+ for k, v := range map[string]json.RawMessage{"move": in.Move, "replica_assignment": in.ReplicaAssignment, "seed": in.Seed} {
+ if len(v) > 0 {
+ out[k] = v
+ }
+ }
+ return out
+}
+
+func varRows(m manifest) []map[string]any {
+ keys := make([]string, 0, len(m.Vars))
+ for k := range m.Vars {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ rows := make([]map[string]any, 0, len(keys))
+ for _, k := range keys {
+ v := m.Vars[k]
+ row := map[string]any{"key": k, "kind": v.Kind, "digest": Digest(v)}
+ if v.Kind == "env" {
+ row["value"] = v.Value
+ }
+ rows = append(rows, row)
+ }
+ return rows
+}
+
+func bundleName(env string) string {
+ if env == "" {
+ return "default"
+ }
+ return env
+}
+
+func (f *Fake) getConfig(w http.ResponseWriter, r *http.Request, appName string, a *app) {
+ env := strings.TrimSpace(r.URL.Query().Get("environment"))
+ raw := a.layer(env)
+ envs := make([]string, 0, len(a.envs))
+ for n := range a.envs {
+ envs = append(envs, n)
+ }
+ sort.Strings(envs)
+ writeJSON(w, 200, map[string]any{"bundle": bundleName(env), "version": Version(raw), "environments": envs, "vars": varRows(decode(raw, appName))})
+}
+
+func (f *Fake) effective(w http.ResponseWriter, r *http.Request, appName string, a *app) {
+ host := strings.TrimSpace(r.URL.Query().Get("host"))
+ if host == "" {
+ refuse(w, 400, "host is required")
+ return
+ }
+ rec, ok := a.recs[host]
+ if !ok {
+ http.NotFound(w, r)
+ return
+ }
+ envName := rec.Environment
+ envRaw := a.layer(envName)
+ if envName != "" && envRaw == nil {
+ // The box renders nothing for a route bound to an environment
+ // that was never created; the platform refuses the view.
+ refuse(w, 502, "could not read the config — try again")
+ return
+ }
+ def, env, ov := decode(a.def, appName), decode(envRaw, appName), decode(a.overlays[host], appName)
+ owned := envName != "" && env.OwnerScope != ""
+ type source struct {
+ name string
+ m manifest
+ }
+ var order []source // highest first
+ if a.overlays[host] != nil {
+ order = append(order, source{"overlay", ov})
+ }
+ if envName != "" {
+ order = append(order, source{"environment", env})
+ }
+ if !owned && a.def != nil {
+ order = append(order, source{"default", def})
+ }
+ merged := map[string]Var{}
+ for i := len(order) - 1; i >= 0; i-- {
+ for k, v := range order[i].m.Vars {
+ merged[k] = v
+ }
+ }
+ keys := make([]string, 0, len(merged))
+ for k := range merged {
+ keys = append(keys, k)
+ }
+ sort.Strings(keys)
+ vars := make([]map[string]any, 0, len(keys))
+ for _, k := range keys {
+ v := merged[k]
+ from, shadows := "", []string{}
+ for _, s := range order {
+ if _, ok := s.m.Vars[k]; !ok {
+ continue
+ }
+ if from == "" {
+ from = s.name
+ } else {
+ shadows = append(shadows, s.name)
+ }
+ }
+ row := map[string]any{"key": k, "kind": v.Kind, "digest": Digest(v), "from": from, "shadows": shadows}
+ if v.Kind == "env" && from != "overlay" {
+ row["value"] = v.Value
+ }
+ vars = append(vars, row)
+ }
+ layers := map[string]any{"overlay": map[string]any{"version": Version(a.overlays[host])}}
+ if !owned {
+ layers["default"] = map[string]any{"version": Version(a.def)}
+ }
+ if envName != "" {
+ layers["environment"] = map[string]any{"name": envName, "version": Version(envRaw)}
+ }
+ writeJSON(w, 200, map[string]any{"host": host, "environment": envName, "owned": owned, "layers": layers, "vars": vars})
+}
+
+func (f *Fake) putConfig(w http.ResponseWriter, r *http.Request, appName string, a *app, raw []byte) {
+ if len(r.Header.Values("If-Match")) > 0 {
+ refuse(w, 400, "this request takes if_version in the body, not an If-Match header")
+ return
+ }
+ var req struct {
+ Environment string `json:"environment"`
+ Set map[string]Var `json:"set"`
+ Unset []string `json:"unset"`
+ ExecDelivery *string `json:"exec_delivery"`
+ }
+ var members map[string]json.RawMessage
+ if json.Unmarshal(raw, &req) != nil || json.Unmarshal(raw, &members) != nil {
+ refuse(w, 400, "malformed JSON body")
+ return
+ }
+ if len(req.Set) == 0 && len(req.Unset) == 0 && req.ExecDelivery == nil {
+ refuse(w, 400, "nothing to do — send set, unset or exec_delivery")
+ return
+ }
+ ifVersion := ""
+ conditional := false
+ if m, ok := members["if_version"]; ok {
+ conditional = true
+ if json.Unmarshal(m, &ifVersion) != nil || strings.TrimSpace(ifVersion) == "" {
+ refuse(w, 400, "if_version must be a version string")
+ return
+ }
+ }
+ if conditional {
+ switch {
+ case f.noCond:
+ refuse(w, 400, "conditional writes need a store that supports them")
+ return
+ case req.ExecDelivery != nil:
+ refuse(w, 400, "if_version cannot cover exec_delivery. send exec_delivery in a request of its own")
+ return
+ }
+ for _, k := range req.Unset {
+ if _, both := req.Set[k]; both {
+ refuse(w, 400, k+" is in both set and unset")
+ return
+ }
+ }
+ }
+ env := req.Environment
+ before := a.layer(env)
+ if conditional && Version(before) != ifVersion {
+ writeJSON(w, http.StatusPreconditionFailed, map[string]any{
+ "error": "the bundle is not at the version you sent, so nothing was written. read it again before you retry",
+ "version": Version(before)})
+ return
+ }
+ defBefore := Version(a.def)
+ m := decode(before, appName)
+ rc := map[string]any{"bundle": bundleName(env), "version_before": Version(before)}
+ set, unset, absent, digests := []string{}, []string{}, []string{}, map[string]string{}
+ seen := map[string]bool{}
+ for _, k := range req.Unset {
+ if seen[k] {
+ continue
+ }
+ seen[k] = true
+ if _, ok := m.Vars[k]; ok {
+ delete(m.Vars, k)
+ unset = append(unset, k)
+ } else {
+ absent = append(absent, k)
+ }
+ }
+ for k, v := range req.Set {
+ m.Vars[k] = v
+ set = append(set, k)
+ digests[k] = Digest(v)
+ }
+ sort.Strings(set)
+ sort.Strings(unset)
+ sort.Strings(absent)
+ after := encode(m)
+ a.store(env, after)
+ rc["version_after"] = Version(after)
+ rc["changed"] = Version(before) != Version(after)
+ rc["set"], rc["unset"], rc["unset_absent"], rc["digests"] = set, unset, absent, digests
+ if env != "" && m.OwnerScope == "" {
+ rc["others"] = map[string]any{"default": map[string]string{"before": defBefore, "after": Version(a.def)}}
+ }
+ if f.lose {
+ f.lose = false
+ if hj, ok := w.(http.Hijacker); ok {
+ if conn, _, err := hj.Hijack(); err == nil {
+ _ = conn.Close()
+ return
+ }
+ }
+ }
+ writeJSON(w, 200, map[string]any{"result": "ok", "removed": len(unset), "receipt": rc})
+}
+
+func (f *Fake) list(w http.ResponseWriter, r *http.Request, a *app) {
+ hosts := make([]string, 0, len(a.recs))
+ for h := range a.recs {
+ hosts = append(hosts, h)
+ }
+ sort.Strings(hosts)
+ start := 0
+ if c := r.URL.Query().Get("cursor"); c != "" {
+ n, err := strconv.Atoi(c)
+ if err != nil || n < 0 || n > len(hosts) {
+ refuse(w, 400, "bad cursor")
+ return
+ }
+ start = n
+ }
+ end, next := len(hosts), ""
+ if f.PageSize > 0 && start+f.PageSize < len(hosts) {
+ end = start + f.PageSize
+ next = strconv.Itoa(end)
+ }
+ rows := make([]map[string]any, 0, end-start)
+ for _, h := range hosts[start:end] {
+ rows = append(rows, record(a.recs[h]))
+ }
+ writeJSON(w, 200, map[string]any{"instances": rows, "truncated": false, "total": len(hosts), "next_cursor": next})
+}
+
+func (f *Fake) restartScope(w http.ResponseWriter, r *http.Request, appName string, a *app, raw []byte) {
+ if f.noScope {
+ http.NotFound(w, r)
+ return
+ }
+ if f.failRestart != 0 {
+ refuse(w, f.failRestart, "restart refused")
+ return
+ }
+ var req struct {
+ Host string `json:"host"`
+ Environment string `json:"environment"`
+ DryRun bool `json:"dry_run"`
+ Message string `json:"message"`
+ }
+ dec := json.NewDecoder(bytes.NewReader(raw))
+ dec.DisallowUnknownFields() // the door is strict: a misspelt selector must not read as none
+ if len(raw) > 0 && dec.Decode(&req) != nil {
+ refuse(w, 400, "malformed or unknown field")
+ return
+ }
+ host, envName := strings.TrimSpace(req.Host), strings.TrimSpace(req.Environment)
+ var routes []carlosop.Instance
+ kind, value := "app", ""
+ switch {
+ case host != "":
+ rec, ok := a.recs[host]
+ if !ok {
+ refuse(w, 400, "no route "+host+" on this app")
+ return
+ }
+ if envName != "" && rec.Environment != envName {
+ refuse(w, 400, "one of --host and --environment is a typo, so nothing was cycled")
+ return
+ }
+ kind, value, routes = "host", host, []carlosop.Instance{rec}
+ case envName != "":
+ for _, rec := range a.recs {
+ if rec.Environment == envName {
+ routes = append(routes, rec)
+ }
+ }
+ if len(routes) == 0 {
+ refuse(w, 400, "no route of this app reads environment "+envName)
+ return
+ }
+ kind, value = "environment", envName
+ default:
+ for _, rec := range a.recs {
+ routes = append(routes, rec)
+ }
+ }
+ if kind == "app" && !req.DryRun {
+ refuse(w, 400, "this door only narrows a restart")
+ return
+ }
+ sort.Slice(routes, func(i, j int) bool { return routes[i].Host < routes[j].Host })
+ rows := make([]map[string]any, 0, len(routes))
+ for _, rt := range routes {
+ rows = append(rows, map[string]any{"host": rt.Host, "environment": rt.Environment, "hibernate": false})
+ }
+ answer := map[string]any{"account": f.account, "app": appName, "scope": map[string]string{"kind": kind, "value": value},
+ "dry_run": req.DryRun, "requested": false, "routes": rows}
+ if !req.DryRun {
+ for _, rt := range routes {
+ f.restarts[rt.Host]++
+ }
+ answer["requested"] = true
+ }
+ writeJSON(w, 200, answer)
+}