| 1 | // Package fakehome is an in-memory stand-in for Home's two operator |
| 2 | // endpoints (POST /operator/v1 and /operator/v1/plan on each role), with |
| 3 | // Paul's confirm ceremony as a method call. It keeps Home's rules that |
| 4 | // Alta's state machine depends on: pinned signature, canonical bytes, |
| 5 | // sequence = previous + 1, exact replay returning the stored result even |
| 6 | // after expiry, refusals that never consume a sequence, one pending and |
| 7 | // one open plan per role, windows that admit only their kind's verbs, the |
| 8 | // provenance fence, owner receipts that expire, signed provisioning |
| 9 | // records and the manifest digest. |
| 10 | // |
| 11 | // It is a fake: the homecompat module runs Alta against Home's real |
| 12 | // engine. This one exists for speed, crash injection and fault paths |
| 13 | // Home's real code makes awkward to reach (a lost answer after commit). |
| 14 | package fakehome |
| 15 | |
| 16 | import ( |
| 17 | "bytes" |
| 18 | "crypto/rand" |
| 19 | "crypto/sha256" |
| 20 | "encoding/base64" |
| 21 | "encoding/hex" |
| 22 | "errors" |
| 23 | "io" |
| 24 | "net/http" |
| 25 | "net/url" |
| 26 | "regexp" |
| 27 | "slices" |
| 28 | "strings" |
| 29 | "sync" |
| 30 | "time" |
| 31 | |
| 32 | "amadan.net/oficina/alta/homeop" |
| 33 | "amadan.net/oficina/home/roster" |
| 34 | family "amadan.net/rastrillo/rastrillo/crypto" |
| 35 | "github.com/go-json-experiment/json/jsontext" |
| 36 | ) |
| 37 | |
| 38 | // observedVersion is Home's app_version rule (0cee9ba). |
| 39 | var observedVersion = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._+-]{0,127}$`) |
| 40 | |
| 41 | var registry = []string{"docs", "sheets", "slides", "calendar", "calls", "memoria", "equipo", "base"} |
| 42 | |
| 43 | type plan struct { |
| 44 | id, kind, label, name, owner string |
| 45 | // existing is an adoption plan's team SQID; empty for an ordinary one. |
| 46 | existing string |
| 47 | apps []string |
| 48 | expires, window int64 |
| 49 | } |
| 50 | |
| 51 | type stored struct { |
| 52 | action, head string |
| 53 | seq int64 |
| 54 | mac [32]byte |
| 55 | result []byte |
| 56 | } |
| 57 | |
| 58 | type role struct { |
| 59 | name, origin string |
| 60 | installation, registry, device string |
| 61 | seq int64 |
| 62 | head string |
| 63 | results map[string]stored |
| 64 | pending, open *plan |
| 65 | } |
| 66 | |
| 67 | type team struct { |
| 68 | id int64 |
| 69 | sqid string |
| 70 | label string |
| 71 | name string |
| 72 | owner string |
| 73 | epoch int64 |
| 74 | viaHTTP bool |
| 75 | ownerUsed map[string]bool |
| 76 | } |
| 77 | |
| 78 | type instance struct { |
| 79 | team int64 |
| 80 | app, origin, consumer string |
| 81 | state string // pending | live | disabled |
| 82 | recordDigest [32]byte |
| 83 | generation string |
| 84 | attempt *attempt |
| 85 | } |
| 86 | |
| 87 | type attempt struct { |
| 88 | id string |
| 89 | issued, expires int64 |
| 90 | } |
| 91 | |
| 92 | type consumer struct{ origin, app, state string } |
| 93 | |
| 94 | // Home is both roles. |
| 95 | type Home struct { |
| 96 | mu sync.Mutex |
| 97 | // Now is Home's clock. |
| 98 | Now func() time.Time |
| 99 | |
| 100 | alta []byte |
| 101 | altaKID string |
| 102 | prefilter [32]byte |
| 103 | |
| 104 | roles map[string]*role |
| 105 | // People are the addresses that have signed in at Home, with refs. |
| 106 | People map[string]string |
| 107 | |
| 108 | owner, provisioning, rosterPage *family.Keypair |
| 109 | |
| 110 | generation *string |
| 111 | teams map[string]*team // by sqid |
| 112 | nextTeam int64 |
| 113 | instances map[string]*instance // by consumer |
| 114 | consumers map[string]consumer // credential table |
| 115 | env map[string]string // HOME_CONSUMERS |
| 116 | |
| 117 | // Faults. LoseAnswer makes the next matching operation commit and then |
| 118 | // drop the connection; Outage makes matching operations answer 503 |
| 119 | // without committing. |
| 120 | LoseAnswer func(action string) bool |
| 121 | Outage func(action string) bool |
| 122 | |
| 123 | // Calls counts operations by action (committed or not). |
| 124 | Calls map[string]int |
| 125 | |
| 126 | // requests is the committed operations in order; committedApp is the |
| 127 | // app the operation in flight touched, set by mutate. |
| 128 | requests []string |
| 129 | committedApp string |
| 130 | |
| 131 | // RecordSigner, when set, signs provisioning records instead of the |
| 132 | // directory's provisioning key; RecordAudience, when set, is the |
| 133 | // audience records bind. Both make records Alta must refuse. |
| 134 | RecordSigner *family.Keypair |
| 135 | RecordAudience string |
| 136 | } |
| 137 | |
| 138 | // Pins are what Alta needs to reach a role. |
| 139 | type Pins struct { |
| 140 | Installation, Registry, Device string |
| 141 | } |
| 142 | |
| 143 | func token() string { return homeop.Token() } |
| 144 | |
| 145 | // New builds a Home that pins alta's public key and prefilter token. |
| 146 | func New(altaPublic []byte, prefilter string, credentialOrigin, directoryOrigin string, now func() time.Time) *Home { |
| 147 | owner, _ := family.Generate() |
| 148 | prov, _ := family.Generate() |
| 149 | page, _ := family.Generate() |
| 150 | h := &Home{Now: now, alta: altaPublic, altaKID: homeop.KeyID(altaPublic), roles: map[string]*role{}, People: map[string]string{}, |
| 151 | owner: owner, provisioning: prov, rosterPage: page, teams: map[string]*team{}, nextTeam: 1, instances: map[string]*instance{}, consumers: map[string]consumer{}, |
| 152 | env: map[string]string{"directory": directoryOrigin, "alta": "https://alta.example.test"}, Calls: map[string]int{}} |
| 153 | raw, _ := base64.RawURLEncoding.DecodeString(prefilter) |
| 154 | h.prefilter = sha256.Sum256(raw) |
| 155 | for name, origin := range map[string]string{homeop.Credential: credentialOrigin, homeop.Directory: directoryOrigin} { |
| 156 | h.roles[name] = &role{name: name, origin: origin, installation: token(), registry: token(), device: token(), results: map[string]stored{}} |
| 157 | } |
| 158 | return h |
| 159 | } |
| 160 | |
| 161 | // Pins returns the pins for role, as Alta's configuration carries them. |
| 162 | func (h *Home) Pins(r string) Pins { |
| 163 | x := h.roles[r] |
| 164 | return Pins{x.installation, x.registry, x.device} |
| 165 | } |
| 166 | |
| 167 | // SharePins gives both roles the credential role's pins, as production |
| 168 | // holds them: Alta has one installation, registry and device on both |
| 169 | // roles (one configuration, as alta-adopt's config file carries it). |
| 170 | func (h *Home) SharePins() Pins { |
| 171 | h.mu.Lock() |
| 172 | defer h.mu.Unlock() |
| 173 | c, d := h.roles[homeop.Credential], h.roles[homeop.Directory] |
| 174 | d.installation, d.registry, d.device = c.installation, c.registry, c.device |
| 175 | return Pins{c.installation, c.registry, c.device} |
| 176 | } |
| 177 | |
| 178 | // ProvisioningPublic is the directory's provisioning key, base64url. |
| 179 | func (h *Home) ProvisioningPublic() string { |
| 180 | return base64.RawURLEncoding.EncodeToString(h.provisioning.SignPub()) |
| 181 | } |
| 182 | |
| 183 | // AddPerson records that address has signed in at Home. |
| 184 | func (h *Home) AddPerson(address string) string { |
| 185 | h.mu.Lock() |
| 186 | defer h.mu.Unlock() |
| 187 | ref := "pr_" + strings.Repeat("a", 25) + string(rune('a'+len(h.People)%26)) |
| 188 | h.People[address] = ref |
| 189 | return ref |
| 190 | } |
| 191 | |
| 192 | // AddEnvConsumer adds an entry to the credential role's immutable env |
| 193 | // manifest (HOME_CONSUMERS), as an existing instance has. Adoption's |
| 194 | // register verifies against it and inserts nothing. |
| 195 | func (h *Home) AddEnvConsumer(id, origin string) { |
| 196 | h.mu.Lock() |
| 197 | defer h.mu.Unlock() |
| 198 | h.env[id] = origin |
| 199 | } |
| 200 | |
| 201 | // Requests is the committed operations in order, each as its action, with |
| 202 | // ":<app>" for the verbs that touch one app, for example |
| 203 | // "directory.activate-consumer:calendar". A refused operation, an |
| 204 | // operation that did not commit and an exact replay add nothing. |
| 205 | func (h *Home) Requests() []string { |
| 206 | h.mu.Lock() |
| 207 | defer h.mu.Unlock() |
| 208 | return slices.Clone(h.requests) |
| 209 | } |
| 210 | |
| 211 | // Confirm is Paul on role's confirm page: it opens the pending plan's |
| 212 | // window. owner is the typed address (credential role, create-team). |
| 213 | func (h *Home) Confirm(r, owner string) error { |
| 214 | h.mu.Lock() |
| 215 | defer h.mu.Unlock() |
| 216 | x := h.roles[r] |
| 217 | now := h.Now().Unix() |
| 218 | h.sweep(x, now) |
| 219 | if x.pending == nil { |
| 220 | return errors.New("fakehome: no pending plan") |
| 221 | } |
| 222 | if x.open != nil { |
| 223 | return errors.New("fakehome: 409 a window is open") |
| 224 | } |
| 225 | if x.pending.owner != "" && x.pending.owner != owner { |
| 226 | return errors.New("fakehome: typed owner does not match") |
| 227 | } |
| 228 | p := x.pending |
| 229 | x.pending = nil |
| 230 | p.window = now + homeop.WindowLifetime |
| 231 | x.open = p |
| 232 | return nil |
| 233 | } |
| 234 | |
| 235 | // Team reports a seeded team's state for assertions. |
| 236 | func (h *Home) Team(label string) (id int64, sqid string, ok bool) { |
| 237 | h.mu.Lock() |
| 238 | defer h.mu.Unlock() |
| 239 | for _, t := range h.teams { |
| 240 | if t.label == label { |
| 241 | return t.id, t.sqid, true |
| 242 | } |
| 243 | } |
| 244 | return 0, "", false |
| 245 | } |
| 246 | |
| 247 | // TeamCount is how many teams exist. |
| 248 | func (h *Home) TeamCount() int { |
| 249 | h.mu.Lock() |
| 250 | defer h.mu.Unlock() |
| 251 | return len(h.teams) |
| 252 | } |
| 253 | |
| 254 | // InstanceState is a directory consumer's state. |
| 255 | func (h *Home) InstanceState(consumer string) string { |
| 256 | h.mu.Lock() |
| 257 | defer h.mu.Unlock() |
| 258 | if i, ok := h.instances[consumer]; ok { |
| 259 | return i.state |
| 260 | } |
| 261 | return "" |
| 262 | } |
| 263 | |
| 264 | // ConsumerState is a credential consumer's state. |
| 265 | func (h *Home) ConsumerState(id string) string { |
| 266 | h.mu.Lock() |
| 267 | defer h.mu.Unlock() |
| 268 | return h.consumers[id].state |
| 269 | } |
| 270 | |
| 271 | // ConsumerCount counts the credential table's rows. |
| 272 | func (h *Home) ConsumerCount() int { |
| 273 | h.mu.Lock() |
| 274 | defer h.mu.Unlock() |
| 275 | return len(h.consumers) |
| 276 | } |
| 277 | |
| 278 | // Stream is a role's (sequence, head). |
| 279 | func (h *Home) Stream(r string) (int64, string) { |
| 280 | h.mu.Lock() |
| 281 | defer h.mu.Unlock() |
| 282 | return h.roles[r].seq, h.roles[r].head |
| 283 | } |
| 284 | |
| 285 | func (h *Home) sweep(x *role, now int64) { |
| 286 | if x.pending != nil && x.pending.expires <= now { |
| 287 | x.pending = nil |
| 288 | } |
| 289 | if x.open != nil && x.open.window <= now { |
| 290 | x.open = nil |
| 291 | } |
| 292 | } |
| 293 | |
| 294 | // Handler is role r's /operator/v1 and /operator/v1/plan. |
| 295 | func (h *Home) Handler(r string) http.Handler { |
| 296 | return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) { |
| 297 | answer := func(status int, code string) { |
| 298 | w.Header().Set("Content-Type", "application/json") |
| 299 | w.WriteHeader(status) |
| 300 | _, _ = io.WriteString(w, `{"outcome":"`+code+`"}`) |
| 301 | } |
| 302 | if req.URL.Path != "/operator/v1" && req.URL.Path != "/operator/v1/plan" { |
| 303 | answer(404, "not_found") |
| 304 | return |
| 305 | } |
| 306 | if req.Method != http.MethodPost { |
| 307 | answer(405, "method") |
| 308 | return |
| 309 | } |
| 310 | if len(req.Header.Values("Cookie")) > 0 || len(req.Header.Values("Origin")) > 0 || req.Header.Get("Sec-Fetch-Mode") != "" { |
| 311 | answer(403, "browser") |
| 312 | return |
| 313 | } |
| 314 | if req.Header.Get("Content-Type") != "application/json" { |
| 315 | answer(415, "media") |
| 316 | return |
| 317 | } |
| 318 | auth := req.Header.Get("Authorization") |
| 319 | tok, err := base64.RawURLEncoding.Strict().DecodeString(strings.TrimPrefix(auth, "Bearer ")) |
| 320 | if !strings.HasPrefix(auth, "Bearer ") || err != nil || sha256.Sum256(tok) != h.prefilter { |
| 321 | answer(401, "prefilter") |
| 322 | return |
| 323 | } |
| 324 | body, err := io.ReadAll(io.LimitReader(req.Body, homeop.BodyLimit+1)) |
| 325 | if err != nil || len(body) > homeop.BodyLimit { |
| 326 | answer(413, "size") |
| 327 | return |
| 328 | } |
| 329 | h.mu.Lock() |
| 330 | defer h.mu.Unlock() |
| 331 | x := h.roles[r] |
| 332 | now := h.Now().Unix() |
| 333 | h.sweep(x, now) |
| 334 | if req.URL.Path == "/operator/v1/plan" { |
| 335 | status := h.submit(x, body, now) |
| 336 | switch status { |
| 337 | case 200: |
| 338 | w.Header().Set("Content-Type", "application/json") |
| 339 | _, _ = io.WriteString(w, `{"outcome":"pending"}`) |
| 340 | case 409: |
| 341 | answer(409, "busy") |
| 342 | default: |
| 343 | answer(403, "refused") |
| 344 | } |
| 345 | return |
| 346 | } |
| 347 | if out, ok := h.inspect(x, body, now); ok { |
| 348 | w.Header().Set("Content-Type", "application/json") |
| 349 | _, _ = w.Write(out) |
| 350 | return |
| 351 | } |
| 352 | out, status, action := h.execute(x, body, now) |
| 353 | if action != "" { |
| 354 | h.Calls[action]++ |
| 355 | } |
| 356 | if status == 200 && action != "" && h.LoseAnswer != nil && h.LoseAnswer(action) { |
| 357 | // Committed; the answer is lost on the way back. |
| 358 | if hj, ok := w.(http.Hijacker); ok { |
| 359 | c, _, _ := hj.Hijack() |
| 360 | c.Close() |
| 361 | return |
| 362 | } |
| 363 | panic(http.ErrAbortHandler) |
| 364 | } |
| 365 | switch status { |
| 366 | case 200: |
| 367 | w.Header().Set("Content-Type", "application/json") |
| 368 | _, _ = w.Write(out) |
| 369 | case 503: |
| 370 | answer(503, "unavailable") |
| 371 | default: |
| 372 | answer(403, "refused") |
| 373 | } |
| 374 | }) |
| 375 | } |
| 376 | |
| 377 | // ---- envelopes ---- |
| 378 | |
| 379 | type envelope struct { |
| 380 | Version int `json:"v"` |
| 381 | KeyID string `json:"kid"` |
| 382 | Payload string `json:"payload"` |
| 383 | Signature string `json:"signature"` |
| 384 | } |
| 385 | |
| 386 | // canonical decodes b strictly into v and requires b to be v's canonical |
| 387 | // encoding, as Home's strictCanonical does. |
| 388 | func canonical(b []byte, v any) bool { |
| 389 | if homeop.Decode(b, v) != nil { |
| 390 | return false |
| 391 | } |
| 392 | re, err := homeop.Encode(v) |
| 393 | return err == nil && bytes.Equal(re, b) |
| 394 | } |
| 395 | |
| 396 | func (h *Home) open(raw []byte, context string) ([]byte, bool) { |
| 397 | var env envelope |
| 398 | if !canonical(raw, &env) || env.Version != 1 || env.KeyID != h.altaKID { |
| 399 | return nil, false |
| 400 | } |
| 401 | p, err := base64.RawURLEncoding.Strict().DecodeString(env.Payload) |
| 402 | sig, err2 := base64.RawURLEncoding.Strict().DecodeString(env.Signature) |
| 403 | if err != nil || err2 != nil || len(sig) != 64 || !family.Verify(h.alta, context, p, sig) { |
| 404 | return nil, false |
| 405 | } |
| 406 | return p, true |
| 407 | } |
| 408 | |
| 409 | func sign(k *family.Keypair, context string, v any) []byte { |
| 410 | payload, _ := homeop.Encode(v) |
| 411 | sig, _ := family.Sign(k, context, payload) |
| 412 | out, _ := homeop.Encode(envelope{1, homeop.KeyID(k.SignPub()), base64.RawURLEncoding.EncodeToString(payload), base64.RawURLEncoding.EncodeToString(sig)}) |
| 413 | return out |
| 414 | } |
| 415 | |
| 416 | func validLabel(s string) bool { |
| 417 | if len(s) == 0 || len(s) > 63 || s[0] == '-' || s[len(s)-1] == '-' { |
| 418 | return false |
| 419 | } |
| 420 | for _, c := range s { |
| 421 | if !(c >= 'a' && c <= 'z' || c >= '0' && c <= '9' || c == '-') { |
| 422 | return false |
| 423 | } |
| 424 | } |
| 425 | return true |
| 426 | } |
| 427 | |
| 428 | // ---- plans ---- |
| 429 | |
| 430 | func (h *Home) submit(x *role, body []byte, now int64) int { |
| 431 | payload, ok := h.open(body, homeop.PlanContext) |
| 432 | if !ok { |
| 433 | return 403 |
| 434 | } |
| 435 | var p homeop.Plan |
| 436 | if !canonical(payload, &p) || p.Version != 1 || p.Purpose != "operator-plan" || p.Role != x.name || p.Origin != x.origin || p.Installation != x.installation || p.Registry != x.registry || p.Device != x.device || !homeop.CanonicalToken(p.PlanID) || p.Issued > now || now >= p.Expires || p.Expires-p.Issued > homeop.PlanLifetime { |
| 437 | return 403 |
| 438 | } |
| 439 | // Home's Plan.valid: an adoption plan binds a team SQID, only on |
| 440 | // create-team or add-apps, only under label oficina, only for the |
| 441 | // canonical apps; and oficina is reserved against everything else. |
| 442 | if p.ExistingTeam != "" { |
| 443 | if !validSQID(p.ExistingTeam) || (p.Kind != homeop.KindCreateTeam && p.Kind != homeop.KindAddApps) || (x.name == homeop.Directory && p.Label != "oficina") { |
| 444 | return 403 |
| 445 | } |
| 446 | for _, a := range p.Apps { |
| 447 | if homeop.CanonicalOrigin(a) == "" { |
| 448 | return 403 |
| 449 | } |
| 450 | } |
| 451 | } else if x.name == homeop.Directory && p.Label == "oficina" && (p.Kind == homeop.KindCreateTeam || p.Kind == homeop.KindAddApps) { |
| 452 | return 403 |
| 453 | } |
| 454 | if p.Kind == homeop.KindInitialize { |
| 455 | if x.name != homeop.Directory || len(p.Apps) != 0 || p.Label != "" || p.DisplayName != "" || p.Owner != "" { |
| 456 | return 403 |
| 457 | } |
| 458 | } else { |
| 459 | if len(p.Apps) == 0 || len(p.Apps) > 8 { |
| 460 | return 403 |
| 461 | } |
| 462 | seen := map[string]bool{} |
| 463 | for _, a := range p.Apps { |
| 464 | if !slices.Contains(registry, a) || seen[a] { |
| 465 | return 403 |
| 466 | } |
| 467 | seen[a] = true |
| 468 | } |
| 469 | if x.name == homeop.Directory { |
| 470 | if p.Owner != "" || !validLabel(p.Label) || (p.Kind == homeop.KindCreateTeam) != (p.DisplayName != "") { |
| 471 | return 403 |
| 472 | } |
| 473 | } else { |
| 474 | if p.Label != "" || p.DisplayName != "" || (p.Kind == homeop.KindCreateTeam) != (p.Owner != "") { |
| 475 | return 403 |
| 476 | } |
| 477 | if p.Owner != "" { |
| 478 | if _, ok := h.People[p.Owner]; !ok { |
| 479 | return 403 |
| 480 | } |
| 481 | } |
| 482 | } |
| 483 | } |
| 484 | if x.pending != nil || (x.open != nil && x.open.id == p.PlanID) { |
| 485 | return 409 |
| 486 | } |
| 487 | x.pending = &plan{id: p.PlanID, kind: p.Kind, label: p.Label, name: p.DisplayName, owner: p.Owner, existing: p.ExistingTeam, apps: p.Apps, expires: p.Expires} |
| 488 | return 200 |
| 489 | } |
| 490 | |
| 491 | // ---- inspect ---- |
| 492 | |
| 493 | func (h *Home) inspect(x *role, body []byte, now int64) ([]byte, bool) { |
| 494 | payload, ok := h.open(body, homeop.InspectContext) |
| 495 | if !ok { |
| 496 | return nil, false |
| 497 | } |
| 498 | var c homeop.InspectChallenge |
| 499 | if !canonical(payload, &c) || c.Role != x.name || c.Origin != x.origin || c.Installation != x.installation || c.Registry != x.registry || c.Device != x.device || c.Issued > now || c.Expires <= now { |
| 500 | return nil, false |
| 501 | } |
| 502 | out := homeop.Inspection{Version: 1, Role: x.name, Challenge: c.Challenge, Observed: now, Sequence: x.seq, Head: x.head} |
| 503 | if x.pending != nil { |
| 504 | out.PendingPlan, out.PendingExpires = x.pending.id, x.pending.expires |
| 505 | } |
| 506 | if x.open != nil { |
| 507 | out.OpenPlan, out.WindowExpires = x.open.id, x.open.window |
| 508 | } |
| 509 | if x.name == homeop.Directory { |
| 510 | out.Generation = h.generation |
| 511 | out.TeamID = h.nextTeam |
| 512 | out.TeamSQID = sqid(h.nextTeam) |
| 513 | } |
| 514 | b, _ := homeop.Encode(out) |
| 515 | return b, true |
| 516 | } |
| 517 | |
| 518 | // sqid is not Home's sqids encoding; the fake only needs a stable, |
| 519 | // distinct token per id. |
| 520 | func sqid(id int64) string { return "t" + strings.Repeat("x", int(id%5)+2) + string(rune('a'+id%26)) } |
| 521 | |
| 522 | var sqidShape = regexp.MustCompile(`^tx{2,6}[a-z]$`) |
| 523 | |
| 524 | // validSQID is Home's validTeamSQID for this fake's sqids: the shape sqid |
| 525 | // produces. Home's decodes to exactly one positive id and re-encodes. |
| 526 | func validSQID(s string) bool { return sqidShape.MatchString(s) } |
| 527 | |
| 528 | // routeScope is Home's routeScope (existing.go): an ordinary window never |
| 529 | // touches the oficina label or a canonical origin; an adoption window |
| 530 | // touches only the exact canonical tuple of the plan's team. |
| 531 | func routeScope(existing, label, team, app, consumer, origin string) bool { |
| 532 | if existing == "" { |
| 533 | return label != "oficina" && origin != homeop.CanonicalOrigin(app) |
| 534 | } |
| 535 | return validSQID(existing) && team == existing && canonicalBinding(label, app, consumer, origin) |
| 536 | } |
| 537 | |
| 538 | // canonicalBinding is directorydata.CanonicalBinding. |
| 539 | func canonicalBinding(label, app, consumer, origin string) bool { |
| 540 | return label == "oficina" && consumer == app && homeop.CanonicalOrigin(app) != "" && origin == homeop.CanonicalOrigin(app) |
| 541 | } |
| 542 | |
| 543 | // ---- operations ---- |
| 544 | |
| 545 | type wrapper struct { |
| 546 | Version int `json:"version"` |
| 547 | Authorization jsontext.Value `json:"signed_authorization"` |
| 548 | Input jsontext.Value `json:"operation_input"` |
| 549 | } |
| 550 | |
| 551 | func (h *Home) execute(x *role, body []byte, now int64) ([]byte, int, string) { |
| 552 | var w wrapper |
| 553 | if !canonical(body, &w) || w.Version != 1 { |
| 554 | return nil, 403, "" |
| 555 | } |
| 556 | payload, ok := h.open(w.Authorization, homeop.InputContext) |
| 557 | if !ok { |
| 558 | return nil, 403, "" |
| 559 | } |
| 560 | var a homeop.Authorization |
| 561 | if !canonical(payload, &a) || a.Role != x.name || a.Origin != x.origin || a.Installation != x.installation || a.Registry != x.registry || a.Device != x.device || a.InputDigest != homeop.Digest(w.Input) || a.Initial != (a.Sequence == 1) || a.Expires-a.Issued > 300 { |
| 562 | return nil, 403, "" |
| 563 | } |
| 564 | head := homeop.Digest(w.Authorization) |
| 565 | mac := sha256.Sum256(w.Input) |
| 566 | if s, ok := x.results[a.OperationID]; ok { |
| 567 | if s.action != a.Action || s.seq != a.Sequence || s.head != head || s.mac != mac || x.seq < a.Sequence { |
| 568 | return nil, 403, a.Action |
| 569 | } |
| 570 | return s.result, 200, a.Action |
| 571 | } |
| 572 | if h.Outage != nil && h.Outage(a.Action) { |
| 573 | return nil, 503, a.Action |
| 574 | } |
| 575 | if !(a.Issued <= now && now < a.Expires) { |
| 576 | return nil, 403, a.Action |
| 577 | } |
| 578 | if a.Sequence != x.seq+1 || a.Previous != x.head { |
| 579 | return nil, 403, a.Action |
| 580 | } |
| 581 | w0 := x.open |
| 582 | if w0 == nil || !admits(w0.kind, a.Action) { |
| 583 | return nil, 403, a.Action |
| 584 | } |
| 585 | base := homeop.Result{Version: 1, OperationID: a.OperationID, Outcome: "committed"} |
| 586 | h.committedApp = "" |
| 587 | res, ok := h.mutate(x, w0, a, w.Input, head, now, base) |
| 588 | if !ok { |
| 589 | return nil, 403, a.Action |
| 590 | } |
| 591 | out, _ := homeop.Encode(res) |
| 592 | x.results[a.OperationID] = stored{action: a.Action, seq: a.Sequence, head: head, mac: mac, result: out} |
| 593 | x.seq, x.head = a.Sequence, head |
| 594 | entry := a.Action |
| 595 | if h.committedApp != "" { |
| 596 | entry += ":" + h.committedApp |
| 597 | } |
| 598 | h.requests = append(h.requests, entry) |
| 599 | return out, 200, a.Action |
| 600 | } |
| 601 | |
| 602 | func admits(kind, action string) bool { |
| 603 | switch action { |
| 604 | case homeop.DirectoryInitialize: |
| 605 | return kind == homeop.KindInitialize |
| 606 | case homeop.DirectorySeedTeam, homeop.CredentialOwnerSeed: |
| 607 | return kind == homeop.KindCreateTeam |
| 608 | case homeop.DirectoryProvision, homeop.DirectoryVerify, homeop.DirectoryActivate, homeop.CredentialRegister: |
| 609 | return kind == homeop.KindCreateTeam || kind == homeop.KindAddApps |
| 610 | case homeop.DirectoryDisable, homeop.CredentialRetire: |
| 611 | return kind == homeop.KindRetireApps |
| 612 | } |
| 613 | return false |
| 614 | } |
| 615 | |
| 616 | func base(in homeop.InputBase, a homeop.Authorization) bool { |
| 617 | return in.Version == 1 && in.Operation == a.Action && in.OperationID == a.OperationID |
| 618 | } |
| 619 | |
| 620 | func (h *Home) fence(sq, label string) (*team, bool) { |
| 621 | t, ok := h.teams[sq] |
| 622 | return t, ok && t.viaHTTP && t.label == label |
| 623 | } |
| 624 | |
| 625 | func (h *Home) mutate(x *role, w *plan, a homeop.Authorization, input []byte, head string, now int64, res homeop.Result) (homeop.Result, bool) { |
| 626 | switch a.Action { |
| 627 | case homeop.DirectoryInitialize: |
| 628 | var in homeop.InitializeInput |
| 629 | if !canonical(input, &in) || !base(in.InputBase, a) || !a.Initial || in.ExpectedGeneration != nil || !homeop.CanonicalToken(in.Generation) || in.Baseline != homeop.Baseline || h.generation != nil { |
| 630 | return res, false |
| 631 | } |
| 632 | g := in.Generation |
| 633 | h.generation = &g |
| 634 | res.Generation = g |
| 635 | return res, true |
| 636 | case homeop.CredentialOwnerSeed: |
| 637 | var in homeop.OwnerInput |
| 638 | if !canonical(input, &in) || !base(in.InputBase, a) || !in.ExistingOnly || in.Address != w.owner || in.Directory != h.roles[homeop.Directory].origin { |
| 639 | return res, false |
| 640 | } |
| 641 | if w.existing != "" && in.TeamSQID != w.existing { |
| 642 | return res, false |
| 643 | } |
| 644 | ref, ok := h.People[in.Address] |
| 645 | if !ok || in.TeamID <= 0 || in.TeamSQID != sqid(in.TeamID) { |
| 646 | return res, false |
| 647 | } |
| 648 | res.Receipt = sign(h.owner, homeop.OwnerContext, homeop.OwnerReceipt{Version: 1, Purpose: "owner-seed", OperationID: a.OperationID, Issuer: x.origin, Directory: in.Directory, TeamID: in.TeamID, TeamSQID: in.TeamSQID, PersonRef: ref, Role: "owner", Issued: now, Expires: now + 300}) |
| 649 | return res, true |
| 650 | case homeop.DirectorySeedTeam: |
| 651 | var in homeop.SeedInput |
| 652 | if !canonical(input, &in) || !base(in.InputBase, a) || a.Initial || in.Label != w.label || in.Name != w.name || h.generation == nil || in.Generation != *h.generation { |
| 653 | return res, false |
| 654 | } |
| 655 | // Home's seedTeamForWindow: oficina is seeded only by an adoption |
| 656 | // window, and only at that window's SQID. |
| 657 | if (in.Label == "oficina") != (w.existing != "") || (w.existing != "" && in.TeamSQID != w.existing) { |
| 658 | return res, false |
| 659 | } |
| 660 | receipt, ok := h.verifyReceipt(in.Receipt, now) |
| 661 | if !ok || receipt.TeamID != in.TeamID || receipt.TeamSQID != in.TeamSQID || in.TeamID != h.nextTeam || in.TeamSQID != sqid(h.nextTeam) { |
| 662 | return res, false |
| 663 | } |
| 664 | for _, t := range h.teams { |
| 665 | if t.label == in.Label || t.ownerUsed[receipt.OperationID] { |
| 666 | return res, false |
| 667 | } |
| 668 | } |
| 669 | t := &team{id: in.TeamID, sqid: in.TeamSQID, label: in.Label, name: in.Name, owner: receipt.PersonRef, epoch: 1, viaHTTP: true, ownerUsed: map[string]bool{receipt.OperationID: true}} |
| 670 | h.teams[t.sqid] = t |
| 671 | h.nextTeam++ |
| 672 | res.Generation, res.TeamID, res.TeamSQID, res.Epoch = in.Generation, t.id, t.sqid, t.epoch |
| 673 | return res, true |
| 674 | case homeop.DirectoryProvision: |
| 675 | var in homeop.ProvisionInput |
| 676 | if !canonical(input, &in) || !base(in.InputBase, a) || a.Initial || in.Sequence != 0 || !slices.Contains(w.apps, in.App) || h.generation == nil || in.Generation != *h.generation { |
| 677 | return res, false |
| 678 | } |
| 679 | t, ok := h.fence(in.TeamSQID, w.label) |
| 680 | if !ok || !routeScope(w.existing, t.label, in.TeamSQID, in.App, in.Consumer, in.Audience) { |
| 681 | return res, false |
| 682 | } |
| 683 | if w.existing == "" && in.Audience != "https://"+t.label+"."+in.App+".oficina.works" { |
| 684 | return res, false |
| 685 | } |
| 686 | h.committedApp = in.App |
| 687 | for c, i := range h.instances { |
| 688 | if (i.team == t.id && i.app == in.App) || c == in.Consumer || i.origin == in.Audience { |
| 689 | return res, false |
| 690 | } |
| 691 | } |
| 692 | b := roster.Bindings{Issuer: h.roles[homeop.Credential].origin, Directory: x.origin, Consumer: in.Consumer, App: in.App, Team: in.TeamSQID, Audience: in.Audience} |
| 693 | page := roster.Key{ID: "page1", Public: base64.RawURLEncoding.EncodeToString(h.rosterPage.SignPub())} |
| 694 | signer := h.provisioning |
| 695 | if h.RecordSigner != nil { |
| 696 | signer = h.RecordSigner |
| 697 | } |
| 698 | if h.RecordAudience != "" { |
| 699 | b.Audience = h.RecordAudience |
| 700 | } |
| 701 | record, err := roster.SignProvisioning(signer, homeop.KeyID(signer.SignPub()), roster.Provisioning{Version: 1, Operation: a.OperationID, Sequence: 1, Bindings: b, Generation: in.Generation, MinEpoch: t.epoch, Keys: []roster.Key{page}}) |
| 702 | if err != nil { |
| 703 | return res, false |
| 704 | } |
| 705 | bearer := make([]byte, 32) |
| 706 | _, _ = rand.Read(bearer) |
| 707 | h.instances[in.Consumer] = &instance{team: t.id, app: in.App, origin: in.Audience, consumer: in.Consumer, state: "pending", recordDigest: sha256.Sum256(record), generation: in.Generation} |
| 708 | res.Generation, res.TeamID, res.TeamSQID, res.Epoch, res.Record, res.Bearer = in.Generation, t.id, t.sqid, t.epoch, record, base64.RawURLEncoding.EncodeToString(bearer) |
| 709 | return res, true |
| 710 | case homeop.CredentialRegister: |
| 711 | var in homeop.RegisterInput |
| 712 | if !canonical(input, &in) || !base(in.InputBase, a) || a.Initial { |
| 713 | return res, false |
| 714 | } |
| 715 | claimed, ok := claimedBindings(in.Record) |
| 716 | if !ok { |
| 717 | return res, false |
| 718 | } |
| 719 | expected := claimed |
| 720 | expected.Issuer, expected.Directory = x.origin, h.roles[homeop.Directory].origin |
| 721 | v, err := roster.VerifyProvisioning(in.Record, []roster.Key{{ID: homeop.KeyID(h.provisioning.SignPub()), Public: h.ProvisioningPublic()}}, expected) |
| 722 | if err != nil { |
| 723 | return res, false |
| 724 | } |
| 725 | b := v.Bindings() |
| 726 | if !slices.Contains(w.apps, b.App) { |
| 727 | return res, false |
| 728 | } |
| 729 | h.committedApp = b.App |
| 730 | if w.existing != "" { |
| 731 | // Home's register under an adoption window: verify only. The |
| 732 | // exact pair is already in the env manifest, no other env |
| 733 | // entry has the origin, and the table has neither; nothing is |
| 734 | // inserted, replaced or retired. |
| 735 | if b.Team != w.existing || !canonicalBinding("oficina", b.App, b.Consumer, b.Audience) || h.env[b.Consumer] != b.Audience { |
| 736 | return res, false |
| 737 | } |
| 738 | for id, origin := range h.env { |
| 739 | if id != b.Consumer && origin == b.Audience { |
| 740 | return res, false |
| 741 | } |
| 742 | } |
| 743 | for id, c := range h.consumers { |
| 744 | if id == b.Consumer || c.origin == b.Audience { |
| 745 | return res, false |
| 746 | } |
| 747 | } |
| 748 | res.Manifest = h.manifest() |
| 749 | return res, true |
| 750 | } |
| 751 | for id, origin := range h.env { |
| 752 | if id == b.Consumer || origin == b.Audience { |
| 753 | return res, false |
| 754 | } |
| 755 | } |
| 756 | for id, c := range h.consumers { |
| 757 | if id == b.Consumer || c.origin == b.Audience { |
| 758 | return res, false |
| 759 | } |
| 760 | } |
| 761 | h.consumers[b.Consumer] = consumer{origin: b.Audience, app: b.App, state: "active"} |
| 762 | res.Manifest = h.manifest() |
| 763 | return res, true |
| 764 | case homeop.CredentialRetire: |
| 765 | var in homeop.RetireInput |
| 766 | if !canonical(input, &in) || !base(in.InputBase, a) || a.Initial { |
| 767 | return res, false |
| 768 | } |
| 769 | c, ok := h.consumers[in.Consumer] |
| 770 | if !ok || c.state != "active" || !slices.Contains(w.apps, c.app) { |
| 771 | return res, false |
| 772 | } |
| 773 | h.committedApp = c.app |
| 774 | c.state = "retired" |
| 775 | h.consumers[in.Consumer] = c |
| 776 | res.Manifest = h.manifest() |
| 777 | return res, true |
| 778 | case homeop.DirectoryVerify: |
| 779 | var in homeop.VerificationInput |
| 780 | if !canonical(input, &in) || !base(in.InputBase, a) || a.Initial || !slices.Contains(w.apps, in.App) { |
| 781 | return res, false |
| 782 | } |
| 783 | if _, ok := h.fence(in.TeamSQID, w.label); !ok || !routeScope(w.existing, w.label, in.TeamSQID, in.App, in.Consumer, in.Audience) { |
| 784 | return res, false |
| 785 | } |
| 786 | h.committedApp = in.App |
| 787 | i, ok := h.pendingBinding(in.Consumer, in.TeamSQID, in.App, in.Audience, in.Generation, in.RecordSequence, in.RecordDigest, in.Owner, in.Epoch) |
| 788 | if !ok || in.Issued <= 0 || in.Issued > now || in.Expires <= now || in.Expires-in.Issued > 600 { |
| 789 | return res, false |
| 790 | } |
| 791 | if i.attempt != nil && i.attempt.expires > now { |
| 792 | return res, false |
| 793 | } |
| 794 | i.attempt = &attempt{a.OperationID, in.Issued, in.Expires} |
| 795 | res.Attempt, res.Expires = a.OperationID, in.Expires |
| 796 | return res, true |
| 797 | case homeop.DirectoryActivate: |
| 798 | var in homeop.ActivationInput |
| 799 | if !canonical(input, &in) || !base(in.InputBase, a) || a.Initial { |
| 800 | return res, false |
| 801 | } |
| 802 | p := in.Evidence |
| 803 | // Home's activateForWindow: the window, not the evidence, picks |
| 804 | // the policy. |
| 805 | policy := homeop.ActivationPolicy |
| 806 | if w.existing != "" { |
| 807 | policy = homeop.ExistingActivationPolicy |
| 808 | } |
| 809 | u, err := url.Parse(p.Audience) |
| 810 | if err != nil || !slices.Contains(w.apps, p.App) || p.Policy != policy || !observedVersion.MatchString(p.AppVersion) || !homeop.CanonicalToken(p.ArtifactDigest) || !homeop.CanonicalToken(p.EnvironmentBinding) || !homeop.CanonicalToken(p.ManifestDigest) || p.AliasHost != u.Host || p.Completed > now || now-p.Completed >= 300 { |
| 811 | return res, false |
| 812 | } |
| 813 | if _, ok := h.fence(p.TeamSQID, w.label); !ok || !routeScope(w.existing, w.label, p.TeamSQID, p.App, p.Consumer, p.Audience) { |
| 814 | return res, false |
| 815 | } |
| 816 | h.committedApp = p.App |
| 817 | i, ok := h.pendingBinding(p.Consumer, p.TeamSQID, p.App, p.Audience, p.Generation, p.RecordSequence, p.RecordDigest, p.Owner, p.Epoch) |
| 818 | if !ok || i.attempt == nil || i.attempt.id != p.Attempt || i.attempt.expires <= now || p.Started < i.attempt.issued || p.Completed >= i.attempt.expires { |
| 819 | return res, false |
| 820 | } |
| 821 | i.state, i.attempt = "live", nil |
| 822 | res.Attempt, res.Generation, res.TeamSQID, res.Epoch = p.Attempt, p.Generation, p.TeamSQID, p.Epoch |
| 823 | return res, true |
| 824 | case homeop.DirectoryDisable: |
| 825 | var in homeop.DisableInput |
| 826 | if !canonical(input, &in) || !base(in.InputBase, a) || a.Initial || !slices.Contains(w.apps, in.App) || h.generation == nil || in.Generation != *h.generation { |
| 827 | return res, false |
| 828 | } |
| 829 | t, ok := h.fence(in.TeamSQID, w.label) |
| 830 | i, ok2 := h.instances[in.Consumer] |
| 831 | if !ok || !ok2 || i.team != t.id || i.app != in.App || i.state == "disabled" { |
| 832 | return res, false |
| 833 | } |
| 834 | h.committedApp = in.App |
| 835 | i.state = "disabled" |
| 836 | res.Generation, res.TeamID, res.TeamSQID = in.Generation, t.id, t.sqid |
| 837 | return res, true |
| 838 | } |
| 839 | return res, false |
| 840 | } |
| 841 | |
| 842 | func (h *Home) pendingBinding(consumer, sq, app, audience, gen string, seq int64, digest, owner string, epoch int64) (*instance, bool) { |
| 843 | i, ok := h.instances[consumer] |
| 844 | if !ok || i.state != "pending" || i.app != app || i.origin != audience || i.generation != gen || seq != 1 { |
| 845 | return nil, false |
| 846 | } |
| 847 | t, ok := h.teams[sq] |
| 848 | if !ok || t.id != i.team || t.owner != owner || t.epoch != epoch { |
| 849 | return nil, false |
| 850 | } |
| 851 | d, err := base64.RawURLEncoding.Strict().DecodeString(digest) |
| 852 | if err != nil || !bytes.Equal(d, i.recordDigest[:]) { |
| 853 | return nil, false |
| 854 | } |
| 855 | return i, true |
| 856 | } |
| 857 | |
| 858 | func (h *Home) verifyReceipt(raw []byte, now int64) (homeop.OwnerReceipt, bool) { |
| 859 | var env envelope |
| 860 | if !canonical(raw, &env) || env.KeyID != homeop.KeyID(h.owner.SignPub()) { |
| 861 | return homeop.OwnerReceipt{}, false |
| 862 | } |
| 863 | p, err := base64.RawURLEncoding.Strict().DecodeString(env.Payload) |
| 864 | sig, err2 := base64.RawURLEncoding.Strict().DecodeString(env.Signature) |
| 865 | if err != nil || err2 != nil || !family.Verify(h.owner.SignPub(), homeop.OwnerContext, p, sig) { |
| 866 | return homeop.OwnerReceipt{}, false |
| 867 | } |
| 868 | var r homeop.OwnerReceipt |
| 869 | if !canonical(p, &r) || now >= r.Expires || r.Issued > now { |
| 870 | return homeop.OwnerReceipt{}, false |
| 871 | } |
| 872 | return r, true |
| 873 | } |
| 874 | |
| 875 | func claimedBindings(record []byte) (roster.Bindings, bool) { |
| 876 | p, err := homeop.EnvelopePayload(record) |
| 877 | if err != nil { |
| 878 | return roster.Bindings{}, false |
| 879 | } |
| 880 | var pr roster.Provisioning |
| 881 | if homeop.Decode(p, &pr) != nil { |
| 882 | return roster.Bindings{}, false |
| 883 | } |
| 884 | return pr.Bindings, true |
| 885 | } |
| 886 | |
| 887 | func (h *Home) manifest() string { |
| 888 | union := map[string]string{} |
| 889 | for id, o := range h.env { |
| 890 | union[id] = o |
| 891 | } |
| 892 | for id, c := range h.consumers { |
| 893 | if c.state == "active" { |
| 894 | union[id] = c.origin |
| 895 | } |
| 896 | } |
| 897 | return homeop.ManifestDigest(union) |
| 898 | } |
| 899 | |
| 900 | // KeyHex is a helper for tests that need a person ref. |
| 901 | func KeyHex(b []byte) string { return hex.EncodeToString(b) } |
| 902 | |