| 1 | package adopt |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "encoding/json" |
| 7 | "errors" |
| 8 | "io" |
| 9 | "mime" |
| 10 | "net" |
| 11 | "net/http" |
| 12 | "net/url" |
| 13 | "strings" |
| 14 | "time" |
| 15 | |
| 16 | "amadan.net/oficina/alta/provision" |
| 17 | ) |
| 18 | |
| 19 | // OpsShape is what GET /api/v1/operations answers, reduced to the shapes |
| 20 | // adoption tells apart. Slides, Calls and Equipo already answer their own 401 there |
| 21 | // (an app middleware with a non-agent error body), so a bare 401 proves |
| 22 | // nothing: only agent-access's own answer counts, in exactly the shape |
| 23 | // agent-access writes it (agent-access f08bfc1, http.go Authenticate, |
| 24 | // writeFailure and writeJSON). Base's own door, which serves Equipo's |
| 25 | // Assistant on a Base host token, already writes that exact shape. |
| 26 | type OpsShape string |
| 27 | |
| 28 | const ( |
| 29 | OpsAbsent OpsShape = "absent" // 404: the delegated-access code is not running |
| 30 | OpsApp401 OpsShape = "app-401" // a 401 that is not agent-access's challenge |
| 31 | OpsAgent401 OpsShape = "agent-401" // agent-access's challenge |
| 32 | OpsAgent200 OpsShape = "agent-200" // agent-access's operations list |
| 33 | OpsOther OpsShape = "other" // anything else, a lookalike 200 included |
| 34 | ) |
| 35 | |
| 36 | // BaselineOps is what app's operations door answers before adoption |
| 37 | // (Paul, 2026-11-17, Home discussion 103): Slides, Calls and Equipo their own |
| 38 | // middleware's 401, every other app a 404. Preflight refuses any other |
| 39 | // baseline, and Delivered holds each app to its own transition. |
| 40 | // |
| 41 | // Base is the one held door (Paul approved, 2026-11-23, |
| 42 | // docs/base-adoption.md): its /api/v1/operations is already agent-shaped |
| 43 | // before adoption (carlos/base internal/operations: a Bearer challenge, |
| 44 | // no-store, error.code unauthenticated), and Base reads neither agent key, |
| 45 | // so no restart can move it. Its baseline is agent-401 and Delivered |
| 46 | // requires agent-401 still, never a 200 without a token. |
| 47 | func BaselineOps(app provision.App) OpsShape { |
| 48 | switch app.Slug { |
| 49 | case "slides", "calls", "equipo": |
| 50 | return OpsApp401 |
| 51 | case "base": |
| 52 | return OpsAgent401 |
| 53 | } |
| 54 | return OpsAbsent |
| 55 | } |
| 56 | |
| 57 | // Delivery is what one probe saw of a running app. It carries versions and |
| 58 | // status codes only, never a body beyond the version name. |
| 59 | type Delivery struct { |
| 60 | Version, Header string |
| 61 | Redirected bool |
| 62 | Health int |
| 63 | Ops OpsShape |
| 64 | At time.Time |
| 65 | } |
| 66 | |
| 67 | // agentShaped reports whether the delegated-access code answered. |
| 68 | func (o OpsShape) agentShaped() bool { return o == OpsAgent401 || o == OpsAgent200 } |
| 69 | |
| 70 | // bodyLimit bounds every probe body. |
| 71 | const bodyLimit = 1 << 20 |
| 72 | |
| 73 | // Probe reads origin's /api/version, /healthz and /api/v1/operations |
| 74 | // without following a redirect: a redirect is recorded in Delivered's |
| 75 | // input, never chased. A plain-http origin must be loopback. |
| 76 | func Probe(ctx context.Context, h *http.Client, origin string) (Delivery, error) { |
| 77 | u, err := url.Parse(origin) |
| 78 | if err != nil || u.Host == "" || u.Path != "" && u.Path != "/" { |
| 79 | return Delivery{}, errors.New("adopt: probe origin is not an origin") |
| 80 | } |
| 81 | if u.Scheme != "https" && !(u.Scheme == "http" && isLoopback(u.Hostname())) { |
| 82 | return Delivery{}, errors.New("adopt: probe origin must be https") |
| 83 | } |
| 84 | base := u.Scheme + "://" + u.Host |
| 85 | c := *h |
| 86 | c.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } |
| 87 | |
| 88 | d := Delivery{At: time.Now().UTC()} |
| 89 | status, hdr, body, err := get(ctx, &c, base+"/api/version") |
| 90 | if err != nil { |
| 91 | return Delivery{}, err |
| 92 | } |
| 93 | switch { |
| 94 | case status >= 300 && status < 400: |
| 95 | d.Redirected = true |
| 96 | case status == http.StatusOK: |
| 97 | d.Version = string(body) |
| 98 | d.Header = hdr.Get("X-Carlos-Version") |
| 99 | } |
| 100 | status, _, _, err = get(ctx, &c, base+"/healthz") |
| 101 | if err != nil { |
| 102 | return Delivery{}, err |
| 103 | } |
| 104 | if status >= 300 && status < 400 { |
| 105 | d.Redirected = true |
| 106 | } |
| 107 | d.Health = status |
| 108 | status, hdr, body, err = get(ctx, &c, base+"/api/v1/operations") |
| 109 | if err != nil { |
| 110 | return Delivery{}, err |
| 111 | } |
| 112 | if status >= 300 && status < 400 { |
| 113 | d.Redirected = true |
| 114 | } |
| 115 | d.Ops = shape(status, hdr, body) |
| 116 | return d, nil |
| 117 | } |
| 118 | |
| 119 | func isLoopback(host string) bool { |
| 120 | if host == "localhost" { |
| 121 | return true |
| 122 | } |
| 123 | ip := net.ParseIP(host) |
| 124 | return ip != nil && ip.IsLoopback() |
| 125 | } |
| 126 | |
| 127 | // get does one GET. Its errors name the step, never the URL or a body. |
| 128 | func get(ctx context.Context, c *http.Client, target string) (int, http.Header, []byte, error) { |
| 129 | req, err := http.NewRequestWithContext(ctx, http.MethodGet, target, nil) |
| 130 | if err != nil { |
| 131 | return 0, nil, nil, errors.New("adopt: probe request refused") |
| 132 | } |
| 133 | resp, err := c.Do(req) |
| 134 | if err != nil { |
| 135 | return 0, nil, nil, errors.New("adopt: probe unreachable") |
| 136 | } |
| 137 | defer resp.Body.Close() |
| 138 | // One byte past the limit tells "exactly the limit" from "cut off". |
| 139 | body, err := io.ReadAll(io.LimitReader(resp.Body, bodyLimit+1)) |
| 140 | if err != nil { |
| 141 | return 0, nil, nil, errors.New("adopt: probe answer unreadable") |
| 142 | } |
| 143 | if len(body) > bodyLimit { |
| 144 | return 0, nil, nil, errors.New("adopt: probe answer too large") |
| 145 | } |
| 146 | return resp.StatusCode, resp.Header, body, nil |
| 147 | } |
| 148 | |
| 149 | // shape classifies the operations answer. agent-access answers every |
| 150 | // request, before routing, with Cache-Control no-store, and every answer |
| 151 | // it writes is application/json. Its two answers to GET |
| 152 | // /api/v1/operations are: |
| 153 | // |
| 154 | // - agent-401: status 401, WWW-Authenticate "Bearer" or "Bearer |
| 155 | // <params>", and a body that is exactly {"error":{"code": |
| 156 | // "unauthenticated","message":<non-empty string>}}; |
| 157 | // - agent-200: status 200 and a body that is exactly {"operations": |
| 158 | // [...]}, an array. |
| 159 | // |
| 160 | // A 401 short of agent-401 is app-401; a 200 short of agent-200 is other. |
| 161 | // Keys are matched exactly, case included, and nothing may follow the |
| 162 | // body's one JSON value. |
| 163 | func shape(status int, h http.Header, body []byte) OpsShape { |
| 164 | agent := hasToken(h.Get("Cache-Control"), "no-store") && jsonMedia(h.Get("Content-Type")) |
| 165 | switch status { |
| 166 | case http.StatusNotFound: |
| 167 | return OpsAbsent |
| 168 | case http.StatusOK: |
| 169 | if agent && operationsList(body) { |
| 170 | return OpsAgent200 |
| 171 | } |
| 172 | return OpsOther |
| 173 | case http.StatusUnauthorized: |
| 174 | if agent && bearerChallenge(h) && unauthenticated(body) { |
| 175 | return OpsAgent401 |
| 176 | } |
| 177 | return OpsApp401 |
| 178 | } |
| 179 | return OpsOther |
| 180 | } |
| 181 | |
| 182 | func jsonMedia(v string) bool { |
| 183 | media, _, err := mime.ParseMediaType(v) |
| 184 | return err == nil && media == "application/json" |
| 185 | } |
| 186 | |
| 187 | // bearerChallenge is one WWW-Authenticate, the Bearer scheme with or |
| 188 | // without parameters. |
| 189 | func bearerChallenge(h http.Header) bool { |
| 190 | vs := h.Values("WWW-Authenticate") |
| 191 | return len(vs) == 1 && (vs[0] == "Bearer" || strings.HasPrefix(vs[0], "Bearer ")) |
| 192 | } |
| 193 | |
| 194 | // object decodes body as exactly one JSON object holding exactly keys. |
| 195 | func object(body []byte, keys ...string) (map[string]json.RawMessage, bool) { |
| 196 | dec := json.NewDecoder(bytes.NewReader(body)) |
| 197 | var m map[string]json.RawMessage |
| 198 | if dec.Decode(&m) != nil || m == nil || len(m) != len(keys) { |
| 199 | return nil, false |
| 200 | } |
| 201 | if _, err := dec.Token(); err != io.EOF { |
| 202 | return nil, false |
| 203 | } |
| 204 | for _, k := range keys { |
| 205 | if _, ok := m[k]; !ok { |
| 206 | return nil, false |
| 207 | } |
| 208 | } |
| 209 | return m, true |
| 210 | } |
| 211 | |
| 212 | func unauthenticated(body []byte) bool { |
| 213 | top, ok := object(body, "error") |
| 214 | if !ok { |
| 215 | return false |
| 216 | } |
| 217 | e, ok := object(top["error"], "code", "message") |
| 218 | if !ok { |
| 219 | return false |
| 220 | } |
| 221 | var code, message string |
| 222 | return json.Unmarshal(e["code"], &code) == nil && code == "unauthenticated" && |
| 223 | json.Unmarshal(e["message"], &message) == nil && message != "" |
| 224 | } |
| 225 | |
| 226 | func operationsList(body []byte) bool { |
| 227 | top, ok := object(body, "operations") |
| 228 | if !ok { |
| 229 | return false |
| 230 | } |
| 231 | var ops []json.RawMessage |
| 232 | return bytes.HasPrefix(bytes.TrimSpace(top["operations"]), []byte("[")) && json.Unmarshal(top["operations"], &ops) == nil |
| 233 | } |
| 234 | |
| 235 | func hasToken(header, want string) bool { |
| 236 | for _, t := range strings.Split(header, ",") { |
| 237 | if strings.EqualFold(strings.TrimSpace(t), want) { |
| 238 | return true |
| 239 | } |
| 240 | } |
| 241 | return false |
| 242 | } |
| 243 | |
| 244 | // sameServing checks the parts delivery and rollback share: the version |
| 245 | // and header unchanged, no redirect, health 200. |
| 246 | func sameServing(before, now Delivery) error { |
| 247 | switch { |
| 248 | case now.Redirected: |
| 249 | return errors.New("adopt: the app redirected") |
| 250 | case before.Version == "" || now.Version != before.Version: |
| 251 | return errors.New("adopt: the served version changed") |
| 252 | case before.Header == "" || now.Header != before.Header: |
| 253 | return errors.New("adopt: the version header changed") |
| 254 | case now.Health != http.StatusOK: |
| 255 | return errors.New("adopt: the app is not healthy") |
| 256 | } |
| 257 | return nil |
| 258 | } |
| 259 | |
| 260 | // Delivered says app's restart delivered the new configuration: the same |
| 261 | // version and header, no redirect, health 200, and the operations door |
| 262 | // moved as app's must (Paul, 2026-11-17). Before, it answered as |
| 263 | // BaselineOps(app) says; now, a 404 must have become agent-401 or |
| 264 | // agent-200, Slides', Calls' and Equipo's own 401 must have become |
| 265 | // agent-401, agent-access's challenge, and Base's agent-401 must still be |
| 266 | // agent-401 (the held door: for Base this proves no delivery of the keys). |
| 267 | func Delivered(app provision.App, before, now Delivery) error { |
| 268 | if err := sameServing(before, now); err != nil { |
| 269 | return err |
| 270 | } |
| 271 | return opsMoved(app, before, now) |
| 272 | } |
| 273 | |
| 274 | // opsMoved is Delivered's operations-door rule: the door answered before |
| 275 | // as BaselineOps(app) says, and now gives agent-access's own answer as |
| 276 | // app's must. A 200 counts only from a 404, so Base's held door (an |
| 277 | // agent-401 baseline) passes only as agent-401. |
| 278 | func opsMoved(app provision.App, before, now Delivery) error { |
| 279 | if before.Ops != BaselineOps(app) { |
| 280 | return errors.New("adopt: the operations door did not answer before the change as this app's does") |
| 281 | } |
| 282 | switch { |
| 283 | case now.Ops == OpsAgent401: |
| 284 | case now.Ops == OpsAgent200 && before.Ops == OpsAbsent: |
| 285 | default: |
| 286 | return errors.New("adopt: the delegated-access door is not answering") |
| 287 | } |
| 288 | return nil |
| 289 | } |
| 290 | |
| 291 | // Reverted says a rollback restart completed: the same version and header, |
| 292 | // health 200, and the operations door back to the before shape. |
| 293 | func Reverted(before, now Delivery) error { |
| 294 | if err := sameServing(before, now); err != nil { |
| 295 | return err |
| 296 | } |
| 297 | if now.Ops != before.Ops { |
| 298 | return errors.New("adopt: the operations door has not returned to its earlier shape") |
| 299 | } |
| 300 | return nil |
| 301 | } |
| 302 | |
| 303 | // signInIdentity reads the Home issuer and consumer an app really signs |
| 304 | // in with, from the redirect its GET /auth/start answers. Apps store both |
| 305 | // as secrets, whose values the config API never returns, and the redirect |
| 306 | // is public. The redirect is never followed. Anything but a 302 or 303 |
| 307 | // from an https origin, carrying the one Location authorizeTarget accepts, |
| 308 | // answers two empty strings, which the mismatch codes then refuse; that |
| 309 | // includes a request that fails. The Location holds a sign-in nonce, so it |
| 310 | // is neither returned nor logged. |
| 311 | func signInIdentity(ctx context.Context, h *http.Client, origin string) (issuer, consumer string) { |
| 312 | u, err := url.Parse(origin) |
| 313 | if err != nil || u.Scheme != "https" || u.Host == "" { |
| 314 | return "", "" |
| 315 | } |
| 316 | c := *h |
| 317 | c.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse } |
| 318 | status, hdr, _, err := get(ctx, &c, origin+"/auth/start") |
| 319 | if err != nil || (status != http.StatusFound && status != http.StatusSeeOther) { |
| 320 | return "", "" |
| 321 | } |
| 322 | loc := hdr.Values("Location") |
| 323 | if len(loc) != 1 { |
| 324 | return "", "" |
| 325 | } |
| 326 | return authorizeTarget(loc[0]) |
| 327 | } |
| 328 | |
| 329 | // authorizeTarget is the issuer and consumer of a Location that is exactly |
| 330 | // HomeIssuerOrigin's /authorize with one non-empty consumer parameter, and |
| 331 | // two empty strings for any other. A # or a backslash is refused in the |
| 332 | // raw text: url.Parse drops an empty fragment and keeps a backslash in the |
| 333 | // query, and browsers read a backslash differently from it. |
| 334 | func authorizeTarget(location string) (issuer, consumer string) { |
| 335 | if strings.ContainsAny(location, "#\\") { |
| 336 | return "", "" |
| 337 | } |
| 338 | u, err := url.Parse(location) |
| 339 | if err != nil || u.User != nil || u.Scheme+"://"+u.Host != HomeIssuerOrigin || |
| 340 | u.Path != "/authorize" || u.RawPath != "" { |
| 341 | return "", "" |
| 342 | } |
| 343 | q, err := url.ParseQuery(u.RawQuery) |
| 344 | if err != nil || len(q["consumer"]) != 1 || q["consumer"][0] == "" { |
| 345 | return "", "" |
| 346 | } |
| 347 | return HomeIssuerOrigin, q["consumer"][0] |
| 348 | } |
| 349 | |