oficina / alta Public

console: the CARLOS team-credential client and its guards

One team credential per app (team-scoped-credentials.md), the account
named by its sqid as the team doors require, and only the doors that role
admits: config, instances, domains, restart/scope. Secrets are sealed on
Alta's side against the console's secrets_pubkey (CARLOS's v1/v2
envelope, v2 when the console advertises secrets_account). Every request
passes Alta's §8 guard first: an empty or unrecorded environment, a host
outside <label>-<app>.<sqid>.oncarlos.com or <label>.<app>.oficina.works,
a DELETE outside a deprovision run, and any platform-managed key are
refused before anything is sent.

fakeconsole is the console as a team credential meets it, with the mail
and relay walks minting per-environment credentials on their own
cadence, and the team instances' public origins.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 221f655abd6993c89c9c979c053d73845c5c8b43 parent 9a055d4
4 files changed, +1,142 −0
  • console/client.go +399 −0
  • console/fakeconsole/fakeconsole.go +566 −0
  • console/seal.go +122 −0
  • console/seal_test.go +55 −0
diff --git a/console/client.go b/console/client.go
new file mode 100644
index 0000000..9b4b47e
--- /dev/null
+++ b/console/client.go
@@ -0,0 +1,399 @@
+// Package console is Alta's CARLOS console client. It holds one `team`
+// service credential per app (carlos/platform
+// implementation/team-scoped-credentials.md) and reaches only the doors
+// that role admits: config, instances, domains and restart/scope, under
+// /api/cli/apps/{account}/{app}.
+//
+// The credential's scope is the fence (CARLOS refuses anything outside
+// the environments scope `alta` owns). The guards here are defence in
+// depth (team-provisioning-app.md §8): every request passes Guard first,
+// and a request Guard refuses never leaves the process.
+package console
+
+import (
+ "bytes"
+ "context"
+ "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "net/url"
+ "regexp"
+ "strings"
+)
+
+// ErrNotFound is the console's 404, which for a team credential means
+// "absent, or not this scope's": the two are deliberately the same bytes.
+var ErrNotFound = errors.New("console: not found")
+
+// ErrGuard is a request Alta's own guard refused before sending it.
+var ErrGuard = errors.New("console: refused by Alta's guard")
+
+// StatusError is any other non-2xx answer. Message is the console's own
+// sentence; it names keys and hosts, never values.
+type StatusError struct {
+ Code int
+ Message string
+}
+
+func (e *StatusError) Error() string { return fmt.Sprintf("console: %d %s", e.Code, e.Message) }
+
+// IsConflict reports a 409.
+func IsConflict(err error) bool {
+ var s *StatusError
+ return errors.As(err, &s) && s.Code == http.StatusConflict
+}
+
+// Guard is the §8 check every request passes. The provisioning store
+// implements it from its own records.
+type Guard interface {
+ // Environment admits env for app: non-empty and owned per Alta's
+ // records. write is false for a read, which a preflight may make for
+ // a label not yet recorded.
+ Environment(ctx context.Context, app, env string, write bool) error
+ // Host admits host for app: <label>-<app>.<account>.oncarlos.com or
+ // <label>.<app>.oficina.works for a label Alta holds.
+ Host(ctx context.Context, app, host string, write bool) error
+ // Delete admits a DELETE only inside a deprovision run.
+ Delete(ctx context.Context, app, host string) error
+}
+
+// managedKey matches the keys only the platform's walks write into an
+// owned environment (team-scoped-credentials.md §3a): any prefix's SMTP
+// five, the relay identity, the mail-events key, scan callback secrets
+// and the object store's coordinates. CARLOS refuses a team write of
+// them too; Alta refuses first, for every prefix, without asking which
+// one the app declared.
+var managedKey = regexp.MustCompile(`^([A-Z][A-Z0-9_]*_SMTP_(HOST|PORT|USER|PASS|FROM)|CARLOS_RELAY|CARLOS_MAIL_EVENTS_KEY|[A-Z][A-Z0-9_]*_SCAN_CALLBACK_SECRET|CARLOS_STORE_[A-Z0-9_]+)$`)
+
+// PlatformManaged reports whether key is the platform's alone.
+func PlatformManaged(key string) bool { return managedKey.MatchString(key) }
+
+// Client is one console, one account, one credential per app.
+type Client struct {
+ HTTP *http.Client
+ Base string // https://console.carloku.com
+ Account string // the account's sqid: team doors 404 any other spelling
+ Tokens map[string]string
+ Guard Guard
+}
+
+func (c *Client) do(ctx context.Context, app, method, path string, body any, out any) error {
+ token := c.Tokens[app]
+ if token == "" {
+ return fmt.Errorf("console: no team credential for %s", app)
+ }
+ var rd io.Reader
+ if body != nil {
+ b, err := json.Marshal(body)
+ if err != nil {
+ return err
+ }
+ rd = bytes.NewReader(b)
+ }
+ u := strings.TrimRight(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 err
+ }
+ req.Header.Set("Authorization", "Bearer "+token)
+ req.Header.Set("Accept", "application/json")
+ if body != nil {
+ req.Header.Set("Content-Type", "application/json")
+ }
+ client := c.HTTP
+ if client == nil {
+ client = http.DefaultClient
+ }
+ cc := *client
+ cc.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
+ resp, err := cc.Do(req)
+ if err != nil {
+ return err
+ }
+ defer resp.Body.Close()
+ raw, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20))
+ if err != nil {
+ return err
+ }
+ if resp.StatusCode == http.StatusNotFound {
+ return ErrNotFound
+ }
+ if resp.StatusCode < 200 || resp.StatusCode > 299 {
+ var msg struct {
+ Error string `json:"error"`
+ }
+ _ = json.Unmarshal(raw, &msg)
+ return &StatusError{Code: resp.StatusCode, Message: msg.Error}
+ }
+ if out != nil {
+ if err := json.Unmarshal(raw, out); err != nil {
+ return fmt.Errorf("console: unreadable answer: %w", err)
+ }
+ }
+ return nil
+}
+
+func (c *Client) guard(err error) error {
+ if err != nil {
+ return fmt.Errorf("%w: %v", ErrGuard, err)
+ }
+ return nil
+}
+
+func (c *Client) checkEnv(ctx context.Context, app, env string, write bool) error {
+ if strings.TrimSpace(env) == "" {
+ return c.guard(errors.New("empty environment"))
+ }
+ if c.Guard == nil {
+ return c.guard(errors.New("no guard"))
+ }
+ return c.guard(c.Guard.Environment(ctx, app, env, write))
+}
+
+func (c *Client) checkHost(ctx context.Context, app, host string, write bool) error {
+ if c.Guard == nil {
+ return c.guard(errors.New("no guard"))
+ }
+ return c.guard(c.Guard.Host(ctx, app, host, write))
+}
+
+// Var is one config variable as GET /config answers it. Value is present
+// for env vars only; a secret is a name and nothing else.
+type Var struct {
+ Key string `json:"key"`
+ Kind string `json:"kind"`
+ Value string `json:"value,omitempty"`
+}
+
+// Config is GET /config?environment=E.
+type Config struct {
+ Bundle string `json:"bundle"`
+ Environments []string `json:"environments"`
+ Vars []Var `json:"vars"`
+ SecretsPubKey string `json:"secrets_pubkey"`
+ SecretsAccount string `json:"secrets_account"`
+}
+
+// Keys is the config's variables by name.
+func (c Config) Keys() map[string]Var {
+ out := make(map[string]Var, len(c.Vars))
+ for _, v := range c.Vars {
+ out[v.Key] = v
+ }
+ return out
+}
+
+// GetConfig reads an owned environment. For a team credential a 404 means
+// absent or not this scope's; found is false then.
+func (c *Client) GetConfig(ctx context.Context, app, env string) (Config, bool, error) {
+ if err := c.checkEnv(ctx, app, env, false); err != nil {
+ return Config{}, false, err
+ }
+ var out Config
+ err := c.do(ctx, app, http.MethodGet, "/config?environment="+url.QueryEscape(env), nil, &out)
+ if errors.Is(err, ErrNotFound) {
+ return Config{}, false, nil
+ }
+ return out, err == nil, err
+}
+
+// SetVar is one variable to write. A secret carries its sealed envelope.
+type SetVar struct {
+ Kind string `json:"kind"`
+ Value string `json:"value,omitempty"`
+ Envelope string `json:"envelope,omitempty"`
+}
+
+// PutResult is PUT /config's answer.
+type PutResult struct {
+ Result string `json:"result"`
+ Removed int `json:"removed"`
+ Restart *struct {
+ Known bool `json:"known"`
+ Hosts []struct {
+ Host string `json:"host"`
+ } `json:"hosts"`
+ } `json:"restart"`
+}
+
+// RestartsHosts reports whether the write landed under a running
+// instance (the console's restart notice names one), or the console could
+// not tell.
+func (p PutResult) RestartsHosts() bool {
+ return p.Restart != nil && (!p.Restart.Known || len(p.Restart.Hosts) > 0)
+}
+
+// PutConfig writes set and unset into env in one CAS write. A platform-
+// managed key in either refuses the whole request here.
+func (c *Client) PutConfig(ctx context.Context, app, env string, set map[string]SetVar, unset []string, message string) (PutResult, error) {
+ if err := c.checkEnv(ctx, app, env, true); err != nil {
+ return PutResult{}, err
+ }
+ for k := range set {
+ if PlatformManaged(k) {
+ return PutResult{}, c.guard(fmt.Errorf("set of platform-managed key %s", k))
+ }
+ }
+ for _, k := range unset {
+ if PlatformManaged(k) {
+ return PutResult{}, c.guard(fmt.Errorf("unset of platform-managed key %s", k))
+ }
+ }
+ if len(set) == 0 && len(unset) == 0 {
+ return PutResult{}, nil
+ }
+ body := map[string]any{"environment": env, "message": message, "set": set}
+ if len(unset) > 0 {
+ body["unset"] = unset
+ }
+ var out PutResult
+ err := c.do(ctx, app, http.MethodPut, "/config", body, &out)
+ return out, err
+}
+
+// Instance is the part of an instance record Alta reads.
+type Instance struct {
+ Host string `json:"host"`
+ App string `json:"app"`
+ Account string `json:"account"`
+ Environment string `json:"environment"`
+ Kind string `json:"kind"`
+}
+
+// Rollout is the box's report for one host, on the list door only.
+type Rollout struct {
+ Installed string `json:"installed"`
+ Serving string `json:"serving"`
+ Awake bool `json:"awake"`
+ ConfigPending bool `json:"config_pending"`
+}
+
+// ListedInstance is one row of GET /instances.
+type ListedInstance struct {
+ Instance
+ StagedVersion string `json:"staged_version"`
+ Health string `json:"health"`
+ Rollout *Rollout `json:"rollout"`
+}
+
+// GetInstance reads one record.
+func (c *Client) GetInstance(ctx context.Context, app, host string) (Instance, bool, error) {
+ if err := c.checkHost(ctx, app, host, false); err != nil {
+ return Instance{}, false, err
+ }
+ var out Instance
+ err := c.do(ctx, app, http.MethodGet, "/instances/"+url.PathEscape(host), nil, &out)
+ if errors.Is(err, ErrNotFound) {
+ return Instance{}, false, nil
+ }
+ return out, err == nil, err
+}
+
+// ListedHost finds host on the list door, which alone carries the box's
+// rollout report (serving build).
+func (c *Client) ListedHost(ctx context.Context, app, host string) (ListedInstance, bool, error) {
+ if err := c.checkHost(ctx, app, host, false); err != nil {
+ return ListedInstance{}, false, err
+ }
+ var out struct {
+ Instances []ListedInstance `json:"instances"`
+ }
+ if err := c.do(ctx, app, http.MethodGet, "/instances?q="+url.QueryEscape(host), nil, &out); err != nil {
+ return ListedInstance{}, false, err
+ }
+ for _, row := range out.Instances {
+ if row.Host == host {
+ return row, true, nil
+ }
+ }
+ return ListedInstance{}, false, nil
+}
+
+// CreateInstance creates a socket-backed instance bound to env: the only
+// kind a team credential may create.
+func (c *Client) CreateInstance(ctx context.Context, app, host, env, message string) error {
+ if err := c.checkHost(ctx, app, host, true); err != nil {
+ return err
+ }
+ if err := c.checkEnv(ctx, app, env, true); err != nil {
+ return err
+ }
+ return c.do(ctx, app, http.MethodPost, "/instances", map[string]any{"host": host, "environment": env, "message": message}, nil)
+}
+
+// DeleteInstance deletes a record; only inside a deprovision run.
+func (c *Client) DeleteInstance(ctx context.Context, app, host string) error {
+ if err := c.checkHost(ctx, app, host, true); err != nil {
+ return err
+ }
+ if err := c.guard(c.Guard.Delete(ctx, app, host)); err != nil {
+ return err
+ }
+ err := c.do(ctx, app, http.MethodDelete, "/instances/"+url.PathEscape(host), nil, nil)
+ if errors.Is(err, ErrNotFound) {
+ return nil
+ }
+ return err
+}
+
+// Domain is one hostname claim as the per-host door answers it. State is
+// #299's lifecycle word; the legacy Status is never read.
+type Domain struct {
+ Host string `json:"host"`
+ Route string `json:"route"`
+ State string `json:"state"`
+ Reason string `json:"reason"`
+ Detail string `json:"detail"`
+ Verified bool `json:"verified"`
+}
+
+// GetDomain reads one claim.
+func (c *Client) GetDomain(ctx context.Context, app, host string) (Domain, bool, error) {
+ if err := c.checkHost(ctx, app, host, false); err != nil {
+ return Domain{}, false, err
+ }
+ var out struct {
+ Domain Domain `json:"domain"`
+ }
+ err := c.do(ctx, app, http.MethodGet, "/domains/"+url.PathEscape(host), nil, &out)
+ if errors.Is(err, ErrNotFound) {
+ return Domain{}, false, nil
+ }
+ return out.Domain, err == nil, err
+}
+
+// AttachDomain claims host for route (explicit host, no wildcard).
+func (c *Client) AttachDomain(ctx context.Context, app, host, route, message string) error {
+ if err := c.checkHost(ctx, app, host, true); err != nil {
+ return err
+ }
+ if err := c.checkHost(ctx, app, route, true); err != nil {
+ return err
+ }
+ return c.do(ctx, app, http.MethodPost, "/domains", map[string]any{"host": host, "route": route, "message": message}, nil)
+}
+
+// DetachDomain removes a claim; only inside a deprovision run.
+func (c *Client) DetachDomain(ctx context.Context, app, host string) error {
+ if err := c.checkHost(ctx, app, host, true); err != nil {
+ return err
+ }
+ if err := c.guard(c.Guard.Delete(ctx, app, host)); err != nil {
+ return err
+ }
+ err := c.do(ctx, app, http.MethodDelete, "/domains/"+url.PathEscape(host), nil, nil)
+ if errors.Is(err, ErrNotFound) {
+ return nil
+ }
+ return err
+}
+
+// RestartHost restarts one in-scope instance.
+func (c *Client) RestartHost(ctx context.Context, app, host, message string) error {
+ if err := c.checkHost(ctx, app, host, true); err != nil {
+ return err
+ }
+ return c.do(ctx, app, http.MethodPost, "/restart/scope", map[string]any{"host": host, "message": message}, nil)
+}
diff --git a/console/fakeconsole/fakeconsole.go b/console/fakeconsole/fakeconsole.go
new file mode 100644
index 0000000..6372baf
--- /dev/null
+++ b/console/fakeconsole/fakeconsole.go
@@ -0,0 +1,566 @@
+// 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
+ 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
+ // 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
+
+ // 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{}, Versions: map[string]string{}, DomainPolls: 1, Roster: "ok", SecretWrites: map[string]int{}}
+ 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, 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 != "" {
+ 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
+}
+
+// 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": i.serving, "awake": true, "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
+ }
+ 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://<label>.<app>.oficina.works) to the fake: /api/version is the
+// build an instance serves, behind a live claim; /api/team is the
+// readiness probe for a roster-mode app.
+func (c *Console) Transport() http.RoundTripper {
+ return roundTrip(func(r *http.Request) (*http.Response, error) {
+ c.mu.Lock()
+ defer c.mu.Unlock()
+ rec := httptest.NewRecorder()
+ d, ok := c.domains[r.URL.Host]
+ var i *inst
+ if ok {
+ i = c.instances[d.route]
+ }
+ switch {
+ case !ok || d.state != "live" || i == nil:
+ return nil, fmt.Errorf("fakeconsole: %s does not resolve", r.URL.Host)
+ case r.URL.Path == "/api/version":
+ rec.WriteString(i.serving)
+ case r.URL.Path == "/api/team" && i.app == "docs":
+ b := c.envs[i.app][i.env]
+ _, token := b.vars["DOCS_TEAM_ROSTER_TOKEN"]
+ consumer := b.vars["DOCS_HOME_CONSUMER_ID"].Value
+ roster := c.Roster
+ if !token {
+ roster = "unknown"
+ }
+ rec.Header().Set("Content-Type", "application/json")
+ _ = json.NewEncoder(rec).Encode(map[string]any{"team_mode": token, "consumer": consumer, "roster": roster})
+ default:
+ rec.WriteHeader(404)
+ }
+ return rec.Result(), nil
+ })
+}
+
+type roundTrip func(*http.Request) (*http.Response, error)
+
+func (f roundTrip) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) }
diff --git a/console/seal.go b/console/seal.go
new file mode 100644
index 0000000..2fe8c57
--- /dev/null
+++ b/console/seal.go
@@ -0,0 +1,122 @@
+package console
+
+import (
+ "crypto/aes"
+ "crypto/cipher"
+ "crypto/ecdh"
+ "crypto/hkdf"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/binary"
+ "errors"
+ "strings"
+)
+
+// The console never sees a secret's plaintext: `carlos secrets set` seals
+// on the operator's machine against the console's secrets_pubkey, and Alta
+// does the same. This is CARLOS's envelope (platform internal/appconfig/
+// crypto.go), reimplemented because Alta cannot import the platform:
+//
+// v1 (unbound): ephPub(65) || nonce(12) || AES-256-GCM ciphertext
+// v2 (bound): "CSB2" || v1's layout, with (account, app) as GCM
+// associated data and a different HKDF info
+//
+// The console says which to write: GET /config answers secrets_account
+// only while it takes bound (v2) envelopes.
+const (
+ v1Info = "carlos-secrets-v1"
+ v2Info = "carlos-secrets-v2"
+ boundPrefix = "CSB2"
+)
+
+func gcmFor(shared []byte, info string) (cipher.AEAD, error) {
+ key, err := hkdf.Key(sha256.New, shared, nil, info, 32)
+ if err != nil {
+ return nil, err
+ }
+ block, err := aes.NewCipher(key)
+ if err != nil {
+ return nil, err
+ }
+ return cipher.NewGCM(block)
+}
+
+func bindingAAD(account, app string) []byte {
+ var out []byte
+ for _, f := range []string{boundPrefix, account, app} {
+ out = binary.BigEndian.AppendUint32(out, uint32(len(f)))
+ out = append(out, f...)
+ }
+ return out
+}
+
+// Seal seals plaintext for the console's public key. With account empty
+// it writes v1; otherwise v2 bound to (account, app).
+func Seal(pubB64, account, app string, plaintext []byte) (string, error) {
+ if len(plaintext) == 0 {
+ return "", errors.New("console: refusing to seal an empty secret")
+ }
+ raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(pubB64))
+ if err != nil {
+ return "", errors.New("console: secrets_pubkey is not base64")
+ }
+ pub, err := ecdh.P256().NewPublicKey(raw)
+ if err != nil {
+ return "", errors.New("console: secrets_pubkey is not a P-256 point")
+ }
+ eph, err := ecdh.P256().GenerateKey(rand.Reader)
+ if err != nil {
+ return "", err
+ }
+ nonce := make([]byte, 12)
+ if _, err := rand.Read(nonce); err != nil {
+ return "", err
+ }
+ shared, err := eph.ECDH(pub)
+ if err != nil {
+ return "", err
+ }
+ prefix, info, aad := "", v1Info, []byte(nil)
+ if account != "" {
+ prefix, info, aad = boundPrefix, v2Info, bindingAAD(account, app)
+ }
+ gcm, err := gcmFor(shared, info)
+ if err != nil {
+ return "", err
+ }
+ out := append([]byte(prefix), eph.PublicKey().Bytes()...)
+ out = append(out, nonce...)
+ out = gcm.Seal(out, nonce, plaintext, aad)
+ return base64.StdEncoding.EncodeToString(out), nil
+}
+
+// Open is Seal's inverse, for tests (the fake console holds the private
+// half, as a box does).
+func Open(priv *ecdh.PrivateKey, account, app, envelope string) ([]byte, error) {
+ raw, err := base64.StdEncoding.DecodeString(envelope)
+ if err != nil {
+ return nil, err
+ }
+ info, aad := v1Info, []byte(nil)
+ if strings.HasPrefix(string(raw), boundPrefix) {
+ raw = raw[len(boundPrefix):]
+ info, aad = v2Info, bindingAAD(account, app)
+ }
+ if len(raw) < 65+12+16 {
+ return nil, errors.New("console: envelope too short")
+ }
+ eph, err := ecdh.P256().NewPublicKey(raw[:65])
+ if err != nil {
+ return nil, err
+ }
+ shared, err := priv.ECDH(eph)
+ if err != nil {
+ return nil, err
+ }
+ gcm, err := gcmFor(shared, info)
+ if err != nil {
+ return nil, err
+ }
+ return gcm.Open(nil, raw[65:77], raw[77:], aad)
+}
diff --git a/console/seal_test.go b/console/seal_test.go
new file mode 100644
index 0000000..8a45b5a
--- /dev/null
+++ b/console/seal_test.go
@@ -0,0 +1,55 @@
+package console
+
+import (
+ "crypto/ecdh"
+ "crypto/rand"
+ "encoding/base64"
+ "strings"
+ "testing"
+)
+
+func TestSealOpensForItsBindingOnly(t *testing.T) {
+ priv, _ := ecdh.P256().GenerateKey(rand.Reader)
+ pub := base64.StdEncoding.EncodeToString(priv.PublicKey().Bytes())
+ v1, err := Seal(pub, "", "docs", []byte("dek"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ if got, err := Open(priv, "anything", "else", v1); err != nil || string(got) != "dek" {
+ t.Fatalf("v1: %q %v", got, err)
+ }
+ v2, err := Seal(pub, "bds", "docs", []byte("dek"))
+ if err != nil {
+ t.Fatal(err)
+ }
+ raw, _ := base64.StdEncoding.DecodeString(v2)
+ if !strings.HasPrefix(string(raw), "CSB2") || len(raw) != 4+65+12+3+16 {
+ t.Fatalf("v2 layout: %d bytes", len(raw))
+ }
+ if got, err := Open(priv, "bds", "docs", v2); err != nil || string(got) != "dek" {
+ t.Fatalf("v2: %q %v", got, err)
+ }
+ if _, err := Open(priv, "bds", "sheets", v2); err == nil {
+ t.Fatal("a v2 envelope opened for another app")
+ }
+ // A v2 envelope with its prefix cut off is not a valid v1 one.
+ if _, err := Open(priv, "", "", base64.StdEncoding.EncodeToString(raw[4:])); err == nil {
+ t.Fatal("downgrade opened")
+ }
+ if _, err := Seal(pub, "", "docs", nil); err == nil {
+ t.Fatal("sealed an empty secret")
+ }
+}
+
+func TestPlatformManaged(t *testing.T) {
+ for _, k := range []string{"CARLOS_SMTP_PASS", "DOCS_SMTP_FROM", "CARLOS_RELAY", "CARLOS_MAIL_EVENTS_KEY", "SLIDES_SCAN_CALLBACK_SECRET", "CARLOS_STORE_ACCESS_KEY"} {
+ if !PlatformManaged(k) {
+ t.Errorf("%s not platform-managed", k)
+ }
+ }
+ for _, k := range []string{"DOCS_ORIGIN", "SMTP_HOSTNAME", "CALLS_DEK", "DOCS_SMTP", "MEMORIA_OWNERS"} {
+ if PlatformManaged(k) {
+ t.Errorf("%s platform-managed", k)
+ }
+ }
+}