// Package fakeconsole is an in-memory CARLOS console as a `team` // credential meets it (carlos/platform team-scoped-credentials.md ยง4): // the thirteen scoped doors Alta uses, each answering an out-of-scope // target with the unknown target's 404; owned environments created by a // team PUT; platform-managed keys refused to team writes; the mail and // relay walks minting per-environment credentials on their own cadence // (Walk); socket-backed instances only; explicit-host domain claims with // #299's state word; restart/scope; and each team instance's public // origin (/api/version, /api/team) behind Transport. package fakeconsole import ( "crypto/ecdh" "crypto/rand" "encoding/base64" "encoding/json" "fmt" "io" "net/http" "net/http/httptest" "regexp" "sort" "strings" "sync" "amadan.net/oficina/alta/console" ) // Var is a stored config variable. type Var struct { Kind, Value, Envelope string } type bundle struct { owner string vars map[string]Var } type inst struct { env, app string serving string asleep bool pending bool restarts int } type claim struct { app, route, state string polls int } // Console is the fake. type Console struct { mu sync.Mutex Account string Scope string tokens map[string]string // token -> app priv *ecdh.PrivateKey Bound bool envs map[string]map[string]*bundle // app -> env -> bundle instances map[string]*inst // host -> instance domains map[string]*claim // host -> claim // MailPrefix is each app's mail declaration; an app absent has no // mail enabled. Relay lists the apps with the relay enabled. MailPrefix map[string]string Relay map[string]bool // Submission lists the apps switched to CARLOS mail submission // (`carlos email submission on`): their owned environments get the // From variable alone, _MAIL_FROM, and no SMTP credential. Submission map[string]bool // PrivateStorage lists the apps with the private-storage policy on // (`carlos instances enable --private-storage`): an instance create // provisions its environment's own store and delivers CARLOS_STORE_* // into that environment, as CARLOS's objstore walk does. // StoreEndpoint, when set, is the deployment's endpoint. PrivateStorage map[string]bool StoreEndpoint string // Versions is what each app's build answers on /api/version, and what // a box reports serving. Versions map[string]string // DomainPolls is how many GETs a new claim answers before it is live. DomainPolls int // Roster is GET /api/team's roster word for a roster-mode app. Roster string // ServingName overrides the box's serving report per app. ServingName map[string]string // VersionAnswer overrides what an app's /api/version answers. VersionAnswer map[string]string // NoTeamProbe: the roster-mode app serves no /api/team (Docs' main // today). NoTeamProbe bool // SeededRoster is a seeded app's (Equipo, Base) roster word on its // /api/team: "" answers "ok", once its owner exists. SeededRoster string // ProbeConsumer overrides the consumer an app's /api/team names. ProbeConsumer map[string]string // ProbeMode overrides an app's probe mode: "roster" or "seeded". ProbeMode map[string]string // Requests is every request's method, door and app, for assertions. Requests []string // SecretWrites counts writes of each secret, app/env/key: a GENERATED // key written twice was regenerated. SecretWrites map[string]int minted int srv *httptest.Server } // New builds a console for account (a sqid) whose team credentials hold // scope. func New(account, scope string) *Console { priv, _ := ecdh.P256().GenerateKey(rand.Reader) c := &Console{Account: account, Scope: scope, tokens: map[string]string{}, priv: priv, envs: map[string]map[string]*bundle{}, instances: map[string]*inst{}, domains: map[string]*claim{}, MailPrefix: map[string]string{}, Relay: map[string]bool{}, Submission: map[string]bool{}, PrivateStorage: map[string]bool{}, Versions: map[string]string{}, DomainPolls: 1, Roster: "ok", SecretWrites: map[string]int{}, ServingName: map[string]string{}, VersionAnswer: map[string]string{}} c.srv = httptest.NewServer(http.HandlerFunc(c.serve)) return c } func (c *Console) Close() { c.srv.Close() } func (c *Console) URL() string { return c.srv.URL } // Mint is Paul's `carlos services create --role team --app A --scope S`. func (c *Console) Mint(app string) string { b := make([]byte, 24) _, _ = rand.Read(b) t := "svc_" + base64.RawURLEncoding.EncodeToString(b) c.mu.Lock() c.tokens[t] = app c.mu.Unlock() return t } // SecretsPub is the console's secrets_pubkey. func (c *Console) SecretsPub() string { return base64.StdEncoding.EncodeToString(c.priv.PublicKey().Bytes()) } // Open opens a stored secret, as a box would. func (c *Console) Open(app, env, key string) (string, error) { c.mu.Lock() defer c.mu.Unlock() b := c.envs[app][env] if b == nil { return "", fmt.Errorf("no env") } v, ok := b.vars[key] if !ok || v.Kind != "secret" { return "", fmt.Errorf("no secret %s", key) } acct := "" if c.Bound { acct = c.Account } p, err := console.Open(c.priv, acct, app, v.Envelope) return string(p), err } // Env returns a copy of an environment's variables. func (c *Console) Env(app, env string) (map[string]Var, string, bool) { c.mu.Lock() defer c.mu.Unlock() b := c.envs[app][env] if b == nil { return nil, "", false } out := map[string]Var{} for k, v := range b.vars { out[k] = v } return out, b.owner, true } // SetEnv seeds an environment directly (a person's write, or a fork). func (c *Console) SetEnv(app, env, owner string, vars map[string]Var) { c.mu.Lock() defer c.mu.Unlock() if c.envs[app] == nil { c.envs[app] = map[string]*bundle{} } b := &bundle{owner: owner, vars: map[string]Var{}} for k, v := range vars { b.vars[k] = v } c.envs[app][env] = b } // AddInstance seeds an instance record (a person's create or rebind). func (c *Console) AddInstance(app, host, env string) { c.mu.Lock() defer c.mu.Unlock() c.instances[host] = &inst{env: env, app: app, serving: c.Versions[app]} } // AddClaim seeds a hostname claim. func (c *Console) AddClaim(app, host, route, state string) { c.mu.Lock() defer c.mu.Unlock() c.domains[host] = &claim{app: app, route: route, state: state} } // Instance reports a record. func (c *Console) Instance(host string) (env string, restarts int, ok bool) { c.mu.Lock() defer c.mu.Unlock() i, ok := c.instances[host] if !ok { return "", 0, false } return i.env, i.restarts, true } // InstanceCount counts records. func (c *Console) InstanceCount() int { c.mu.Lock() defer c.mu.Unlock() return len(c.instances) } // Claim reports a domain claim. func (c *Console) Claim(host string) (route, state string, ok bool) { c.mu.Lock() defer c.mu.Unlock() d, ok := c.domains[host] if !ok { return "", "", false } return d.route, d.state, true } // PlatformCanary marks every value the walks mint: a test scans Alta's // database for it. const PlatformCanary = "PLATFORM-VALUE-CANARY" // Walk is one pass of the mail and relay walks: every owned environment // of an app with mail declared gets its own SMTP credential under the // declared prefix, or, for an app switched to submission, only the From // variable for that prefix (CARLOS's DeliverMailFromIn); and Calls its // own relay identity. Never shared with the default bundle; never written // by a team credential. func (c *Console) Walk() { c.mu.Lock() defer c.mu.Unlock() for app, envs := range c.envs { for _, b := range envs { if b.owner == "" { continue } if p := c.MailPrefix[app]; p != "" && c.Submission[app] { stem := strings.TrimSuffix(p, "_SMTP") if _, ok := b.vars[stem+"_MAIL_FROM"]; !ok { b.vars[stem+"_MAIL_FROM"] = Var{Kind: "env", Value: "team@oficina.works"} } } else if p != "" { if _, ok := b.vars[p+"_USER"]; !ok { c.minted++ b.vars[p+"_HOST"] = Var{Kind: "env", Value: "email-smtp.eu-west-1.amazonaws.com"} b.vars[p+"_PORT"] = Var{Kind: "env", Value: "587"} b.vars[p+"_FROM"] = Var{Kind: "env", Value: "team@oficina.works"} b.vars[p+"_USER"] = Var{Kind: "env", Value: fmt.Sprintf("%s-USER-%d", PlatformCanary, c.minted)} b.vars[p+"_PASS"] = Var{Kind: "secret", Envelope: c.sealCanary(app)} } } if c.Relay[app] { if _, ok := b.vars["CARLOS_RELAY"]; !ok { b.vars["CARLOS_RELAY"] = Var{Kind: "secret", Envelope: c.sealCanary(app)} } } } } } func (c *Console) sealCanary(app string) string { acct := "" if c.Bound { acct = c.Account } e, _ := console.Seal(c.SecretsPub(), acct, app, []byte(PlatformCanary+"-SECRET")) return e } // ServingName, when set, is what a box reports serving for an app, // instead of the version /api/version answers (carlos ship's release // version need not be the binary's stamp). func (c *Console) servingName(i *inst) string { if n := c.ServingName[i.app]; n != "" { return n } return i.serving } // SetAsleep marks an instance's box report asleep (not awake), as a // hibernated or starting instance reports. func (c *Console) SetAsleep(host string, asleep bool) { c.mu.Lock() defer c.mu.Unlock() if i, ok := c.instances[host]; ok { i.asleep = asleep } } // SetDomainState moves a claim's state word. func (c *Console) SetDomainState(host, state string) { c.mu.Lock() defer c.mu.Unlock() if d, ok := c.domains[host]; ok { d.state = state } } // ---- the doors ---- var path = 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 (c *Console) owned(app, env string) bool { b := c.envs[app][env] return env != "" && b != nil && b.owner == c.Scope } func (c *Console) inScopeHost(app, host string) (*inst, bool) { i, ok := c.instances[host] if !ok || i.app != app || !c.owned(app, i.env) { return nil, false } return i, true } func (c *Console) serve(w http.ResponseWriter, r *http.Request) { c.mu.Lock() defer c.mu.Unlock() m := path.FindStringSubmatch(r.URL.Path) if m == nil { http.NotFound(w, r) return } account, app, rest := m[1], m[2], m[3] c.Requests = append(c.Requests, r.Method+" "+strings.SplitN(rest, "/", 3)[1]+" "+app) bound := c.tokens[strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")] if bound == "" { refuse(w, 401, "not signed in") return } // teamInScope: the path must name the credential's own account by // sqid and its own app, or 404. if account != c.Account || app != bound { http.NotFound(w, r) return } var body map[string]any if r.Body != nil { raw, _ := io.ReadAll(r.Body) if len(raw) > 0 && json.Unmarshal(raw, &body) != nil { refuse(w, 400, "bad json") return } } s := func(k string) string { v, _ := body[k].(string); return v } switch { case r.Method == http.MethodGet && rest == "/config": env := r.URL.Query().Get("environment") if !c.owned(app, env) { http.NotFound(w, r) return } var vars []map[string]any keys := make([]string, 0) for k := range c.envs[app][env].vars { keys = append(keys, k) } sort.Strings(keys) for _, k := range keys { v := c.envs[app][env].vars[k] row := map[string]any{"key": k, "kind": v.Kind} if v.Kind == "env" { row["value"] = v.Value } vars = append(vars, row) } out := map[string]any{"bundle": env, "environments": []string{env}, "vars": vars, "secrets_pubkey": c.SecretsPub()} if c.Bound { out["secrets_account"] = c.Account } writeJSON(w, 200, out) case r.Method == http.MethodPut && rest == "/config": env := s("environment") if env == "" { http.NotFound(w, r) return } b := c.envs[app][env] if b != nil && b.owner != c.Scope { http.NotFound(w, r) return } if b == nil { // Capture rules: a name a record references is not the scope's. for _, i := range c.instances { if i.app == app && i.env == env { http.NotFound(w, r) return } } } set, _ := body["set"].(map[string]any) unset, _ := body["unset"].([]any) for k := range set { if console.PlatformManaged(k) { refuse(w, 403, "a team credential cannot set or unset a platform-managed key ("+k+")") return } } for _, k := range unset { if console.PlatformManaged(fmt.Sprint(k)) { refuse(w, 403, "a team credential cannot set or unset a platform-managed key") return } } if b == nil { if c.envs[app] == nil { c.envs[app] = map[string]*bundle{} } b = &bundle{owner: c.Scope, vars: map[string]Var{}} c.envs[app][env] = b } for k, raw := range set { v, _ := raw.(map[string]any) kind, _ := v["kind"].(string) if kind == "secret" { e, _ := v["envelope"].(string) if _, err := base64.StdEncoding.DecodeString(e); err != nil || e == "" { refuse(w, 400, "var "+k+": envelope is not valid base64") return } if val, _ := v["value"].(string); val != "" { refuse(w, 400, "plaintext secret") return } b.vars[k] = Var{Kind: "secret", Envelope: e} c.SecretWrites[app+"/"+env+"/"+k]++ } else { val, _ := v["value"].(string) b.vars[k] = Var{Kind: "env", Value: val} } } removed := 0 for _, k := range unset { if _, ok := b.vars[fmt.Sprint(k)]; ok { delete(b.vars, fmt.Sprint(k)) removed++ } } var hosts []map[string]string for h, i := range c.instances { if i.app == app && i.env == env { i.pending = true hosts = append(hosts, map[string]string{"host": h}) } } writeJSON(w, 200, map[string]any{"result": "ok", "removed": removed, "restart": map[string]any{"known": true, "hosts": hosts}}) case r.Method == http.MethodGet && rest == "/instances": q := r.URL.Query().Get("q") var rows []map[string]any for h, i := range c.instances { if i.app != app || !c.owned(app, i.env) || (q != "" && !strings.Contains(h, q)) { continue } row := map[string]any{"host": h, "app": app, "account": c.Account, "environment": i.env, "health": "Running", "staged_version": i.serving} if i.serving != "" { row["rollout"] = map[string]any{"installed": i.serving, "serving": c.servingName(i), "awake": !i.asleep, "config_pending": i.pending} } rows = append(rows, row) } writeJSON(w, 200, map[string]any{"instances": rows, "total": len(rows)}) case r.Method == http.MethodPost && rest == "/instances": env := s("environment") if !c.owned(app, env) { http.NotFound(w, r) return } if s("kind") != "" && s("kind") != "instance" { refuse(w, 403, "creates socket-backed instances only") return } host := s("host") if !strings.HasSuffix(host, "."+c.Account+".oncarlos.com") { refuse(w, 400, "invalid host") return } if _, ok := c.instances[host]; ok { refuse(w, 409, "host already exists") return } if c.PrivateStorage[app] { // The store first, then the record (CARLOS's create door). b := c.envs[app][env] b.vars["CARLOS_STORE_BUCKET"] = Var{Kind: "env", Value: "carlos-" + c.Account + "-" + app + "-" + env} b.vars["CARLOS_STORE_REGION"] = Var{Kind: "env", Value: "eu-west-1"} if c.StoreEndpoint != "" { b.vars["CARLOS_STORE_ENDPOINT"] = Var{Kind: "env", Value: c.StoreEndpoint} } b.vars["CARLOS_STORE_ACCESS_KEY"] = Var{Kind: "secret", Envelope: c.sealCanary(app)} b.vars["CARLOS_STORE_SECRET_KEY"] = Var{Kind: "secret", Envelope: c.sealCanary(app)} } c.instances[host] = &inst{env: env, app: app, serving: c.Versions[app]} writeJSON(w, 200, map[string]any{"host": host, "environment": env}) case strings.HasPrefix(rest, "/instances/"): host := strings.TrimPrefix(rest, "/instances/") i, ok := c.inScopeHost(app, host) if !ok { http.NotFound(w, r) return } switch r.Method { case http.MethodGet: writeJSON(w, 200, map[string]any{"host": host, "app": app, "account": c.Account, "environment": i.env}) case http.MethodDelete: delete(c.instances, host) writeJSON(w, 200, map[string]any{"host": host, "deleted": true}) default: refuse(w, 405, "method") } case r.Method == http.MethodPost && rest == "/domains": route := strings.ToLower(s("route")) if _, ok := c.inScopeHost(app, route); !ok { http.NotFound(w, r) return } host := s("host") if body["wildcard"] != nil || body["catchall"] != nil { refuse(w, 403, "no wildcard") return } if d, ok := c.domains[host]; ok && d.route != route { refuse(w, 409, "hostname is taken") return } if _, ok := c.domains[host]; !ok { c.domains[host] = &claim{app: app, route: route, state: "checking"} } writeJSON(w, 200, map[string]any{"host": host, "route": route, "created": true}) case strings.HasPrefix(rest, "/domains/"): host := strings.TrimPrefix(rest, "/domains/") d, ok := c.domains[host] if !ok || d.app != app || d.route == "" { refuse(w, 404, "no such hostname") return } if _, in := c.inScopeHost(app, d.route); !in { refuse(w, 404, "no such hostname") return } switch r.Method { case http.MethodGet: if d.state != "live" { d.polls++ if d.polls > c.DomainPolls && d.state == "checking" { d.state = "live" } } writeJSON(w, 200, map[string]any{"domain": map[string]any{"host": host, "route": d.route, "status": "pending", "state": d.state, "verified": true}}) case http.MethodDelete: delete(c.domains, host) writeJSON(w, 200, map[string]any{"host": host, "removed": true}) } case r.Method == http.MethodPost && rest == "/restart/scope": i, ok := c.inScopeHost(app, s("host")) if !ok { http.NotFound(w, r) return } i.restarts++ i.pending = false writeJSON(w, 200, map[string]any{"result": "ok"}) default: // Every other door is closed to the team role. refuse(w, 403, "not for a team credential") } } // Transport routes the team instances' public origins // (https://