oficina / alta Public

homeop: Alta's half of Home's operator endpoint

The signed operation, plan and inspect challenge, every verb's input and
Home's result, as Home's internal/operator declares them at 82d9388,
field for field and tag for tag, so the canonical encoding Home re-checks
(strictCanonical) matches. A client for both roles' /operator/v1 and
/operator/v1/plan that sends nothing a browser would, follows no
redirect, and reports Home's fixed outcomes (ok, refused, busy,
unavailable) plus 'lost' when no answer came back, from which nothing
is inferred.
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 9a055d4916100aa9a5ceb59dc75373b2bbe8de71
6 files changed, +964 −0
  • .gitignore +5 −0
  • go.mod +25 −0
  • go.sum +75 −0
  • homeop/client.go +205 −0
  • homeop/protocol.go +570 −0
  • homeop/protocol_test.go +84 −0
diff --git a/.gitignore b/.gitignore
new file mode 100644
index 0000000..b85f9cb
--- /dev/null
+++ b/.gitignore
@@ -0,0 +1,5 @@
+releases/
+*.db
+*.db-wal
+*.db-shm
+/alta
diff --git a/go.mod b/go.mod
new file mode 100644
index 0000000..7676bf3
--- /dev/null
+++ b/go.mod
@@ -0,0 +1,25 @@
+module amadan.net/oficina/alta
+
+go 1.26
+
+toolchain go1.26.5
+
+require (
+ amadan.net/oficina/home/handoff v0.0.0-20261028092646-82d938882ed3
+ amadan.net/oficina/home/roster v0.0.0-20261028092646-82d938882ed3
+ amadan.net/rastrillo/rastrillo v0.29.1-0.20261028004840-5bb38c0ab31b
+ github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2
+ modernc.org/sqlite v1.55.0
+)
+
+require (
+ github.com/dustin/go-humanize v1.0.1 // indirect
+ github.com/google/uuid v1.6.0 // indirect
+ github.com/mattn/go-isatty v0.0.20 // indirect
+ github.com/ncruces/go-strftime v1.0.0 // indirect
+ github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec // indirect
+ golang.org/x/sys v0.46.0 // indirect
+ modernc.org/libc v1.74.1 // indirect
+ modernc.org/mathutil v1.7.1 // indirect
+ modernc.org/memory v1.11.0 // indirect
+)
diff --git a/go.sum b/go.sum
new file mode 100644
index 0000000..53fb821
--- /dev/null
+++ b/go.sum
@@ -0,0 +1,75 @@
+amadan.net/oficina/home/handoff v0.0.0-20261028092646-82d938882ed3 h1:KQ3zM7eJp/JRQuPI2090jVcV5fJSVmOvonVAfSWzwUY=
+amadan.net/oficina/home/handoff v0.0.0-20261028092646-82d938882ed3/go.mod h1:YISpzFJ+iMgrM0rUL032OSzsAQbP4/nozvXLCCOcn1k=
+amadan.net/oficina/home/roster v0.0.0-20261028092646-82d938882ed3 h1:AjimnZNNK8kIlaba371a4TgO7Z04DgLLBhjv25k2fPo=
+amadan.net/oficina/home/roster v0.0.0-20261028092646-82d938882ed3/go.mod h1:gqshuXyDtFZUCYbhuZyV3Epc51pUcsLbpqAqiA5UiXg=
+amadan.net/rastrillo/rastrillo v0.29.1-0.20261028004840-5bb38c0ab31b h1:7rApPVcEQ4MReZ6Q1h6fydrxtQwjd6kk6MyzQfpHYjo=
+amadan.net/rastrillo/rastrillo v0.29.1-0.20261028004840-5bb38c0ab31b/go.mod h1:jSSeydqEvlm/fU3hhWoXFnyEaDgroR8LPRZSo9ZhhIM=
+amadan.net/rastrillo/rastrillo/money v0.1.0 h1:MxU4oqNrW8abxRTkgZBv24OYNpFnvonajNqeLIzmmaM=
+amadan.net/rastrillo/rastrillo/money v0.1.0/go.mod h1:cmgkjBEIQh1pFSYvQk0UU6oPYS8kSDypdT9+t4Flx0U=
+github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY=
+github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto=
+github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2 h1:iizUGZ9pEquQS5jTGkh4AqeeHCMbfbjeb0zMt0aEFzs=
+github.com/go-json-experiment/json v0.0.0-20250725192818-e39067aee2d2/go.mod h1:TiCD2a1pcmjd7YnhGH0f/zKNcCD06B029pHhzV23c2M=
+github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e h1:ijClszYn+mADRFY17kjQEVQ1XRhq2/JR1M3sGqeJoxs=
+github.com/google/pprof v0.0.0-20250317173921-a4b03ec1a45e/go.mod h1:boTsfXsheKC2y+lKOCMpSfarhxDeIzfZG1jqGcPl3cA=
+github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0=
+github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo=
+github.com/hashicorp/golang-lru/v2 v2.0.7 h1:a+bsQ5rvGLjzHuww6tVxozPZFVghXaHOwFs4luLUK2k=
+github.com/hashicorp/golang-lru/v2 v2.0.7/go.mod h1:QeFd9opnmA6QUJc5vARoKUSoFhyfM2/ZepoAG6RGpeM=
+github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
+github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
+github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
+github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
+github.com/keymaildev/signin v0.1.1 h1:gO+1IAM99sqUkBtCezkgGxab+/DOrqwDxd5H32N1s9Q=
+github.com/keymaildev/signin v0.1.1/go.mod h1:Eb/sCmEel1jlcdkgPOrNeMn5jvxzoFvJrdjDUxOBHls=
+github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
+github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
+github.com/ncruces/go-strftime v1.0.0 h1:HMFp8mLCTPp341M/ZnA4qaf7ZlsbTc+miZjCLOFAw7w=
+github.com/ncruces/go-strftime v1.0.0/go.mod h1:Fwc5htZGVVkseilnfgOVb9mKy6w1naJmn9CehxcKcls=
+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec h1:W09IVJc94icq4NjY3clb7Lk8O1qJ8BdBEF8z0ibU0rE=
+github.com/remyoudompheng/bigfft v0.0.0-20230129092748-24d4a6f8daec/go.mod h1:qqbHyh8v60DhA7CoWK5oRCqLrMHRGoxYCSS9EjAz6Eo=
+github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e h1:MRM5ITcdelLK2j1vwZ3Je0FKVCfqOLp5zO6trqMLYs0=
+github.com/skip2/go-qrcode v0.0.0-20200617195104-da1b6568686e/go.mod h1:XV66xRDqSt+GTGFMVlhk3ULuV0y9ZmzeVGR4mloJI3M=
+golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
+golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
+golang.org/x/sync v0.21.0 h1:HLII4xRRTtCRkxYp4HNFF0Js/Og6q2i++KXbg0gHCwM=
+golang.org/x/sync v0.21.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
+golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
+golang.org/x/sys v0.46.0 h1:noSf2Fq6F8DBgS+LysIkx7rIExoNHJsxOAtPp4rthXw=
+golang.org/x/sys v0.46.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
+golang.org/x/text v0.39.0 h1:UbZz4pLOvn600D6Oh6GGEI6VAmndrEBLv8/6BEXzyus=
+golang.org/x/text v0.39.0/go.mod h1:3UwRclnC2g0TU9x8PZiyfOajCd1zaUNHF9cvqcQZ+ZM=
+golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
+golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
+gorm.io/gorm v1.31.2 h1:3o8FXNo9v9S858gil+3LlZA1LkCOzgb4g5BL64FgaCo=
+gorm.io/gorm v1.31.2/go.mod h1:XyQVbO2k6YkOis7C2437jSit3SsDK72s7n7rsSHd+Gs=
+gorm.io/plugin/dbresolver v1.6.2 h1:F4b85TenghUeITqe3+epPSUtHH7RIk3fXr5l83DF8Pc=
+gorm.io/plugin/dbresolver v1.6.2/go.mod h1:tctw63jdrOezFR9HmrKnPkmig3m5Edem9fdxk9bQSzM=
+modernc.org/cc/v4 v4.29.0 h1:CXgwL8cvxmyzBQZzbSl/6xFtMCryb6u8IOqDci39cgc=
+modernc.org/cc/v4 v4.29.0/go.mod h1:OnovgIhbbMXMu1aISnJ0wvVD1KnW+cAUJkIrAWh+kVI=
+modernc.org/ccgo/v4 v4.34.6 h1:sBgfIwyN0TQ9C5hwIeuqyeAKyMWnbvj2fvpF4L11uzU=
+modernc.org/ccgo/v4 v4.34.6/go.mod h1:SZ8YcN9NG7XVsQYdm6jYBvi8PQP1qi+kqB6OhjqI3Fk=
+modernc.org/fileutil v1.4.0 h1:j6ZzNTftVS054gi281TyLjHPp6CPHr2KCxEXjEbD6SM=
+modernc.org/fileutil v1.4.0/go.mod h1:EqdKFDxiByqxLk8ozOxObDSfcVOv/54xDs/DUHdvCUU=
+modernc.org/gc/v2 v2.6.5 h1:nyqdV8q46KvTpZlsw66kWqwXRHdjIlJOhG6kxiV/9xI=
+modernc.org/gc/v2 v2.6.5/go.mod h1:YgIahr1ypgfe7chRuJi2gD7DBQiKSLMPgBQe9oIiito=
+modernc.org/gc/v3 v3.1.4 h1:2g65LGVSmFQrXeITAw97x7hCRvZFcyE1uDP+7Vng7JI=
+modernc.org/gc/v3 v3.1.4/go.mod h1:HFK/6AGESC7Ex+EZJhJ2Gni6cTaYpSMmU/cT9RmlfYY=
+modernc.org/goabi0 v0.2.0 h1:HvEowk7LxcPd0eq6mVOAEMai46V+i7Jrj13t4AzuNks=
+modernc.org/goabi0 v0.2.0/go.mod h1:CEFRnnJhKvWT1c1JTI3Avm+tgOWbkOu5oPA8eH8LnMI=
+modernc.org/libc v1.74.1 h1:bdR4VTKFMC4966QSNZ05XLGI/VwzVa2kTUX51Dm0riQ=
+modernc.org/libc v1.74.1/go.mod h1:uH4t5bOx3G3g9Xcmj10YKlTcVISlRDwv8VoQJG9n8Os=
+modernc.org/mathutil v1.7.1 h1:GCZVGXdaN8gTqB1Mf/usp1Y/hSqgI2vAGGP4jZMCxOU=
+modernc.org/mathutil v1.7.1/go.mod h1:4p5IwJITfppl0G4sUEDtCr4DthTaT47/N3aT6MhfgJg=
+modernc.org/memory v1.11.0 h1:o4QC8aMQzmcwCK3t3Ux/ZHmwFPzE6hf2Y5LbkRs+hbI=
+modernc.org/memory v1.11.0/go.mod h1:/JP4VbVC+K5sU2wZi9bHoq2MAkCnrt2r98UGeSK7Mjw=
+modernc.org/opt v0.2.0 h1:tGyef5ApycA7FSEOMraay9SaTk5zmbx7Tu+cJs4QKZg=
+modernc.org/opt v0.2.0/go.mod h1:03fq9lsNfvkYSfxrfUhZCWPk1lm4cq4N+Bh//bEtgns=
+modernc.org/sortutil v1.2.1 h1:+xyoGf15mM3NMlPDnFqrteY07klSFxLElE2PVuWIJ7w=
+modernc.org/sortutil v1.2.1/go.mod h1:7ZI3a3REbai7gzCLcotuw9AC4VZVpYMjDzETGsSMqJE=
+modernc.org/sqlite v1.55.0 h1:hIFh0MCH0rGinQ/4KYb5/UbCkRkb+UP+OkLCVWa5MTM=
+modernc.org/sqlite v1.55.0/go.mod h1:4ntCLuNmnH8+GNqjka1wNg7KJd5/Hi5FYp8K+XQ7GZw=
+modernc.org/strutil v1.2.1 h1:UneZBkQA+DX2Rp35KcM69cSsNES9ly8mQWD71HKlOA0=
+modernc.org/strutil v1.2.1/go.mod h1:EHkiggD70koQxjVdSBM3JKM7k6L0FbGE5eymy9i3B9A=
+modernc.org/token v1.1.0 h1:Xl7Ap9dKaEs5kLoOQeQmPWevfnk/DM5qcLcYlA8ys6Y=
+modernc.org/token v1.1.0/go.mod h1:UGzOrNV1mAFSEB63lOFHIpNRUVMvYTc6yu1SMY/XTDM=
diff --git a/homeop/client.go b/homeop/client.go
new file mode 100644
index 0000000..e8ef761
--- /dev/null
+++ b/homeop/client.go
@@ -0,0 +1,205 @@
+package homeop
+
+import (
+ "bytes"
+ "context"
+ "crypto/sha256"
+ "encoding/base64"
+ stdjson "encoding/json"
+ "errors"
+ "fmt"
+ "io"
+ "net/http"
+ "slices"
+ "time"
+
+ family "amadan.net/rastrillo/rastrillo/crypto"
+)
+
+func manifestDigest(consumers map[string]string) string {
+ ids := make([]string, 0, len(consumers))
+ for id := range consumers {
+ ids = append(ids, id)
+ }
+ slices.Sort(ids)
+ entries := make([][2]string, 0, len(ids))
+ for _, id := range ids {
+ entries = append(entries, [2]string{id, consumers[id]})
+ }
+ b, err := stdjson.Marshal([]any{ManifestContext, entries})
+ if err != nil {
+ return ""
+ }
+ sum := sha256.Sum256(b)
+ return base64.RawURLEncoding.EncodeToString(sum[:])
+}
+
+// Outcome is what one call to Home's endpoint came to. Home answers a
+// refusal and an outage with fixed codes and nothing else (§6), so this
+// is all Alta can know, and all it may log.
+type Outcome int
+
+const (
+ // OK: 200, body is the result.
+ OK Outcome = iota
+ // Refused: Home said no (403 refused, 401 prefilter, 404, 405, 415).
+ Refused
+ // Busy: 409, a plan is already pending or a window open on the role.
+ Busy
+ // Unavailable: 503, or anything else Home answered.
+ Unavailable
+ // Lost: no answer. Nothing may be inferred from it (§6): the request
+ // may or may not have committed, and only an exact replay says.
+ Lost
+)
+
+func (o Outcome) String() string {
+ return [...]string{"ok", "refused", "busy", "unavailable", "lost"}[o]
+}
+
+// Role is one Home role's endpoint as Alta reaches it: its origin, the
+// pins Home holds for Alta, and the prefilter bearer.
+type Role struct {
+ Name string
+ Origin string
+ // URL is where the role is reached, when that is not Origin (a test
+ // server); the pins still name Origin.
+ URL string
+ Installation string
+ Registry string
+ Device string
+}
+
+// Client talks to both roles' /operator/v1. It sends nothing a browser
+// would (no cookie, no Origin, no Sec-Fetch-*), as Home refuses those.
+type Client struct {
+ HTTP *http.Client
+ Key *family.Keypair
+ Prefilter string
+ Roles map[string]Role
+ Now func() time.Time
+}
+
+func (c *Client) now() time.Time {
+ if c.Now != nil {
+ return c.Now()
+ }
+ return time.Now()
+}
+
+func (c *Client) role(name string) (Role, error) {
+ r, ok := c.Roles[name]
+ if !ok {
+ return Role{}, fmt.Errorf("homeop: no role %q", name)
+ }
+ return r, nil
+}
+
+// Post sends body to one of the role's two routes.
+func (c *Client) Post(ctx context.Context, role, path string, body []byte) (Outcome, []byte) {
+ r, err := c.role(role)
+ if err != nil {
+ return Refused, nil
+ }
+ base := r.Origin
+ if r.URL != "" {
+ base = r.URL
+ }
+ req, err := http.NewRequestWithContext(ctx, http.MethodPost, base+path, bytes.NewReader(body))
+ if err != nil {
+ return Refused, nil
+ }
+ req.Header.Set("Content-Type", "application/json")
+ req.Header.Set("Authorization", "Bearer "+c.Prefilter)
+ client := c.HTTP
+ if client == nil {
+ client = http.DefaultClient
+ }
+ // No redirect is followed: Home's operator routes never redirect, and
+ // a redirect would carry the prefilter bearer somewhere else.
+ cc := *client
+ cc.CheckRedirect = func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }
+ resp, err := cc.Do(req)
+ if err != nil {
+ return Lost, nil
+ }
+ defer resp.Body.Close()
+ out, err := io.ReadAll(io.LimitReader(resp.Body, BodyLimit+1))
+ if err != nil || len(out) > BodyLimit {
+ if resp.StatusCode == http.StatusOK {
+ return Lost, nil
+ }
+ return Unavailable, nil
+ }
+ switch resp.StatusCode {
+ case http.StatusOK:
+ return OK, out
+ case http.StatusConflict:
+ return Busy, nil
+ case http.StatusForbidden, http.StatusUnauthorized, http.StatusNotFound, http.StatusMethodNotAllowed, http.StatusUnsupportedMediaType, http.StatusRequestEntityTooLarge:
+ return Refused, nil
+ default:
+ return Unavailable, nil
+ }
+}
+
+// Inspect signs a fresh challenge for role and returns Home's answer,
+// checked to answer this challenge.
+func (c *Client) Inspect(ctx context.Context, role string) (Inspection, Outcome, error) {
+ r, err := c.role(role)
+ if err != nil {
+ return Inspection{}, Refused, err
+ }
+ now := c.now().Unix()
+ ch := InspectChallenge{Role: role, Origin: r.Origin, Installation: r.Installation, Registry: r.Registry, Device: r.Device, Challenge: Token(), Issued: now, Expires: now + RequestLifetime}
+ raw, err := SignInspect(c.Key, ch)
+ if err != nil {
+ return Inspection{}, Refused, err
+ }
+ o, body := c.Post(ctx, role, "/operator/v1", raw)
+ if o != OK {
+ return Inspection{}, o, nil
+ }
+ var in Inspection
+ if Decode(body, &in) != nil || in.Version != 1 || in.Role != role || in.Challenge != ch.Challenge || in.Sequence < 0 {
+ return Inspection{}, Unavailable, errors.New("homeop: inspection does not answer the challenge")
+ }
+ return in, OK, nil
+}
+
+// SubmitPlan posts a signed plan to role.
+func (c *Client) SubmitPlan(ctx context.Context, role string, signed []byte) Outcome {
+ o, _ := c.Post(ctx, role, "/operator/v1/plan", signed)
+ return o
+}
+
+// Execute posts a signed operation and decodes the result.
+func (c *Client) Execute(ctx context.Context, role string, req []byte) (Result, []byte, Outcome) {
+ o, body := c.Post(ctx, role, "/operator/v1", req)
+ if o != OK {
+ return Result{}, nil, o
+ }
+ var res Result
+ if Decode(body, &res) != nil || res.Version != 1 || res.Outcome != "committed" {
+ return Result{}, nil, Unavailable
+ }
+ return res, body, OK
+}
+
+// NewPlan fills a plan's pins for role.
+func (c *Client) NewPlan(role, planID, kind string, apps []string, issued time.Time) (Plan, error) {
+ r, err := c.role(role)
+ if err != nil {
+ return Plan{}, err
+ }
+ return Plan{Role: role, Origin: r.Origin, Installation: r.Installation, Registry: r.Registry, Device: r.Device, PlanID: planID, Kind: kind, Apps: append([]string{}, apps...), Issued: issued.Unix(), Expires: issued.Unix() + PlanLifetime}, nil
+}
+
+// NewAuthorization fills an authorization's pins for role.
+func (c *Client) NewAuthorization(role string) (Authorization, error) {
+ r, err := c.role(role)
+ if err != nil {
+ return Authorization{}, err
+ }
+ return Authorization{Role: role, Origin: r.Origin, Installation: r.Installation, Registry: r.Registry, Device: r.Device}, nil
+}
diff --git a/homeop/protocol.go b/homeop/protocol.go
new file mode 100644
index 0000000..31322b3
--- /dev/null
+++ b/homeop/protocol.go
@@ -0,0 +1,570 @@
+// Package homeop is Alta's half of Home's operator endpoint
+// (home implementation/team-provisioning-amendment.md §3–§7): the signed
+// operation, the signed plan, the signed inspect challenge, every verb's
+// input and the result Home returns.
+//
+// Home verifies each of these by decoding it strictly and re-encoding it
+// with go-json-experiment's deterministic encoder, then comparing bytes
+// (internal/operator/protocol.go strictCanonical). So the structs here are
+// Home's own, field for field and tag for tag, in the same order: a field
+// moved here is a request Home refuses. homecompat/ checks every one of
+// them against Home's real verifier and engine.
+package homeop
+
+import (
+ "crypto/elliptic"
+ "crypto/rand"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/hex"
+ "errors"
+ "net/mail"
+ "net/url"
+ "strings"
+ "unicode"
+ "unicode/utf8"
+
+ family "amadan.net/rastrillo/rastrillo/crypto"
+ "github.com/go-json-experiment/json"
+ "github.com/go-json-experiment/json/jsontext"
+)
+
+// Contexts and limits, as Home declares them.
+const (
+ InputContext = "oficina/home/operator-input/v1"
+ PlanContext = "oficina/home/operator-plan/v1"
+ InspectContext = "oficina/home/operator-inspect/v1"
+ OwnerContext = "oficina/home/owner-seed/v1"
+
+ BodyLimit = 64 << 10
+ InputLimit = 48 << 10
+ AuthorizationLimit = 16 << 10
+ PlanLimit = 8 << 10
+
+ // RequestLifetime is an operation's and an inspect challenge's
+ // signed life; Home refuses more than 300 s.
+ RequestLifetime = 300
+ // PlanLifetime bounds a plan; WindowLifetime is the window Paul's
+ // confirmation opens. Home never extends either.
+ PlanLifetime = 900
+ WindowLifetime = 900
+
+ // Baseline is the only baseline_attestation directory.initialize
+ // accepts. Alta sends it only after Paul types it (§6 step 1).
+ Baseline = "operator-attests-never-provisioned"
+ // ActivationPolicy is ActivationEvidence.Policy.
+ ActivationPolicy = "oficina/team-activation/v1"
+ // ManifestContext is the consumer manifest digest's domain string.
+ ManifestContext = "oficina/home/consumer-manifest/v1"
+)
+
+// Roles.
+const (
+ Credential = "credential"
+ Directory = "directory"
+)
+
+// Plan kinds.
+const (
+ KindInitialize = "initialize"
+ KindCreateTeam = "create-team"
+ KindAddApps = "add-apps"
+ KindRetireApps = "retire-apps"
+)
+
+// Verbs.
+const (
+ DirectoryInspect = "directory.inspect"
+ DirectoryInitialize = "directory.initialize"
+ DirectorySeedTeam = "directory.seed-team"
+ DirectoryProvision = "directory.provision-consumer"
+ DirectoryVerify = "directory.verify-consumer"
+ DirectoryActivate = "directory.activate-consumer"
+ DirectoryDisable = "directory.disable-consumer"
+ CredentialInspect = "credential.inspect"
+ CredentialOwnerSeed = "credential.owner-seed"
+ CredentialRegister = "credential.register-consumer"
+ CredentialRetire = "credential.retire-consumer"
+)
+
+var ErrRefused = errors.New("homeop: refused")
+
+// Authorization is Home's signed operator authority (protocol.go).
+type Authorization struct {
+ Version int `json:"version"`
+ Purpose string `json:"purpose"`
+ Role string `json:"role"`
+ Origin string `json:"origin"`
+ Installation string `json:"installation"`
+ Registry string `json:"registry"`
+ Device string `json:"device"`
+ Sequence int64 `json:"sequence"`
+ Initial bool `json:"initial_authority"`
+ Previous string `json:"previous"`
+ JournalSequence int64 `json:"journal_sequence"`
+ OperationID string `json:"operation_id"`
+ Action string `json:"action"`
+ InputDigest string `json:"input_digest"`
+ Issued int64 `json:"issued_at"`
+ Expires int64 `json:"expires_at"`
+}
+
+type envelope struct {
+ Version int `json:"v"`
+ KeyID string `json:"kid"`
+ Payload string `json:"payload"`
+ Signature string `json:"signature"`
+}
+
+type wrapper struct {
+ Version int `json:"version"`
+ Authorization jsontext.Value `json:"signed_authorization"`
+ Input jsontext.Value `json:"operation_input"`
+}
+
+// Plan is what Alta signs and submits to each role (plan.go).
+type Plan struct {
+ Version int `json:"version"`
+ Purpose string `json:"purpose"`
+ Role string `json:"role"`
+ Origin string `json:"origin"`
+ Installation string `json:"installation"`
+ Registry string `json:"registry"`
+ Device string `json:"device"`
+ PlanID string `json:"plan_id"`
+ Kind string `json:"kind"`
+ Apps []string `json:"apps"`
+ Label string `json:"label,omitzero"`
+ DisplayName string `json:"display_name,omitzero"`
+ Owner string `json:"owner,omitzero"`
+ Issued int64 `json:"issued_at"`
+ Expires int64 `json:"expires_at"`
+}
+
+// InspectChallenge is <role>.inspect's signed request (inspect.go).
+type InspectChallenge struct {
+ Version int `json:"version"`
+ Purpose string `json:"purpose"`
+ Role string `json:"role"`
+ Origin string `json:"origin"`
+ Installation string `json:"installation"`
+ Registry string `json:"registry"`
+ Device string `json:"device"`
+ Challenge string `json:"challenge"`
+ Issued int64 `json:"issued_at"`
+ Expires int64 `json:"expires_at"`
+}
+
+// Inspection is <role>.inspect's answer (http_verbs.go HTTPInspection).
+type Inspection struct {
+ Version int `json:"version"`
+ Role string `json:"role"`
+ Challenge string `json:"challenge"`
+ Observed int64 `json:"observed_at"`
+ Sequence int64 `json:"sequence"`
+ Head string `json:"head"`
+ Generation *string `json:"generation,omitempty"`
+ TeamID int64 `json:"proposed_team_id,omitempty"`
+ TeamSQID string `json:"proposed_team_sqid,omitempty"`
+ PendingPlan string `json:"pending_plan,omitempty"`
+ PendingExpires int64 `json:"pending_expires_at,omitempty"`
+ OpenPlan string `json:"open_plan,omitempty"`
+ WindowExpires int64 `json:"window_expires_at,omitempty"`
+}
+
+// InputBase opens every operation input.
+type InputBase struct {
+ Version int `json:"version"`
+ Operation string `json:"operation"`
+ OperationID string `json:"operation_id"`
+}
+
+type InitializeInput struct {
+ InputBase
+ ExpectedGeneration *string `json:"expected_generation"`
+ Generation string `json:"generation"`
+ Baseline string `json:"baseline_attestation"`
+}
+
+type SeedInput struct {
+ InputBase
+ Generation string `json:"expected_generation"`
+ TeamID int64 `json:"team_id"`
+ TeamSQID string `json:"team_sqid"`
+ Label string `json:"label"`
+ Name string `json:"display_name"`
+ Receipt jsontext.Value `json:"receipt"`
+}
+
+type ProvisionInput struct {
+ InputBase
+ Generation string `json:"expected_generation"`
+ TeamSQID string `json:"team_sqid"`
+ App string `json:"app"`
+ Consumer string `json:"consumer"`
+ Audience string `json:"audience"`
+ Sequence int64 `json:"expected_sequence"`
+}
+
+type OwnerInput struct {
+ InputBase
+ Directory string `json:"directory"`
+ TeamID int64 `json:"team_id"`
+ TeamSQID string `json:"team_sqid"`
+ Address string `json:"address"`
+ ExistingOnly bool `json:"existing_only"`
+}
+
+type RegisterInput struct {
+ InputBase
+ Record jsontext.Value `json:"record"`
+}
+
+type RetireInput struct {
+ InputBase
+ Consumer string `json:"consumer"`
+}
+
+type DisableInput struct {
+ InputBase
+ Generation string `json:"expected_generation"`
+ TeamSQID string `json:"team_sqid"`
+ App string `json:"app"`
+ Consumer string `json:"consumer"`
+}
+
+type VerificationInput struct {
+ InputBase
+ Consumer string `json:"consumer"`
+ TeamSQID string `json:"team_sqid"`
+ App string `json:"app"`
+ Audience string `json:"audience"`
+ Generation string `json:"generation"`
+ RecordSequence int64 `json:"record_sequence"`
+ RecordDigest string `json:"record_digest"`
+ Epoch int64 `json:"expected_epoch"`
+ Owner string `json:"owner_ref"`
+ Issued int64 `json:"issued_at"`
+ Expires int64 `json:"expires_at"`
+}
+
+type ActivationEvidence struct {
+ Version int `json:"version"`
+ Policy string `json:"policy"`
+ Attempt string `json:"attempt_id"`
+ Consumer string `json:"consumer"`
+ TeamSQID string `json:"team_sqid"`
+ App string `json:"app"`
+ Audience string `json:"audience"`
+ Generation string `json:"generation"`
+ RecordSequence int64 `json:"record_sequence"`
+ RecordDigest string `json:"record_digest"`
+ Epoch int64 `json:"epoch"`
+ Owner string `json:"owner_ref"`
+ AppVersion string `json:"app_version"`
+ ArtifactDigest string `json:"artifact_digest"`
+ EnvironmentBinding string `json:"environment_binding"`
+ ManifestDigest string `json:"credential_manifest_digest"`
+ AliasHost string `json:"alias_host"`
+ Started int64 `json:"started_at"`
+ Completed int64 `json:"completed_at"`
+}
+
+type ActivationInput struct {
+ InputBase
+ Evidence ActivationEvidence `json:"evidence"`
+}
+
+// Result is the engine's result JSON (directory.go Result).
+type Result struct {
+ Attempt string `json:"attempt_id,omitempty"`
+ Expires int64 `json:"expires_at,omitempty"`
+ Version int `json:"version"`
+ OperationID string `json:"operation_id"`
+ Outcome string `json:"outcome"`
+ Generation string `json:"generation,omitempty"`
+ TeamID int64 `json:"team_id,omitempty"`
+ TeamSQID string `json:"team_sqid,omitempty"`
+ Epoch int64 `json:"epoch,omitempty"`
+ Record jsontext.Value `json:"record,omitempty"`
+ Bearer string `json:"bearer,omitempty"`
+ Receipt jsontext.Value `json:"receipt,omitempty"`
+ Manifest string `json:"credential_manifest_digest,omitempty"`
+}
+
+// OwnerReceipt is the payload of the credential role's signed owner
+// receipt. Alta reads it (person_ref, expiry) but never verifies it: the
+// directory does.
+type OwnerReceipt struct {
+ Version int `json:"version"`
+ Purpose string `json:"purpose"`
+ OperationID string `json:"operation_id"`
+ Issuer string `json:"issuer"`
+ Directory string `json:"directory"`
+ TeamID int64 `json:"team_id"`
+ TeamSQID string `json:"team_sqid"`
+ PersonRef string `json:"person_ref"`
+ Role string `json:"role"`
+ Issued int64 `json:"issued_at"`
+ Expires int64 `json:"expires_at"`
+}
+
+// Encode is Home's canonical encoding.
+func Encode(v any) ([]byte, error) {
+ b, err := json.Marshal(v, json.Deterministic(true))
+ if err != nil {
+ return nil, ErrRefused
+ }
+ return b, nil
+}
+
+// Decode is Home's strict decoding: valid UTF-8, no unknown members.
+func Decode(b []byte, v any) error {
+ if !utf8.Valid(b) || json.Unmarshal(b, v, json.RejectUnknownMembers(true)) != nil {
+ return ErrRefused
+ }
+ return nil
+}
+
+// Token is 32 random bytes, base64url without padding: an operation id,
+// a plan id, a challenge, a generation.
+func Token() string {
+ b := make([]byte, 32)
+ if _, err := rand.Read(b); err != nil {
+ panic(err)
+ }
+ return base64.RawURLEncoding.EncodeToString(b)
+}
+
+// CanonicalToken is Home's token rule: exactly 32 bytes, canonical
+// unpadded base64url.
+func CanonicalToken(s string) bool {
+ b, err := base64.RawURLEncoding.Strict().DecodeString(s)
+ return err == nil && len(b) == 32 && base64.RawURLEncoding.EncodeToString(b) == s
+}
+
+// Digest is base64url(SHA-256(b)), Home's input digest and stream head.
+func Digest(b []byte) string {
+ h := sha256.Sum256(b)
+ return base64.RawURLEncoding.EncodeToString(h[:])
+}
+
+// KeyID is hex(SHA-256(public key)), the envelope's kid.
+func KeyID(public []byte) string {
+ h := sha256.Sum256(public)
+ return hex.EncodeToString(h[:])
+}
+
+// Origin is Home's origin rule.
+func Origin(s string) bool {
+ if len(s) == 0 || len(s) > 253 {
+ return false
+ }
+ u, e := url.Parse(s)
+ return e == nil && u.Scheme == "https" && u.Host != "" && u.Host == strings.ToLower(u.Host) && u.User == nil && u.Path == "" && u.RawPath == "" && u.RawQuery == "" && !u.ForceQuery && u.Fragment == "" && u.RawFragment == "" && !strings.ContainsAny(u.Host, "%\\:") && !strings.HasSuffix(u.Host, ".") && u.String() == s
+}
+
+// OwnerAddress is the exact form owner-seed accepts: a bare address that
+// parses to itself.
+func OwnerAddress(s string) bool {
+ if len(s) == 0 || len(s) > 320 || !utf8.ValidString(s) {
+ return false
+ }
+ a, e := mail.ParseAddress(s)
+ return e == nil && a.Address == s && a.Name == ""
+}
+
+// TeamName is the directory's team-name rule.
+func TeamName(s string) bool {
+ if len(s) == 0 || len(s) > 255 || !utf8.ValidString(s) || strings.TrimSpace(s) == "" {
+ return false
+ }
+ for _, r := range s {
+ if unicode.IsControl(r) {
+ return false
+ }
+ }
+ return true
+}
+
+// PersonRef is Home's person reference shape.
+func PersonRef(s string) bool {
+ if len(s) != 29 || !strings.HasPrefix(s, "pr_") {
+ return false
+ }
+ for _, c := range s[3:] {
+ if !(c >= 'a' && c <= 'z' || c >= '2' && c <= '7') {
+ return false
+ }
+ }
+ return true
+}
+
+// PlanPrefix is the first 8 hex digits of a plan id: what Paul matches on
+// both Home confirm pages.
+func PlanPrefix(id string) string {
+ b, err := base64.RawURLEncoding.Strict().DecodeString(id)
+ if err != nil || len(b) != 32 {
+ return ""
+ }
+ return hex.EncodeToString(b[:4])
+}
+
+// signingKey mirrors Home's check on the signer.
+func signingKey(k *family.Keypair) bool {
+ if k == nil || k.SignPriv == nil {
+ return false
+ }
+ p := k.SignPriv
+ return p.Curve == elliptic.P256() && p.D != nil && p.D.Sign() > 0 && p.D.Cmp(elliptic.P256().Params().N) < 0 && p.X != nil && p.Y != nil && elliptic.P256().IsOnCurve(p.X, p.Y)
+}
+
+func sealEnvelope(k *family.Keypair, context string, payload []byte) ([]byte, error) {
+ sig, err := family.Sign(k, context, payload)
+ if err != nil {
+ return nil, ErrRefused
+ }
+ return Encode(envelope{1, KeyID(k.SignPub()), base64.RawURLEncoding.EncodeToString(payload), base64.RawURLEncoding.EncodeToString(sig)})
+}
+
+// EnvelopePayload returns the payload bytes of a signed envelope without
+// verifying it. Alta uses it to read an owner receipt Home produced.
+func EnvelopePayload(raw []byte) ([]byte, error) {
+ var env envelope
+ if Decode(raw, &env) != nil || env.Version != 1 {
+ return nil, ErrRefused
+ }
+ b, err := base64.RawURLEncoding.Strict().DecodeString(env.Payload)
+ if err != nil {
+ return nil, ErrRefused
+ }
+ return b, nil
+}
+
+// ReadReceipt reads an owner receipt's payload.
+func ReadReceipt(raw []byte) (OwnerReceipt, error) {
+ var r OwnerReceipt
+ p, err := EnvelopePayload(raw)
+ if err != nil || Decode(p, &r) != nil || r.Version != 1 || r.Purpose != "owner-seed" || !PersonRef(r.PersonRef) {
+ return OwnerReceipt{}, ErrRefused
+ }
+ return r, nil
+}
+
+// Request is one signed operation: the exact bytes Alta sends (and keeps,
+// sealed, for exact replay) and the stream head it becomes once committed.
+type Request struct {
+ Bytes []byte
+ Head string
+ Authorization Authorization
+}
+
+// SignRequest signs input under a, filling a's input digest. a must
+// already carry the sequence, previous head, operation id and clock.
+func SignRequest(k *family.Keypair, a Authorization, input any) (Request, error) {
+ if !signingKey(k) {
+ return Request{}, ErrRefused
+ }
+ in, err := Encode(input)
+ if err != nil || len(in) > InputLimit {
+ return Request{}, ErrRefused
+ }
+ a.Version, a.Purpose = 1, "operator-input"
+ a.InputDigest = Digest(in)
+ a.Initial = a.Sequence == 1
+ if !validAuthorization(a) {
+ return Request{}, ErrRefused
+ }
+ payload, err := Encode(a)
+ if err != nil {
+ return Request{}, err
+ }
+ env, err := sealEnvelope(k, InputContext, payload)
+ if err != nil || len(env) > AuthorizationLimit {
+ return Request{}, ErrRefused
+ }
+ out, err := Encode(wrapper{1, env, in})
+ if err != nil || len(out) > BodyLimit {
+ return Request{}, ErrRefused
+ }
+ return Request{Bytes: out, Head: Digest(env), Authorization: a}, nil
+}
+
+// ReadRequest recovers the authorization of a request Alta signed, so a
+// sealed request row needs no copy of it.
+func ReadRequest(raw []byte) (Request, error) {
+ var w wrapper
+ if Decode(raw, &w) != nil || w.Version != 1 {
+ return Request{}, ErrRefused
+ }
+ p, err := EnvelopePayload(w.Authorization)
+ if err != nil {
+ return Request{}, err
+ }
+ var a Authorization
+ if Decode(p, &a) != nil {
+ return Request{}, ErrRefused
+ }
+ return Request{Bytes: raw, Head: Digest(w.Authorization), Authorization: a}, nil
+}
+
+func validAuthorization(a Authorization) bool {
+ return a.Version == 1 && a.Purpose == "operator-input" && Origin(a.Origin) && CanonicalToken(a.Installation) && CanonicalToken(a.Registry) && CanonicalToken(a.Device) && CanonicalToken(a.OperationID) && CanonicalToken(a.InputDigest) && a.Sequence > 0 && a.Initial == (a.Sequence == 1) && a.JournalSequence > 0 && ((a.Sequence == 1 && a.Previous == "") || (a.Sequence > 1 && CanonicalToken(a.Previous))) && a.Issued > 0 && a.Expires > a.Issued && a.Expires-a.Issued <= RequestLifetime && allowedAction(a.Role, a.Action)
+}
+
+func allowedAction(role, a string) bool {
+ switch role {
+ case Credential:
+ switch a {
+ case CredentialOwnerSeed, CredentialRegister, CredentialRetire, CredentialInspect:
+ return true
+ }
+ case Directory:
+ switch a {
+ case DirectoryInspect, DirectoryInitialize, DirectorySeedTeam, DirectoryProvision, DirectoryVerify, DirectoryActivate, DirectoryDisable:
+ return true
+ }
+ }
+ return false
+}
+
+// SignPlan signs a plan under the plan context.
+func SignPlan(k *family.Keypair, p Plan) ([]byte, error) {
+ if !signingKey(k) {
+ return nil, ErrRefused
+ }
+ p.Version, p.Purpose = 1, "operator-plan"
+ if p.Apps == nil {
+ p.Apps = []string{}
+ }
+ payload, err := Encode(p)
+ if err != nil {
+ return nil, err
+ }
+ out, err := sealEnvelope(k, PlanContext, payload)
+ if err != nil || len(out) > PlanLimit {
+ return nil, ErrRefused
+ }
+ return out, nil
+}
+
+// SignInspect signs an inspect challenge.
+func SignInspect(k *family.Keypair, c InspectChallenge) ([]byte, error) {
+ if !signingKey(k) {
+ return nil, ErrRefused
+ }
+ c.Version, c.Purpose = 1, "operator-inspect"
+ payload, err := Encode(c)
+ if err != nil {
+ return nil, err
+ }
+ return sealEnvelope(k, InspectContext, payload)
+}
+
+// ManifestDigest is §7's credential_manifest_digest: base64url(SHA-256(
+// encoding/json.Marshal(["oficina/home/consumer-manifest/v1", [[id,
+// origin], …]]))), entries sorted by consumer id bytes. Alta computes it
+// only to check what step 6 returned against what it expects.
+func ManifestDigest(consumers map[string]string) string {
+ return manifestDigest(consumers)
+}
diff --git a/homeop/protocol_test.go b/homeop/protocol_test.go
new file mode 100644
index 0000000..3b5ee8d
--- /dev/null
+++ b/homeop/protocol_test.go
@@ -0,0 +1,84 @@
+package homeop
+
+import (
+ "bytes"
+ "encoding/base64"
+ "strings"
+ "testing"
+
+ family "amadan.net/rastrillo/rastrillo/crypto"
+)
+
+func TestSignRequestRoundTrip(t *testing.T) {
+ k, _ := family.Generate()
+ a := Authorization{Role: Directory, Origin: "https://oficina.works", Installation: Token(), Registry: Token(), Device: Token(), Sequence: 2, Previous: Token(), JournalSequence: 7, OperationID: Token(), Action: DirectoryProvision, Issued: 100, Expires: 400}
+ req, err := SignRequest(k, a, ProvisionInput{InputBase: InputBase{1, DirectoryProvision, a.OperationID}, Generation: Token(), TeamSQID: "abc", App: "docs", Consumer: "x-docs", Audience: "https://x.docs.oficina.works"})
+ if err != nil {
+ t.Fatal(err)
+ }
+ back, err := ReadRequest(req.Bytes)
+ if err != nil || back.Head != req.Head || back.Authorization != req.Authorization {
+ t.Fatalf("round trip: %v %+v", err, back)
+ }
+ if back.Authorization.Initial {
+ t.Fatal("sequence 2 is not initial")
+ }
+ // Canonical: re-encoding the decoded wrapper gives the same bytes.
+ var w wrapper
+ if Decode(req.Bytes, &w) != nil {
+ t.Fatal("decode")
+ }
+ re, _ := Encode(w)
+ if !bytes.Equal(re, req.Bytes) {
+ t.Fatal("not canonical")
+ }
+}
+
+func TestSignRequestRefusesWhatHomeRefuses(t *testing.T) {
+ k, _ := family.Generate()
+ good := Authorization{Role: Credential, Origin: "https://id.oficina.works", Installation: Token(), Registry: Token(), Device: Token(), Sequence: 1, JournalSequence: 1, OperationID: Token(), Action: CredentialOwnerSeed, Issued: 100, Expires: 400}
+ for name, mutate := range map[string]func(*Authorization){
+ "life over 300 s": func(a *Authorization) { a.Expires = a.Issued + 301 },
+ "verb of other role": func(a *Authorization) { a.Action = DirectorySeedTeam },
+ "previous at seq 1": func(a *Authorization) { a.Previous = Token() },
+ "no previous at seq2": func(a *Authorization) { a.Sequence = 2 },
+ "journal zero": func(a *Authorization) { a.JournalSequence = 0 },
+ "origin with path": func(a *Authorization) { a.Origin = "https://id.oficina.works/x" },
+ } {
+ a := good
+ mutate(&a)
+ if _, err := SignRequest(k, a, InputBase{1, a.Action, a.OperationID}); err == nil {
+ t.Errorf("%s: signed", name)
+ }
+ }
+ if _, err := SignRequest(k, good, InputBase{1, good.Action, good.OperationID}); err != nil {
+ t.Fatal(err)
+ }
+}
+
+func TestPlanCarriesEmptyAppsForInitialize(t *testing.T) {
+ k, _ := family.Generate()
+ raw, err := SignPlan(k, Plan{Role: Directory, Origin: "https://oficina.works", Installation: Token(), Registry: Token(), Device: Token(), PlanID: Token(), Kind: KindInitialize, Issued: 1, Expires: 900})
+ if err != nil {
+ t.Fatal(err)
+ }
+ p, _ := EnvelopePayload(raw)
+ if !strings.Contains(string(p), `"apps":[]`) || strings.Contains(string(p), "label") || strings.Contains(string(p), "owner") {
+ t.Fatalf("plan payload %s", p)
+ }
+}
+
+func TestPlanPrefix(t *testing.T) {
+ id := base64.RawURLEncoding.EncodeToString(append([]byte{0xde, 0xad, 0xbe, 0xef}, make([]byte, 28)...))
+ if got := PlanPrefix(id); got != "deadbeef" {
+ t.Fatal(got)
+ }
+}
+
+func TestManifestDigestIsOrderIndependent(t *testing.T) {
+ a := ManifestDigest(map[string]string{"docs": "https://docs.oficina.works", "alta": "https://alta.oficina.works"})
+ b := ManifestDigest(map[string]string{"alta": "https://alta.oficina.works", "docs": "https://docs.oficina.works"})
+ if a != b || !CanonicalToken(a) {
+ t.Fatal(a, b)
+ }
+}