| 1 | // Package fakeconsole is an in-memory CARLOS console as a `team` |
| 2 | // credential meets it (carlos/platform team-scoped-credentials.md §4): |
| 3 | // the thirteen scoped doors Alta uses, each answering an out-of-scope |
| 4 | // target with the unknown target's 404; owned environments created by a |
| 5 | // team PUT; platform-managed keys refused to team writes; the mail and |
| 6 | // relay walks minting per-environment credentials on their own cadence |
| 7 | // (Walk); socket-backed instances only; explicit-host domain claims with |
| 8 | // #299's state word; restart/scope; and each team instance's public |
| 9 | // origin (/api/version, /api/team) behind Transport. |
| 10 | package fakeconsole |
| 11 | |
| 12 | import ( |
| 13 | "crypto/ecdh" |
| 14 | "crypto/rand" |
| 15 | "encoding/base64" |
| 16 | "encoding/json" |
| 17 | "fmt" |
| 18 | "io" |
| 19 | "net/http" |
| 20 | "net/http/httptest" |
| 21 | "regexp" |
| 22 | "sort" |
| 23 | "strings" |
| 24 | "sync" |
| 25 | |
| 26 | "amadan.net/oficina/alta/console" |
| 27 | ) |
| 28 | |
| 29 | // Var is a stored config variable. |
| 30 | type Var struct { |
| 31 | Kind, Value, Envelope string |
| 32 | } |
| 33 | |
| 34 | type bundle struct { |
| 35 | owner string |
| 36 | vars map[string]Var |
| 37 | } |
| 38 | |
| 39 | type inst struct { |
| 40 | env, app string |
| 41 | serving string |
| 42 | asleep bool |
| 43 | pending bool |
| 44 | restarts int |
| 45 | } |
| 46 | |
| 47 | type claim struct { |
| 48 | app, route, state string |
| 49 | polls int |
| 50 | } |
| 51 | |
| 52 | // Console is the fake. |
| 53 | type Console struct { |
| 54 | mu sync.Mutex |
| 55 | Account string |
| 56 | Scope string |
| 57 | tokens map[string]string // token -> app |
| 58 | |
| 59 | priv *ecdh.PrivateKey |
| 60 | Bound bool |
| 61 | |
| 62 | envs map[string]map[string]*bundle // app -> env -> bundle |
| 63 | instances map[string]*inst // host -> instance |
| 64 | domains map[string]*claim // host -> claim |
| 65 | |
| 66 | // MailPrefix is each app's mail declaration; an app absent has no |
| 67 | // mail enabled. Relay lists the apps with the relay enabled. |
| 68 | MailPrefix map[string]string |
| 69 | Relay map[string]bool |
| 70 | // Submission lists the apps switched to CARLOS mail submission |
| 71 | // (`carlos email submission on`): their owned environments get the |
| 72 | // From variable alone, <stem>_MAIL_FROM, and no SMTP credential. |
| 73 | Submission map[string]bool |
| 74 | // PrivateStorage lists the apps with the private-storage policy on |
| 75 | // (`carlos instances enable --private-storage`): an instance create |
| 76 | // provisions its environment's own store and delivers CARLOS_STORE_* |
| 77 | // into that environment, as CARLOS's objstore walk does. |
| 78 | // StoreEndpoint, when set, is the deployment's endpoint. |
| 79 | PrivateStorage map[string]bool |
| 80 | StoreEndpoint string |
| 81 | // Versions is what each app's build answers on /api/version, and what |
| 82 | // a box reports serving. |
| 83 | Versions map[string]string |
| 84 | // DomainPolls is how many GETs a new claim answers before it is live. |
| 85 | DomainPolls int |
| 86 | // Roster is GET /api/team's roster word for a roster-mode app. |
| 87 | Roster string |
| 88 | // ServingName overrides the box's serving report per app. |
| 89 | ServingName map[string]string |
| 90 | // VersionAnswer overrides what an app's /api/version answers. |
| 91 | VersionAnswer map[string]string |
| 92 | // NoTeamProbe: the roster-mode app serves no /api/team (Docs' main |
| 93 | // today). |
| 94 | NoTeamProbe bool |
| 95 | // SeededRoster is a seeded app's (Equipo, Base) roster word on its |
| 96 | // /api/team: "" answers "ok", once its owner exists. |
| 97 | SeededRoster string |
| 98 | // ProbeConsumer overrides the consumer an app's /api/team names. |
| 99 | ProbeConsumer map[string]string |
| 100 | // ProbeMode overrides an app's probe mode: "roster" or "seeded". |
| 101 | ProbeMode map[string]string |
| 102 | |
| 103 | // Requests is every request's method, door and app, for assertions. |
| 104 | Requests []string |
| 105 | // SecretWrites counts writes of each secret, app/env/key: a GENERATED |
| 106 | // key written twice was regenerated. |
| 107 | SecretWrites map[string]int |
| 108 | minted int |
| 109 | srv *httptest.Server |
| 110 | } |
| 111 | |
| 112 | // New builds a console for account (a sqid) whose team credentials hold |
| 113 | // scope. |
| 114 | func New(account, scope string) *Console { |
| 115 | priv, _ := ecdh.P256().GenerateKey(rand.Reader) |
| 116 | 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{}, |
| 117 | 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{}} |
| 118 | c.srv = httptest.NewServer(http.HandlerFunc(c.serve)) |
| 119 | return c |
| 120 | } |
| 121 | |
| 122 | func (c *Console) Close() { c.srv.Close() } |
| 123 | func (c *Console) URL() string { return c.srv.URL } |
| 124 | |
| 125 | // Mint is Paul's `carlos services create --role team --app A --scope S`. |
| 126 | func (c *Console) Mint(app string) string { |
| 127 | b := make([]byte, 24) |
| 128 | _, _ = rand.Read(b) |
| 129 | t := "svc_" + base64.RawURLEncoding.EncodeToString(b) |
| 130 | c.mu.Lock() |
| 131 | c.tokens[t] = app |
| 132 | c.mu.Unlock() |
| 133 | return t |
| 134 | } |
| 135 | |
| 136 | // SecretsPub is the console's secrets_pubkey. |
| 137 | func (c *Console) SecretsPub() string { |
| 138 | return base64.StdEncoding.EncodeToString(c.priv.PublicKey().Bytes()) |
| 139 | } |
| 140 | |
| 141 | // Open opens a stored secret, as a box would. |
| 142 | func (c *Console) Open(app, env, key string) (string, error) { |
| 143 | c.mu.Lock() |
| 144 | defer c.mu.Unlock() |
| 145 | b := c.envs[app][env] |
| 146 | if b == nil { |
| 147 | return "", fmt.Errorf("no env") |
| 148 | } |
| 149 | v, ok := b.vars[key] |
| 150 | if !ok || v.Kind != "secret" { |
| 151 | return "", fmt.Errorf("no secret %s", key) |
| 152 | } |
| 153 | acct := "" |
| 154 | if c.Bound { |
| 155 | acct = c.Account |
| 156 | } |
| 157 | p, err := console.Open(c.priv, acct, app, v.Envelope) |
| 158 | return string(p), err |
| 159 | } |
| 160 | |
| 161 | // Env returns a copy of an environment's variables. |
| 162 | func (c *Console) Env(app, env string) (map[string]Var, string, bool) { |
| 163 | c.mu.Lock() |
| 164 | defer c.mu.Unlock() |
| 165 | b := c.envs[app][env] |
| 166 | if b == nil { |
| 167 | return nil, "", false |
| 168 | } |
| 169 | out := map[string]Var{} |
| 170 | for k, v := range b.vars { |
| 171 | out[k] = v |
| 172 | } |
| 173 | return out, b.owner, true |
| 174 | } |
| 175 | |
| 176 | // SetEnv seeds an environment directly (a person's write, or a fork). |
| 177 | func (c *Console) SetEnv(app, env, owner string, vars map[string]Var) { |
| 178 | c.mu.Lock() |
| 179 | defer c.mu.Unlock() |
| 180 | if c.envs[app] == nil { |
| 181 | c.envs[app] = map[string]*bundle{} |
| 182 | } |
| 183 | b := &bundle{owner: owner, vars: map[string]Var{}} |
| 184 | for k, v := range vars { |
| 185 | b.vars[k] = v |
| 186 | } |
| 187 | c.envs[app][env] = b |
| 188 | } |
| 189 | |
| 190 | // AddInstance seeds an instance record (a person's create or rebind). |
| 191 | func (c *Console) AddInstance(app, host, env string) { |
| 192 | c.mu.Lock() |
| 193 | defer c.mu.Unlock() |
| 194 | c.instances[host] = &inst{env: env, app: app, serving: c.Versions[app]} |
| 195 | } |
| 196 | |
| 197 | // AddClaim seeds a hostname claim. |
| 198 | func (c *Console) AddClaim(app, host, route, state string) { |
| 199 | c.mu.Lock() |
| 200 | defer c.mu.Unlock() |
| 201 | c.domains[host] = &claim{app: app, route: route, state: state} |
| 202 | } |
| 203 | |
| 204 | // Instance reports a record. |
| 205 | func (c *Console) Instance(host string) (env string, restarts int, ok bool) { |
| 206 | c.mu.Lock() |
| 207 | defer c.mu.Unlock() |
| 208 | i, ok := c.instances[host] |
| 209 | if !ok { |
| 210 | return "", 0, false |
| 211 | } |
| 212 | return i.env, i.restarts, true |
| 213 | } |
| 214 | |
| 215 | // InstanceCount counts records. |
| 216 | func (c *Console) InstanceCount() int { |
| 217 | c.mu.Lock() |
| 218 | defer c.mu.Unlock() |
| 219 | return len(c.instances) |
| 220 | } |
| 221 | |
| 222 | // Claim reports a domain claim. |
| 223 | func (c *Console) Claim(host string) (route, state string, ok bool) { |
| 224 | c.mu.Lock() |
| 225 | defer c.mu.Unlock() |
| 226 | d, ok := c.domains[host] |
| 227 | if !ok { |
| 228 | return "", "", false |
| 229 | } |
| 230 | return d.route, d.state, true |
| 231 | } |
| 232 | |
| 233 | // PlatformCanary marks every value the walks mint: a test scans Alta's |
| 234 | // database for it. |
| 235 | const PlatformCanary = "PLATFORM-VALUE-CANARY" |
| 236 | |
| 237 | // Walk is one pass of the mail and relay walks: every owned environment |
| 238 | // of an app with mail declared gets its own SMTP credential under the |
| 239 | // declared prefix, or, for an app switched to submission, only the From |
| 240 | // variable for that prefix (CARLOS's DeliverMailFromIn); and Calls its |
| 241 | // own relay identity. Never shared with the default bundle; never written |
| 242 | // by a team credential. |
| 243 | func (c *Console) Walk() { |
| 244 | c.mu.Lock() |
| 245 | defer c.mu.Unlock() |
| 246 | for app, envs := range c.envs { |
| 247 | for _, b := range envs { |
| 248 | if b.owner == "" { |
| 249 | continue |
| 250 | } |
| 251 | if p := c.MailPrefix[app]; p != "" && c.Submission[app] { |
| 252 | stem := strings.TrimSuffix(p, "_SMTP") |
| 253 | if _, ok := b.vars[stem+"_MAIL_FROM"]; !ok { |
| 254 | b.vars[stem+"_MAIL_FROM"] = Var{Kind: "env", Value: "team@oficina.works"} |
| 255 | } |
| 256 | } else if p != "" { |
| 257 | if _, ok := b.vars[p+"_USER"]; !ok { |
| 258 | c.minted++ |
| 259 | b.vars[p+"_HOST"] = Var{Kind: "env", Value: "email-smtp.eu-west-1.amazonaws.com"} |
| 260 | b.vars[p+"_PORT"] = Var{Kind: "env", Value: "587"} |
| 261 | b.vars[p+"_FROM"] = Var{Kind: "env", Value: "team@oficina.works"} |
| 262 | b.vars[p+"_USER"] = Var{Kind: "env", Value: fmt.Sprintf("%s-USER-%d", PlatformCanary, c.minted)} |
| 263 | b.vars[p+"_PASS"] = Var{Kind: "secret", Envelope: c.sealCanary(app)} |
| 264 | } |
| 265 | } |
| 266 | if c.Relay[app] { |
| 267 | if _, ok := b.vars["CARLOS_RELAY"]; !ok { |
| 268 | b.vars["CARLOS_RELAY"] = Var{Kind: "secret", Envelope: c.sealCanary(app)} |
| 269 | } |
| 270 | } |
| 271 | } |
| 272 | } |
| 273 | } |
| 274 | |
| 275 | func (c *Console) sealCanary(app string) string { |
| 276 | acct := "" |
| 277 | if c.Bound { |
| 278 | acct = c.Account |
| 279 | } |
| 280 | e, _ := console.Seal(c.SecretsPub(), acct, app, []byte(PlatformCanary+"-SECRET")) |
| 281 | return e |
| 282 | } |
| 283 | |
| 284 | // ServingName, when set, is what a box reports serving for an app, |
| 285 | // instead of the version /api/version answers (carlos ship's release |
| 286 | // version need not be the binary's stamp). |
| 287 | func (c *Console) servingName(i *inst) string { |
| 288 | if n := c.ServingName[i.app]; n != "" { |
| 289 | return n |
| 290 | } |
| 291 | return i.serving |
| 292 | } |
| 293 | |
| 294 | // SetAsleep marks an instance's box report asleep (not awake), as a |
| 295 | // hibernated or starting instance reports. |
| 296 | func (c *Console) SetAsleep(host string, asleep bool) { |
| 297 | c.mu.Lock() |
| 298 | defer c.mu.Unlock() |
| 299 | if i, ok := c.instances[host]; ok { |
| 300 | i.asleep = asleep |
| 301 | } |
| 302 | } |
| 303 | |
| 304 | // SetDomainState moves a claim's state word. |
| 305 | func (c *Console) SetDomainState(host, state string) { |
| 306 | c.mu.Lock() |
| 307 | defer c.mu.Unlock() |
| 308 | if d, ok := c.domains[host]; ok { |
| 309 | d.state = state |
| 310 | } |
| 311 | } |
| 312 | |
| 313 | // ---- the doors ---- |
| 314 | |
| 315 | var path = regexp.MustCompile(`^/api/cli/apps/([^/]+)/([^/]+)(/.*)$`) |
| 316 | |
| 317 | func writeJSON(w http.ResponseWriter, status int, v any) { |
| 318 | w.Header().Set("Content-Type", "application/json") |
| 319 | w.WriteHeader(status) |
| 320 | _ = json.NewEncoder(w).Encode(v) |
| 321 | } |
| 322 | |
| 323 | func refuse(w http.ResponseWriter, status int, msg string) { |
| 324 | writeJSON(w, status, map[string]string{"error": msg}) |
| 325 | } |
| 326 | |
| 327 | func (c *Console) owned(app, env string) bool { |
| 328 | b := c.envs[app][env] |
| 329 | return env != "" && b != nil && b.owner == c.Scope |
| 330 | } |
| 331 | |
| 332 | func (c *Console) inScopeHost(app, host string) (*inst, bool) { |
| 333 | i, ok := c.instances[host] |
| 334 | if !ok || i.app != app || !c.owned(app, i.env) { |
| 335 | return nil, false |
| 336 | } |
| 337 | return i, true |
| 338 | } |
| 339 | |
| 340 | func (c *Console) serve(w http.ResponseWriter, r *http.Request) { |
| 341 | c.mu.Lock() |
| 342 | defer c.mu.Unlock() |
| 343 | m := path.FindStringSubmatch(r.URL.Path) |
| 344 | if m == nil { |
| 345 | http.NotFound(w, r) |
| 346 | return |
| 347 | } |
| 348 | account, app, rest := m[1], m[2], m[3] |
| 349 | c.Requests = append(c.Requests, r.Method+" "+strings.SplitN(rest, "/", 3)[1]+" "+app) |
| 350 | bound := c.tokens[strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ")] |
| 351 | if bound == "" { |
| 352 | refuse(w, 401, "not signed in") |
| 353 | return |
| 354 | } |
| 355 | // teamInScope: the path must name the credential's own account by |
| 356 | // sqid and its own app, or 404. |
| 357 | if account != c.Account || app != bound { |
| 358 | http.NotFound(w, r) |
| 359 | return |
| 360 | } |
| 361 | var body map[string]any |
| 362 | if r.Body != nil { |
| 363 | raw, _ := io.ReadAll(r.Body) |
| 364 | if len(raw) > 0 && json.Unmarshal(raw, &body) != nil { |
| 365 | refuse(w, 400, "bad json") |
| 366 | return |
| 367 | } |
| 368 | } |
| 369 | s := func(k string) string { v, _ := body[k].(string); return v } |
| 370 | switch { |
| 371 | case r.Method == http.MethodGet && rest == "/config": |
| 372 | env := r.URL.Query().Get("environment") |
| 373 | if !c.owned(app, env) { |
| 374 | http.NotFound(w, r) |
| 375 | return |
| 376 | } |
| 377 | var vars []map[string]any |
| 378 | keys := make([]string, 0) |
| 379 | for k := range c.envs[app][env].vars { |
| 380 | keys = append(keys, k) |
| 381 | } |
| 382 | sort.Strings(keys) |
| 383 | for _, k := range keys { |
| 384 | v := c.envs[app][env].vars[k] |
| 385 | row := map[string]any{"key": k, "kind": v.Kind} |
| 386 | if v.Kind == "env" { |
| 387 | row["value"] = v.Value |
| 388 | } |
| 389 | vars = append(vars, row) |
| 390 | } |
| 391 | out := map[string]any{"bundle": env, "environments": []string{env}, "vars": vars, "secrets_pubkey": c.SecretsPub()} |
| 392 | if c.Bound { |
| 393 | out["secrets_account"] = c.Account |
| 394 | } |
| 395 | writeJSON(w, 200, out) |
| 396 | case r.Method == http.MethodPut && rest == "/config": |
| 397 | env := s("environment") |
| 398 | if env == "" { |
| 399 | http.NotFound(w, r) |
| 400 | return |
| 401 | } |
| 402 | b := c.envs[app][env] |
| 403 | if b != nil && b.owner != c.Scope { |
| 404 | http.NotFound(w, r) |
| 405 | return |
| 406 | } |
| 407 | if b == nil { |
| 408 | // Capture rules: a name a record references is not the scope's. |
| 409 | for _, i := range c.instances { |
| 410 | if i.app == app && i.env == env { |
| 411 | http.NotFound(w, r) |
| 412 | return |
| 413 | } |
| 414 | } |
| 415 | } |
| 416 | set, _ := body["set"].(map[string]any) |
| 417 | unset, _ := body["unset"].([]any) |
| 418 | for k := range set { |
| 419 | if console.PlatformManaged(k) { |
| 420 | refuse(w, 403, "a team credential cannot set or unset a platform-managed key ("+k+")") |
| 421 | return |
| 422 | } |
| 423 | } |
| 424 | for _, k := range unset { |
| 425 | if console.PlatformManaged(fmt.Sprint(k)) { |
| 426 | refuse(w, 403, "a team credential cannot set or unset a platform-managed key") |
| 427 | return |
| 428 | } |
| 429 | } |
| 430 | if b == nil { |
| 431 | if c.envs[app] == nil { |
| 432 | c.envs[app] = map[string]*bundle{} |
| 433 | } |
| 434 | b = &bundle{owner: c.Scope, vars: map[string]Var{}} |
| 435 | c.envs[app][env] = b |
| 436 | } |
| 437 | for k, raw := range set { |
| 438 | v, _ := raw.(map[string]any) |
| 439 | kind, _ := v["kind"].(string) |
| 440 | if kind == "secret" { |
| 441 | e, _ := v["envelope"].(string) |
| 442 | if _, err := base64.StdEncoding.DecodeString(e); err != nil || e == "" { |
| 443 | refuse(w, 400, "var "+k+": envelope is not valid base64") |
| 444 | return |
| 445 | } |
| 446 | if val, _ := v["value"].(string); val != "" { |
| 447 | refuse(w, 400, "plaintext secret") |
| 448 | return |
| 449 | } |
| 450 | b.vars[k] = Var{Kind: "secret", Envelope: e} |
| 451 | c.SecretWrites[app+"/"+env+"/"+k]++ |
| 452 | } else { |
| 453 | val, _ := v["value"].(string) |
| 454 | b.vars[k] = Var{Kind: "env", Value: val} |
| 455 | } |
| 456 | } |
| 457 | removed := 0 |
| 458 | for _, k := range unset { |
| 459 | if _, ok := b.vars[fmt.Sprint(k)]; ok { |
| 460 | delete(b.vars, fmt.Sprint(k)) |
| 461 | removed++ |
| 462 | } |
| 463 | } |
| 464 | var hosts []map[string]string |
| 465 | for h, i := range c.instances { |
| 466 | if i.app == app && i.env == env { |
| 467 | i.pending = true |
| 468 | hosts = append(hosts, map[string]string{"host": h}) |
| 469 | } |
| 470 | } |
| 471 | writeJSON(w, 200, map[string]any{"result": "ok", "removed": removed, "restart": map[string]any{"known": true, "hosts": hosts}}) |
| 472 | case r.Method == http.MethodGet && rest == "/instances": |
| 473 | q := r.URL.Query().Get("q") |
| 474 | var rows []map[string]any |
| 475 | for h, i := range c.instances { |
| 476 | if i.app != app || !c.owned(app, i.env) || (q != "" && !strings.Contains(h, q)) { |
| 477 | continue |
| 478 | } |
| 479 | row := map[string]any{"host": h, "app": app, "account": c.Account, "environment": i.env, "health": "Running", "staged_version": i.serving} |
| 480 | if i.serving != "" { |
| 481 | row["rollout"] = map[string]any{"installed": i.serving, "serving": c.servingName(i), "awake": !i.asleep, "config_pending": i.pending} |
| 482 | } |
| 483 | rows = append(rows, row) |
| 484 | } |
| 485 | writeJSON(w, 200, map[string]any{"instances": rows, "total": len(rows)}) |
| 486 | case r.Method == http.MethodPost && rest == "/instances": |
| 487 | env := s("environment") |
| 488 | if !c.owned(app, env) { |
| 489 | http.NotFound(w, r) |
| 490 | return |
| 491 | } |
| 492 | if s("kind") != "" && s("kind") != "instance" { |
| 493 | refuse(w, 403, "creates socket-backed instances only") |
| 494 | return |
| 495 | } |
| 496 | host := s("host") |
| 497 | if !strings.HasSuffix(host, "."+c.Account+".oncarlos.com") { |
| 498 | refuse(w, 400, "invalid host") |
| 499 | return |
| 500 | } |
| 501 | if _, ok := c.instances[host]; ok { |
| 502 | refuse(w, 409, "host already exists") |
| 503 | return |
| 504 | } |
| 505 | if c.PrivateStorage[app] { |
| 506 | // The store first, then the record (CARLOS's create door). |
| 507 | b := c.envs[app][env] |
| 508 | b.vars["CARLOS_STORE_BUCKET"] = Var{Kind: "env", Value: "carlos-" + c.Account + "-" + app + "-" + env} |
| 509 | b.vars["CARLOS_STORE_REGION"] = Var{Kind: "env", Value: "eu-west-1"} |
| 510 | if c.StoreEndpoint != "" { |
| 511 | b.vars["CARLOS_STORE_ENDPOINT"] = Var{Kind: "env", Value: c.StoreEndpoint} |
| 512 | } |
| 513 | b.vars["CARLOS_STORE_ACCESS_KEY"] = Var{Kind: "secret", Envelope: c.sealCanary(app)} |
| 514 | b.vars["CARLOS_STORE_SECRET_KEY"] = Var{Kind: "secret", Envelope: c.sealCanary(app)} |
| 515 | } |
| 516 | c.instances[host] = &inst{env: env, app: app, serving: c.Versions[app]} |
| 517 | writeJSON(w, 200, map[string]any{"host": host, "environment": env}) |
| 518 | case strings.HasPrefix(rest, "/instances/"): |
| 519 | host := strings.TrimPrefix(rest, "/instances/") |
| 520 | i, ok := c.inScopeHost(app, host) |
| 521 | if !ok { |
| 522 | http.NotFound(w, r) |
| 523 | return |
| 524 | } |
| 525 | switch r.Method { |
| 526 | case http.MethodGet: |
| 527 | writeJSON(w, 200, map[string]any{"host": host, "app": app, "account": c.Account, "environment": i.env}) |
| 528 | case http.MethodDelete: |
| 529 | delete(c.instances, host) |
| 530 | writeJSON(w, 200, map[string]any{"host": host, "deleted": true}) |
| 531 | default: |
| 532 | refuse(w, 405, "method") |
| 533 | } |
| 534 | case r.Method == http.MethodPost && rest == "/domains": |
| 535 | route := strings.ToLower(s("route")) |
| 536 | if _, ok := c.inScopeHost(app, route); !ok { |
| 537 | http.NotFound(w, r) |
| 538 | return |
| 539 | } |
| 540 | host := s("host") |
| 541 | if body["wildcard"] != nil || body["catchall"] != nil { |
| 542 | refuse(w, 403, "no wildcard") |
| 543 | return |
| 544 | } |
| 545 | if d, ok := c.domains[host]; ok && d.route != route { |
| 546 | refuse(w, 409, "hostname is taken") |
| 547 | return |
| 548 | } |
| 549 | if _, ok := c.domains[host]; !ok { |
| 550 | c.domains[host] = &claim{app: app, route: route, state: "checking"} |
| 551 | } |
| 552 | writeJSON(w, 200, map[string]any{"host": host, "route": route, "created": true}) |
| 553 | case strings.HasPrefix(rest, "/domains/"): |
| 554 | host := strings.TrimPrefix(rest, "/domains/") |
| 555 | d, ok := c.domains[host] |
| 556 | if !ok || d.app != app || d.route == "" { |
| 557 | refuse(w, 404, "no such hostname") |
| 558 | return |
| 559 | } |
| 560 | if _, in := c.inScopeHost(app, d.route); !in { |
| 561 | refuse(w, 404, "no such hostname") |
| 562 | return |
| 563 | } |
| 564 | switch r.Method { |
| 565 | case http.MethodGet: |
| 566 | if d.state != "live" { |
| 567 | d.polls++ |
| 568 | if d.polls > c.DomainPolls && d.state == "checking" { |
| 569 | d.state = "live" |
| 570 | } |
| 571 | } |
| 572 | writeJSON(w, 200, map[string]any{"domain": map[string]any{"host": host, "route": d.route, "status": "pending", "state": d.state, "verified": true}}) |
| 573 | case http.MethodDelete: |
| 574 | delete(c.domains, host) |
| 575 | writeJSON(w, 200, map[string]any{"host": host, "removed": true}) |
| 576 | } |
| 577 | case r.Method == http.MethodPost && rest == "/restart/scope": |
| 578 | i, ok := c.inScopeHost(app, s("host")) |
| 579 | if !ok { |
| 580 | http.NotFound(w, r) |
| 581 | return |
| 582 | } |
| 583 | i.restarts++ |
| 584 | i.pending = false |
| 585 | writeJSON(w, 200, map[string]any{"result": "ok"}) |
| 586 | default: |
| 587 | // Every other door is closed to the team role. |
| 588 | refuse(w, 403, "not for a team credential") |
| 589 | } |
| 590 | } |
| 591 | |
| 592 | // Transport routes the team instances' public origins |
| 593 | // (https://<label>.<app>.oficina.works) to the fake: /api/version is the |
| 594 | // build an instance serves, behind a live claim; /api/team is the |
| 595 | // readiness probe for a roster-mode app. |
| 596 | func (c *Console) Transport() http.RoundTripper { |
| 597 | return roundTrip(func(r *http.Request) (*http.Response, error) { |
| 598 | c.mu.Lock() |
| 599 | defer c.mu.Unlock() |
| 600 | rec := httptest.NewRecorder() |
| 601 | d, ok := c.domains[r.URL.Host] |
| 602 | var i *inst |
| 603 | if ok { |
| 604 | i = c.instances[d.route] |
| 605 | } |
| 606 | switch { |
| 607 | case !ok || d.state != "live" || i == nil: |
| 608 | return nil, fmt.Errorf("fakeconsole: %s does not resolve", r.URL.Host) |
| 609 | case r.URL.Path == "/api/version": |
| 610 | if v, ok := c.VersionAnswer[i.app]; ok { |
| 611 | rec.WriteString(v) |
| 612 | } else { |
| 613 | rec.WriteString(i.serving) |
| 614 | } |
| 615 | case r.URL.Path == "/api/team" && !c.NoTeamProbe: |
| 616 | // The six have roster mode; Equipo and Base answer seeded |
| 617 | // (their owners come from the environment). |
| 618 | p := strings.ToUpper(i.app) |
| 619 | b := c.envs[i.app][i.env] |
| 620 | consumer := b.vars[p+"_HOME_CONSUMER_ID"].Value |
| 621 | if v, ok := c.ProbeConsumer[i.app]; ok { |
| 622 | consumer = v |
| 623 | } |
| 624 | mode := "roster" |
| 625 | if i.app == "equipo" || i.app == "base" { |
| 626 | mode = "seeded" |
| 627 | } |
| 628 | if v, ok := c.ProbeMode[i.app]; ok { |
| 629 | mode = v |
| 630 | } |
| 631 | rec.Header().Set("Content-Type", "application/json") |
| 632 | if mode == "seeded" { |
| 633 | roster := c.SeededRoster |
| 634 | if roster == "" { |
| 635 | roster = "ok" |
| 636 | } |
| 637 | _ = json.NewEncoder(rec).Encode(map[string]any{"team_mode": false, "seeded": true, "consumer": consumer, "roster": roster}) |
| 638 | break |
| 639 | } |
| 640 | _, token := b.vars[p+"_TEAM_ROSTER_TOKEN"] |
| 641 | roster := c.Roster |
| 642 | if !token { |
| 643 | roster = "unknown" |
| 644 | } |
| 645 | _ = json.NewEncoder(rec).Encode(map[string]any{"team_mode": token, "consumer": consumer, "roster": roster}) |
| 646 | default: |
| 647 | rec.WriteHeader(404) |
| 648 | } |
| 649 | return rec.Result(), nil |
| 650 | }) |
| 651 | } |
| 652 | |
| 653 | type roundTrip func(*http.Request) (*http.Response, error) |
| 654 | |
| 655 | func (f roundTrip) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } |
| 656 | |