| 1 | // Package console is Alta's CARLOS console client. It holds one `team` |
| 2 | // service credential per app (carlos/platform |
| 3 | // implementation/team-scoped-credentials.md) and reaches only the doors |
| 4 | // that role admits: config, instances, domains and restart/scope, under |
| 5 | // /api/cli/apps/{account}/{app}. |
| 6 | // |
| 7 | // The credential's scope is the fence (CARLOS refuses anything outside |
| 8 | // the environments scope `alta` owns). The guards here are defence in |
| 9 | // depth (team-provisioning-app.md §8): every request passes Guard first, |
| 10 | // and a request Guard refuses never leaves the process. |
| 11 | package console |
| 12 | |
| 13 | import ( |
| 14 | "bytes" |
| 15 | "context" |
| 16 | "encoding/json" |
| 17 | "errors" |
| 18 | "fmt" |
| 19 | "io" |
| 20 | "net/http" |
| 21 | "net/url" |
| 22 | "regexp" |
| 23 | "strings" |
| 24 | ) |
| 25 | |
| 26 | // ErrNotFound is the console's 404, which for a team credential means |
| 27 | // "absent, or not this scope's": the two are deliberately the same bytes. |
| 28 | var ErrNotFound = errors.New("console: not found") |
| 29 | |
| 30 | // ErrGuard is a request Alta's own guard refused before sending it. |
| 31 | var ErrGuard = errors.New("console: refused by Alta's guard") |
| 32 | |
| 33 | // StatusError is any other non-2xx answer. Message is the console's own |
| 34 | // sentence; it names keys and hosts, never values. |
| 35 | type StatusError struct { |
| 36 | Code int |
| 37 | Message string |
| 38 | } |
| 39 | |
| 40 | func (e *StatusError) Error() string { return fmt.Sprintf("console: %d %s", e.Code, e.Message) } |
| 41 | |
| 42 | // IsConflict reports a 409. |
| 43 | func IsConflict(err error) bool { |
| 44 | var s *StatusError |
| 45 | return errors.As(err, &s) && s.Code == http.StatusConflict |
| 46 | } |
| 47 | |
| 48 | // Guard is the §8 check every request passes. The provisioning store |
| 49 | // implements it from its own records. |
| 50 | type Guard interface { |
| 51 | // Environment admits env for app: non-empty and owned per Alta's |
| 52 | // records. write is false for a read, which a preflight may make for |
| 53 | // a label not yet recorded. |
| 54 | Environment(ctx context.Context, app, env string, write bool) error |
| 55 | // Host admits host for app: <label>-<app>.<account>.oncarlos.com or |
| 56 | // <label>.<app>.oficina.works for a label Alta holds. |
| 57 | Host(ctx context.Context, app, host string, write bool) error |
| 58 | // Delete admits a DELETE only inside a deprovision run. |
| 59 | Delete(ctx context.Context, app, host string) error |
| 60 | } |
| 61 | |
| 62 | // managedKey matches the keys only the platform writes into an owned |
| 63 | // environment (team-scoped-credentials.md §3a): any prefix's SMTP five, |
| 64 | // the From variable a switched app gets in their place (<stem>_MAIL_FROM, |
| 65 | // platform mail submission G3), the relay identity, the mail-events key, |
| 66 | // scan callback secrets and the object store's coordinates; and |
| 67 | // CARLOS_MAIL, which only the agent sets, at instance start. CARLOS |
| 68 | // refuses a team write of most of them too; Alta refuses first, for every |
| 69 | // prefix, without asking which one the app declared. |
| 70 | var managedKey = regexp.MustCompile(`^([A-Z][A-Z0-9_]*_SMTP_(HOST|PORT|USER|PASS|FROM)|[A-Z][A-Z0-9_]*_MAIL_FROM|CARLOS_MAIL|CARLOS_RELAY|CARLOS_MAIL_EVENTS_KEY|[A-Z][A-Z0-9_]*_SCAN_CALLBACK_SECRET|CARLOS_STORE_[A-Z0-9_]+)$`) |
| 71 | |
| 72 | // PlatformManaged reports whether key is the platform's alone. |
| 73 | func PlatformManaged(key string) bool { return managedKey.MatchString(key) } |
| 74 | |
| 75 | // operatorOnly is the keys only Paul ever sets (Memoria's AI and his |
| 76 | // TensorX key, Paul 2026-11-12): Alta never holds or writes them, so a set |
| 77 | // of either is refused before it is sent. Unsetting (a fork's blanked |
| 78 | // MEMORIA_AI) stays allowed. |
| 79 | // Equipo's execution pair is the same (team-bundle spec slice 3b). |
| 80 | var operatorOnly = map[string]bool{"MEMORIA_AI": true, "MEMORIA_TENSORX_KEY": true, "EQUIPO_EXECUTION_ENABLED": true, "EQUIPO_EXECUTION_MARKER_PATH": true} |
| 81 | |
| 82 | // OperatorOnly reports whether key is Paul's alone to set. |
| 83 | func OperatorOnly(key string) bool { return operatorOnly[key] } |
| 84 | |
| 85 | // Client is one console, one account, one credential per app. |
| 86 | type Client struct { |
| 87 | HTTP *http.Client |
| 88 | Base string // https://console.carloku.com |
| 89 | Account string // the account's sqid: team doors 404 any other spelling |
| 90 | Tokens map[string]string |
| 91 | Guard Guard |
| 92 | } |
| 93 | |
| 94 | func (c *Client) do(ctx context.Context, app, method, path string, body any, out any) error { |
| 95 | token := c.Tokens[app] |
| 96 | if token == "" { |
| 97 | return fmt.Errorf("console: no team credential for %s", app) |
| 98 | } |
| 99 | var rd io.Reader |
| 100 | if body != nil { |
| 101 | b, err := json.Marshal(body) |
| 102 | if err != nil { |
| 103 | return err |
| 104 | } |
| 105 | rd = bytes.NewReader(b) |
| 106 | } |
| 107 | u := strings.TrimRight(c.Base, "/") + "/api/cli/apps/" + url.PathEscape(c.Account) + "/" + url.PathEscape(app) + path |
| 108 | req, err := http.NewRequestWithContext(ctx, method, u, rd) |
| 109 | if err != nil { |
| 110 | return err |
| 111 | } |
| 112 | req.Header.Set("Authorization", "Bearer "+token) |
| 113 | req.Header.Set("Accept", "application/json") |
| 114 | if body != nil { |
| 115 | req.Header.Set("Content-Type", "application/json") |
| 116 | } |
| 117 | client := c.HTTP |
| 118 | if client == nil { |
| 119 | client = http.DefaultClient |
| 120 | } |
| 121 | cc := *client |
| 122 | cc.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } |
| 123 | resp, err := cc.Do(req) |
| 124 | if err != nil { |
| 125 | return err |
| 126 | } |
| 127 | defer resp.Body.Close() |
| 128 | raw, err := io.ReadAll(io.LimitReader(resp.Body, 4<<20)) |
| 129 | if err != nil { |
| 130 | return err |
| 131 | } |
| 132 | if resp.StatusCode == http.StatusNotFound { |
| 133 | return ErrNotFound |
| 134 | } |
| 135 | if resp.StatusCode < 200 || resp.StatusCode > 299 { |
| 136 | var msg struct { |
| 137 | Error string `json:"error"` |
| 138 | } |
| 139 | _ = json.Unmarshal(raw, &msg) |
| 140 | return &StatusError{Code: resp.StatusCode, Message: msg.Error} |
| 141 | } |
| 142 | if out != nil { |
| 143 | if err := json.Unmarshal(raw, out); err != nil { |
| 144 | return fmt.Errorf("console: unreadable answer: %w", err) |
| 145 | } |
| 146 | } |
| 147 | return nil |
| 148 | } |
| 149 | |
| 150 | func (c *Client) guard(err error) error { |
| 151 | if err != nil { |
| 152 | return fmt.Errorf("%w: %v", ErrGuard, err) |
| 153 | } |
| 154 | return nil |
| 155 | } |
| 156 | |
| 157 | func (c *Client) checkEnv(ctx context.Context, app, env string, write bool) error { |
| 158 | if strings.TrimSpace(env) == "" { |
| 159 | return c.guard(errors.New("empty environment")) |
| 160 | } |
| 161 | if c.Guard == nil { |
| 162 | return c.guard(errors.New("no guard")) |
| 163 | } |
| 164 | return c.guard(c.Guard.Environment(ctx, app, env, write)) |
| 165 | } |
| 166 | |
| 167 | func (c *Client) checkHost(ctx context.Context, app, host string, write bool) error { |
| 168 | if c.Guard == nil { |
| 169 | return c.guard(errors.New("no guard")) |
| 170 | } |
| 171 | return c.guard(c.Guard.Host(ctx, app, host, write)) |
| 172 | } |
| 173 | |
| 174 | // Var is one config variable as GET /config answers it. Value is present |
| 175 | // for env vars only; a secret is a name and nothing else. |
| 176 | type Var struct { |
| 177 | Key string `json:"key"` |
| 178 | Kind string `json:"kind"` |
| 179 | Value string `json:"value,omitempty"` |
| 180 | } |
| 181 | |
| 182 | // Config is GET /config?environment=E. |
| 183 | type Config struct { |
| 184 | Bundle string `json:"bundle"` |
| 185 | Environments []string `json:"environments"` |
| 186 | Vars []Var `json:"vars"` |
| 187 | SecretsPubKey string `json:"secrets_pubkey"` |
| 188 | SecretsAccount string `json:"secrets_account"` |
| 189 | } |
| 190 | |
| 191 | // Keys is the config's variables by name. |
| 192 | func (c Config) Keys() map[string]Var { |
| 193 | out := make(map[string]Var, len(c.Vars)) |
| 194 | for _, v := range c.Vars { |
| 195 | out[v.Key] = v |
| 196 | } |
| 197 | return out |
| 198 | } |
| 199 | |
| 200 | // GetConfig reads an owned environment. For a team credential a 404 means |
| 201 | // absent or not this scope's; found is false then. |
| 202 | func (c *Client) GetConfig(ctx context.Context, app, env string) (Config, bool, error) { |
| 203 | if err := c.checkEnv(ctx, app, env, false); err != nil { |
| 204 | return Config{}, false, err |
| 205 | } |
| 206 | var out Config |
| 207 | err := c.do(ctx, app, http.MethodGet, "/config?environment="+url.QueryEscape(env), nil, &out) |
| 208 | if errors.Is(err, ErrNotFound) { |
| 209 | return Config{}, false, nil |
| 210 | } |
| 211 | return out, err == nil, err |
| 212 | } |
| 213 | |
| 214 | // SetVar is one variable to write. A secret carries its sealed envelope. |
| 215 | type SetVar struct { |
| 216 | Kind string `json:"kind"` |
| 217 | Value string `json:"value,omitempty"` |
| 218 | Envelope string `json:"envelope,omitempty"` |
| 219 | } |
| 220 | |
| 221 | // PutResult is PUT /config's answer. |
| 222 | type PutResult struct { |
| 223 | Result string `json:"result"` |
| 224 | Removed int `json:"removed"` |
| 225 | Restart *struct { |
| 226 | Known bool `json:"known"` |
| 227 | Hosts []struct { |
| 228 | Host string `json:"host"` |
| 229 | } `json:"hosts"` |
| 230 | } `json:"restart"` |
| 231 | } |
| 232 | |
| 233 | // RestartsHosts reports whether the write landed under a running |
| 234 | // instance (the console's restart notice names one), or the console could |
| 235 | // not tell. |
| 236 | func (p PutResult) RestartsHosts() bool { |
| 237 | return p.Restart != nil && (!p.Restart.Known || len(p.Restart.Hosts) > 0) |
| 238 | } |
| 239 | |
| 240 | // PutConfig writes set and unset into env in one CAS write. A platform- |
| 241 | // managed key in either refuses the whole request here. |
| 242 | func (c *Client) PutConfig(ctx context.Context, app, env string, set map[string]SetVar, unset []string, message string) (PutResult, error) { |
| 243 | if err := c.checkEnv(ctx, app, env, true); err != nil { |
| 244 | return PutResult{}, err |
| 245 | } |
| 246 | for k := range set { |
| 247 | if PlatformManaged(k) { |
| 248 | return PutResult{}, c.guard(fmt.Errorf("set of platform-managed key %s", k)) |
| 249 | } |
| 250 | if OperatorOnly(k) { |
| 251 | return PutResult{}, c.guard(fmt.Errorf("set of operator-only key %s", k)) |
| 252 | } |
| 253 | } |
| 254 | for _, k := range unset { |
| 255 | if PlatformManaged(k) { |
| 256 | return PutResult{}, c.guard(fmt.Errorf("unset of platform-managed key %s", k)) |
| 257 | } |
| 258 | } |
| 259 | if len(set) == 0 && len(unset) == 0 { |
| 260 | return PutResult{}, nil |
| 261 | } |
| 262 | body := map[string]any{"environment": env, "message": message, "set": set} |
| 263 | if len(unset) > 0 { |
| 264 | body["unset"] = unset |
| 265 | } |
| 266 | var out PutResult |
| 267 | err := c.do(ctx, app, http.MethodPut, "/config", body, &out) |
| 268 | return out, err |
| 269 | } |
| 270 | |
| 271 | // Instance is the part of an instance record Alta reads. |
| 272 | type Instance struct { |
| 273 | Host string `json:"host"` |
| 274 | App string `json:"app"` |
| 275 | Account string `json:"account"` |
| 276 | Environment string `json:"environment"` |
| 277 | Kind string `json:"kind"` |
| 278 | } |
| 279 | |
| 280 | // Rollout is the box's report for one host, on the list door only. |
| 281 | type Rollout struct { |
| 282 | Installed string `json:"installed"` |
| 283 | Serving string `json:"serving"` |
| 284 | Awake bool `json:"awake"` |
| 285 | ConfigPending bool `json:"config_pending"` |
| 286 | // Transient: the process is starting or stopping. |
| 287 | Transient bool `json:"transient"` |
| 288 | } |
| 289 | |
| 290 | // ListedInstance is one row of GET /instances. |
| 291 | type ListedInstance struct { |
| 292 | Instance |
| 293 | StagedVersion string `json:"staged_version"` |
| 294 | Health string `json:"health"` |
| 295 | Rollout *Rollout `json:"rollout"` |
| 296 | } |
| 297 | |
| 298 | // GetInstance reads one record. |
| 299 | func (c *Client) GetInstance(ctx context.Context, app, host string) (Instance, bool, error) { |
| 300 | if err := c.checkHost(ctx, app, host, false); err != nil { |
| 301 | return Instance{}, false, err |
| 302 | } |
| 303 | var out Instance |
| 304 | err := c.do(ctx, app, http.MethodGet, "/instances/"+url.PathEscape(host), nil, &out) |
| 305 | if errors.Is(err, ErrNotFound) { |
| 306 | return Instance{}, false, nil |
| 307 | } |
| 308 | return out, err == nil, err |
| 309 | } |
| 310 | |
| 311 | // ListedHost finds host on the list door, which alone carries the box's |
| 312 | // rollout report (serving build). |
| 313 | func (c *Client) ListedHost(ctx context.Context, app, host string) (ListedInstance, bool, error) { |
| 314 | if err := c.checkHost(ctx, app, host, false); err != nil { |
| 315 | return ListedInstance{}, false, err |
| 316 | } |
| 317 | var out struct { |
| 318 | Instances []ListedInstance `json:"instances"` |
| 319 | } |
| 320 | if err := c.do(ctx, app, http.MethodGet, "/instances?q="+url.QueryEscape(host), nil, &out); err != nil { |
| 321 | return ListedInstance{}, false, err |
| 322 | } |
| 323 | for _, row := range out.Instances { |
| 324 | if row.Host == host { |
| 325 | return row, true, nil |
| 326 | } |
| 327 | } |
| 328 | return ListedInstance{}, false, nil |
| 329 | } |
| 330 | |
| 331 | // CreateInstance creates a socket-backed instance bound to env: the only |
| 332 | // kind a team credential may create. |
| 333 | func (c *Client) CreateInstance(ctx context.Context, app, host, env, message string) error { |
| 334 | if err := c.checkHost(ctx, app, host, true); err != nil { |
| 335 | return err |
| 336 | } |
| 337 | if err := c.checkEnv(ctx, app, env, true); err != nil { |
| 338 | return err |
| 339 | } |
| 340 | return c.do(ctx, app, http.MethodPost, "/instances", map[string]any{"host": host, "environment": env, "message": message}, nil) |
| 341 | } |
| 342 | |
| 343 | // DeleteInstance deletes a record; only inside a deprovision run. |
| 344 | func (c *Client) DeleteInstance(ctx context.Context, app, host string) error { |
| 345 | if err := c.checkHost(ctx, app, host, true); err != nil { |
| 346 | return err |
| 347 | } |
| 348 | if err := c.guard(c.Guard.Delete(ctx, app, host)); err != nil { |
| 349 | return err |
| 350 | } |
| 351 | err := c.do(ctx, app, http.MethodDelete, "/instances/"+url.PathEscape(host), nil, nil) |
| 352 | if errors.Is(err, ErrNotFound) { |
| 353 | return nil |
| 354 | } |
| 355 | return err |
| 356 | } |
| 357 | |
| 358 | // Domain is one hostname claim as the per-host door answers it. State is |
| 359 | // #299's lifecycle word; the legacy Status is never read. |
| 360 | type Domain struct { |
| 361 | Host string `json:"host"` |
| 362 | Route string `json:"route"` |
| 363 | State string `json:"state"` |
| 364 | Reason string `json:"reason"` |
| 365 | Detail string `json:"detail"` |
| 366 | Verified bool `json:"verified"` |
| 367 | } |
| 368 | |
| 369 | // GetDomain reads one claim. |
| 370 | func (c *Client) GetDomain(ctx context.Context, app, host string) (Domain, bool, error) { |
| 371 | if err := c.checkHost(ctx, app, host, false); err != nil { |
| 372 | return Domain{}, false, err |
| 373 | } |
| 374 | var out struct { |
| 375 | Domain Domain `json:"domain"` |
| 376 | } |
| 377 | err := c.do(ctx, app, http.MethodGet, "/domains/"+url.PathEscape(host), nil, &out) |
| 378 | if errors.Is(err, ErrNotFound) { |
| 379 | return Domain{}, false, nil |
| 380 | } |
| 381 | return out.Domain, err == nil, err |
| 382 | } |
| 383 | |
| 384 | // AttachDomain claims host for route (explicit host, no wildcard). |
| 385 | func (c *Client) AttachDomain(ctx context.Context, app, host, route, message string) error { |
| 386 | if err := c.checkHost(ctx, app, host, true); err != nil { |
| 387 | return err |
| 388 | } |
| 389 | if err := c.checkHost(ctx, app, route, true); err != nil { |
| 390 | return err |
| 391 | } |
| 392 | return c.do(ctx, app, http.MethodPost, "/domains", map[string]any{"host": host, "route": route, "message": message}, nil) |
| 393 | } |
| 394 | |
| 395 | // DetachDomain removes a claim; only inside a deprovision run. |
| 396 | func (c *Client) DetachDomain(ctx context.Context, app, host string) error { |
| 397 | if err := c.checkHost(ctx, app, host, true); err != nil { |
| 398 | return err |
| 399 | } |
| 400 | if err := c.guard(c.Guard.Delete(ctx, app, host)); err != nil { |
| 401 | return err |
| 402 | } |
| 403 | err := c.do(ctx, app, http.MethodDelete, "/domains/"+url.PathEscape(host), nil, nil) |
| 404 | if errors.Is(err, ErrNotFound) { |
| 405 | return nil |
| 406 | } |
| 407 | return err |
| 408 | } |
| 409 | |
| 410 | // RestartHost restarts one in-scope instance. |
| 411 | func (c *Client) RestartHost(ctx context.Context, app, host, message string) error { |
| 412 | if err := c.checkHost(ctx, app, host, true); err != nil { |
| 413 | return err |
| 414 | } |
| 415 | return c.do(ctx, app, http.MethodPost, "/restart/scope", map[string]any{"host": host, "message": message}, nil) |
| 416 | } |
| 417 | |