package adopt import ( "bytes" "context" "encoding/json" "errors" "io" "mime" "net" "net/http" "net/url" "strings" "time" "amadan.net/oficina/alta/provision" ) // OpsShape is what GET /api/v1/operations answers, reduced to the shapes // adoption tells apart. Slides, Calls and Equipo already answer their own 401 there // (an app middleware with a non-agent error body), so a bare 401 proves // nothing: only agent-access's own answer counts, in exactly the shape // agent-access writes it (agent-access f08bfc1, http.go Authenticate, // writeFailure and writeJSON). Base's own door, which serves Equipo's // Assistant on a Base host token, already writes that exact shape. type OpsShape string const ( OpsAbsent OpsShape = "absent" // 404: the delegated-access code is not running OpsApp401 OpsShape = "app-401" // a 401 that is not agent-access's challenge OpsAgent401 OpsShape = "agent-401" // agent-access's challenge OpsAgent200 OpsShape = "agent-200" // agent-access's operations list OpsOther OpsShape = "other" // anything else, a lookalike 200 included ) // BaselineOps is what app's operations door answers before adoption // (Paul, 2026-11-17, Home discussion 103): Slides, Calls and Equipo their own // middleware's 401, every other app a 404. Preflight refuses any other // baseline, and Delivered holds each app to its own transition. // // Base is the one held door (Paul approved, 2026-11-23, // docs/base-adoption.md): its /api/v1/operations is already agent-shaped // before adoption (carlos/base internal/operations: a Bearer challenge, // no-store, error.code unauthenticated), and Base reads neither agent key, // so no restart can move it. Its baseline is agent-401 and Delivered // requires agent-401 still, never a 200 without a token. func BaselineOps(app provision.App) OpsShape { switch app.Slug { case "slides", "calls", "equipo": return OpsApp401 case "base": return OpsAgent401 } return OpsAbsent } // Delivery is what one probe saw of a running app. It carries versions and // status codes only, never a body beyond the version name. type Delivery struct { Version, Header string Redirected bool Health int Ops OpsShape At time.Time } // agentShaped reports whether the delegated-access code answered. func (o OpsShape) agentShaped() bool { return o == OpsAgent401 || o == OpsAgent200 } // bodyLimit bounds every probe body. const bodyLimit = 1 << 20 // Probe reads origin's /api/version, /healthz and /api/v1/operations // without following a redirect: a redirect is recorded in Delivered's // input, never chased. A plain-http origin must be loopback. func Probe(ctx context.Context, h *http.Client, origin string) (Delivery, error) { u, err := url.Parse(origin) if err != nil || u.Host == "" || u.Path != "" && u.Path != "/" { return Delivery{}, errors.New("adopt: probe origin is not an origin") } if u.Scheme != "https" && !(u.Scheme == "http" && isLoopback(u.Hostname())) { return Delivery{}, errors.New("adopt: probe origin must be https") } base := u.Scheme + "://" + u.Host c := *h c.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } d := Delivery{At: time.Now().UTC()} status, hdr, body, err := get(ctx, &c, base+"/api/version") if err != nil { return Delivery{}, err } switch { case status >= 300 && status < 400: d.Redirected = true case status == http.StatusOK: d.Version = string(body) d.Header = hdr.Get("X-Carlos-Version") } status, _, _, err = get(ctx, &c, base+"/healthz") if err != nil { return Delivery{}, err } if status >= 300 && status < 400 { d.Redirected = true } d.Health = status status, hdr, body, err = get(ctx, &c, base+"/api/v1/operations") if err != nil { return Delivery{}, err } if status >= 300 && status < 400 { d.Redirected = true } d.Ops = shape(status, hdr, body) return d, nil } func isLoopback(host string) bool { if host == "localhost" { return true } ip := net.ParseIP(host) return ip != nil && ip.IsLoopback() } // get does one GET. Its errors name the step, never the URL or a body. func get(ctx context.Context, c *http.Client, target string) (int, http.Header, []byte, error) { req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil) if err != nil { return 0, nil, nil, errors.New("adopt: probe request refused") } resp, err := c.Do(req) if err != nil { return 0, nil, nil, errors.New("adopt: probe unreachable") } defer resp.Body.Close() // One byte past the limit tells "exactly the limit" from "cut off". body, err := io.ReadAll(io.LimitReader(resp.Body, bodyLimit+1)) if err != nil { return 0, nil, nil, errors.New("adopt: probe answer unreadable") } if len(body) > bodyLimit { return 0, nil, nil, errors.New("adopt: probe answer too large") } return resp.StatusCode, resp.Header, body, nil } // shape classifies the operations answer. agent-access answers every // request, before routing, with Cache-Control no-store, and every answer // it writes is application/json. Its two answers to GET // /api/v1/operations are: // // - agent-401: status 401, WWW-Authenticate "Bearer" or "Bearer // ", and a body that is exactly {"error":{"code": // "unauthenticated","message":}}; // - agent-200: status 200 and a body that is exactly {"operations": // [...]}, an array. // // A 401 short of agent-401 is app-401; a 200 short of agent-200 is other. // Keys are matched exactly, case included, and nothing may follow the // body's one JSON value. func shape(status int, h http.Header, body []byte) OpsShape { agent := hasToken(h.Get("Cache-Control"), "no-store") && jsonMedia(h.Get("Content-Type")) switch status { case http.StatusNotFound: return OpsAbsent case http.StatusOK: if agent && operationsList(body) { return OpsAgent200 } return OpsOther case http.StatusUnauthorized: if agent && bearerChallenge(h) && unauthenticated(body) { return OpsAgent401 } return OpsApp401 } return OpsOther } func jsonMedia(v string) bool { media, _, err := mime.ParseMediaType(v) return err == nil && media == "application/json" } // bearerChallenge is one WWW-Authenticate, the Bearer scheme with or // without parameters. func bearerChallenge(h http.Header) bool { vs := h.Values("WWW-Authenticate") return len(vs) == 1 && (vs[0] == "Bearer" || strings.HasPrefix(vs[0], "Bearer ")) } // object decodes body as exactly one JSON object holding exactly keys. func object(body []byte, keys ...string) (map[string]json.RawMessage, bool) { dec := json.NewDecoder(bytes.NewReader(body)) var m map[string]json.RawMessage if dec.Decode(&m) != nil || m == nil || len(m) != len(keys) { return nil, false } if _, err := dec.Token(); err != io.EOF { return nil, false } for _, k := range keys { if _, ok := m[k]; !ok { return nil, false } } return m, true } func unauthenticated(body []byte) bool { top, ok := object(body, "error") if !ok { return false } e, ok := object(top["error"], "code", "message") if !ok { return false } var code, message string return json.Unmarshal(e["code"], &code) == nil && code == "unauthenticated" && json.Unmarshal(e["message"], &message) == nil && message != "" } func operationsList(body []byte) bool { top, ok := object(body, "operations") if !ok { return false } var ops []json.RawMessage return bytes.HasPrefix(bytes.TrimSpace(top["operations"]), []byte("[")) && json.Unmarshal(top["operations"], &ops) == nil } func hasToken(header, want string) bool { for _, t := range strings.Split(header, ",") { if strings.EqualFold(strings.TrimSpace(t), want) { return true } } return false } // sameServing checks the parts delivery and rollback share: the version // and header unchanged, no redirect, health 200. func sameServing(before, now Delivery) error { switch { case now.Redirected: return errors.New("adopt: the app redirected") case before.Version == "" || now.Version != before.Version: return errors.New("adopt: the served version changed") case before.Header == "" || now.Header != before.Header: return errors.New("adopt: the version header changed") case now.Health != http.StatusOK: return errors.New("adopt: the app is not healthy") } return nil } // Delivered says app's restart delivered the new configuration: the same // version and header, no redirect, health 200, and the operations door // moved as app's must (Paul, 2026-11-17). Before, it answered as // BaselineOps(app) says; now, a 404 must have become agent-401 or // agent-200, Slides', Calls' and Equipo's own 401 must have become // agent-401, agent-access's challenge, and Base's agent-401 must still be // agent-401 (the held door: for Base this proves no delivery of the keys). func Delivered(app provision.App, before, now Delivery) error { if err := sameServing(before, now); err != nil { return err } return opsMoved(app, before, now) } // opsMoved is Delivered's operations-door rule: the door answered before // as BaselineOps(app) says, and now gives agent-access's own answer as // app's must. A 200 counts only from a 404, so Base's held door (an // agent-401 baseline) passes only as agent-401. func opsMoved(app provision.App, before, now Delivery) error { if before.Ops != BaselineOps(app) { return errors.New("adopt: the operations door did not answer before the change as this app's does") } switch { case now.Ops == OpsAgent401: case now.Ops == OpsAgent200 && before.Ops == OpsAbsent: default: return errors.New("adopt: the delegated-access door is not answering") } return nil } // Reverted says a rollback restart completed: the same version and header, // health 200, and the operations door back to the before shape. func Reverted(before, now Delivery) error { if err := sameServing(before, now); err != nil { return err } if now.Ops != before.Ops { return errors.New("adopt: the operations door has not returned to its earlier shape") } return nil } // signInIdentity reads the Home issuer and consumer an app really signs // in with, from the redirect its GET /auth/start answers. Apps store both // as secrets, whose values the config API never returns, and the redirect // is public. The redirect is never followed. Anything but a 302 or 303 // from an https origin, carrying the one Location authorizeTarget accepts, // answers two empty strings, which the mismatch codes then refuse; that // includes a request that fails. The Location holds a sign-in nonce, so it // is neither returned nor logged. func signInIdentity(ctx context.Context, h *http.Client, origin string) (issuer, consumer string) { u, err := url.Parse(origin) if err != nil || u.Scheme != "https" || u.Host == "" { return "", "" } c := *h c.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } status, hdr, _, err := get(ctx, &c, origin+"/auth/start") if err != nil || (status != http.StatusFound && status != http.StatusSeeOther) { return "", "" } loc := hdr.Values("Location") if len(loc) != 1 { return "", "" } return authorizeTarget(loc[0]) } // authorizeTarget is the issuer and consumer of a Location that is exactly // HomeIssuerOrigin's /authorize with one non-empty consumer parameter, and // two empty strings for any other. A # or a backslash is refused in the // raw text: url.Parse drops an empty fragment and keeps a backslash in the // query, and browsers read a backslash differently from it. func authorizeTarget(location string) (issuer, consumer string) { if strings.ContainsAny(location, "#\\") { return "", "" } u, err := url.Parse(location) if err != nil || u.User != nil || u.Scheme+"://"+u.Host != HomeIssuerOrigin || u.Path != "/authorize" || u.RawPath != "" { return "", "" } q, err := url.ParseQuery(u.RawQuery) if err != nil || len(q["consumer"]) != 1 || q["consumer"][0] == "" { return "", "" } return HomeIssuerOrigin, q["consumer"][0] }