// 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///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. // // Hostname claims (AttachDomain) are listed as GET /domains lists them: // the canonical name of an app is a claim routed to one of its records, // never a field of the record. // // 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 domains map[string]domain // host -> claim } // domain is one hostname claim: host served by the record at route. type domain struct{ route, state string } // 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) // DuringDryRun runs on each dry run of POST /restart/scope, outside // the fake's lock: a change landing after the caller decided to ask. DuringDryRun func(app string) // PageSize, when set, pages GET /instances by that many rows. PageSize int lose bool noCond bool noScope bool failRestart int failRead map[string]int // door -> status 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{}, domains: map[string]domain{}} 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 } // AttachDomain claims host for appName, served by the record at route, // in state (the console's derived word: "live", "pending-dns", // "unverified" and so on). Claims are keyed by host, as the platform's // are: attaching host again re-points it. Nothing checks that route is // a record, since the platform's list does not either. func (f *Fake) AttachDomain(appName, host, route, state string) { f.mu.Lock() defer f.mu.Unlock() f.app(appName).domains[host] = domain{route: route, state: state} } // DetachDomain drops appName's claim on host. func (f *Fake) DetachDomain(appName, host string) { f.mu.Lock() defer f.mu.Unlock() delete(f.app(appName).domains, host) } // 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() } // FailRead makes every GET of door ("/domains", "/instances") answer // status. func (f *Fake) FailRead(door string, status int) { f.mu.Lock() defer f.mu.Unlock() if f.failRead == nil { f.failRead = map[string]int{} } f.failRead[door] = status } // 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) } if r.Method == http.MethodPost && rest == "/restart/scope" && f.DuringDryRun != nil { body, _ := io.ReadAll(io.LimitReader(r.Body, 1<<20)) r.Body = io.NopCloser(bytes.NewReader(body)) var q struct { DryRun bool `json:"dry_run"` } if json.Unmarshal(body, &q) == nil && q.DryRun { f.DuringDryRun(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)) if status := f.failRead[rest]; status != 0 && r.Method == http.MethodGet { refuse(w, status, "this read is failing") return } 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 && rest == "/domains": f.domainList(w, 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{"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}) } // domainList is handleAPIDomainList's answer for plain claims: host // sorted, each with the fields the platform always sends, and the // self-describing deployment block. func (f *Fake) domainList(w http.ResponseWriter, a *app) { hosts := make([]string, 0, len(a.domains)) for h := range a.domains { hosts = append(hosts, h) } sort.Strings(hosts) rows := make([]map[string]any, 0, len(hosts)) for _, h := range hosts { d := a.domains[h] status := "pending" if d.state == "live" { status = "live" } rows = append(rows, map[string]any{"host": h, "route": d.route, "status": status, "state": d.state, "wildcard": false, "catchall": false, "verified": d.state != "unverified"}) } writeJSON(w, 200, map[string]any{"domains": rows, "deployment": map[string]any{"managed_domains": true}}) } 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) }