From fd873a02c340763ca62310ba9217bcdd9f67f174 Mon Sep 17 00:00:00 2001 From: shoemoney Date: Tue, 23 Jun 2026 11:31:29 -0500 Subject: [PATCH] =?UTF-8?q?feat(M8a):=20device-facing=20invites=20with=20p?= =?UTF-8?q?rivilege=20attenuation=20=E2=9C=89=EF=B8=8F=F0=9F=94=90?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Completes M8a's collaboration surface. A member mints an invite; the invitee redeems it through the EXISTING /v1/join proof-of-possession flow and lands enrolled + assigned the bound principal + granted the bound role. - migration #3: invites table (token_hash → principal/share/role/+s), chains 0→1→2→3 — verified on a copy of the real hub DB. - POST /v1/invite (authed) enforces ATTENUATION server-side via the pure, unit-tested meta.MayGrant: never grant above your own role, never touch a principal who outranks you, viewers can't grant, editors need +s. On a legacy share the inviter is seeded as owner before the explicit flip so they (and their same-principal devices) never self-lock-out. - /v1/join applies a redeemed invite's binding (plain token = v1 join). - transport.Invite + devbox invite [--reshare]. Tests: MayGrant attenuation matrix, invite binding round-trip, and the end-to-end TestInviteFlow (owner invites → flip preserves owner → invitee redeems into editor → editor-without-+s denied). 18 pkgs -race green; linux/amd64 + windows cross-build. --- cmd/devbox/main.go | 34 +++++++++ internal/hub/meta/meta.go | 136 ++++++++++++++++++++++++++++----- internal/hub/meta/meta_test.go | 56 ++++++++++++++ internal/hub/server.go | 88 +++++++++++++++++++++ internal/hub/server_test.go | 76 ++++++++++++++++++ internal/transport/client.go | 9 +++ pkg/proto/proto.go | 16 ++++ 7 files changed, 398 insertions(+), 17 deletions(-) diff --git a/cmd/devbox/main.go b/cmd/devbox/main.go index 144b736..2f0de17 100644 --- a/cmd/devbox/main.go +++ b/cmd/devbox/main.go @@ -52,6 +52,7 @@ func main() { ignoreCmd(), conflictsCmd(), membersCmd(), + inviteCmd(), startCmd(), stopCmd(), pauseCmd(), @@ -305,6 +306,39 @@ func logCmd() *cobra.Command { } } +func inviteCmd() *cobra.Command { + var reshare bool + cmd := &cobra.Command{ + Use: "invite ", + Short: "✉️ mint an invite token granting a principal a role on a share (M8a)", + Args: cobra.ExactArgs(3), + RunE: func(cmd *cobra.Command, args []string) error { + dir, err := config.Dir() + if err != nil { + return err + } + d, err := config.LoadDaemon(dir) + if err != nil { + return err + } + if d.Hub == "" || d.Bearer == "" { + return fmt.Errorf("not joined — run: devbox join ") + } + c := transport.New(d.Hub) + c.SetBearer(d.Bearer) + tok, err := c.Invite(args[0], args[1], args[2], reshare) + if err != nil { + return err + } + fmt.Fprintf(cmd.OutOrStdout(), "✉️ invite for %s as %s on %s:\n %s\nthey run: devbox join %s %s\n", + args[1], args[2], args[0], tok, d.Hub, tok) + return nil + }, + } + cmd.Flags().BoolVar(&reshare, "reshare", false, "grant the +s bit (lets them delegate)") + return cmd +} + func membersCmd() *cobra.Command { return &cobra.Command{ Use: "members ", diff --git a/internal/hub/meta/meta.go b/internal/hub/meta/meta.go index 6138392..0d3deb4 100644 --- a/internal/hub/meta/meta.go +++ b/internal/hub/meta/meta.go @@ -132,6 +132,19 @@ CREATE TABLE members ( PRIMARY KEY (share, principal_id) ); ALTER TABLE shares ADD COLUMN acl_mode TEXT NOT NULL DEFAULT 'legacy'; +`, + // 3 (v2, M8a): invites. An invite is a normal one-time join token (so it rides + // the existing /v1/join proof-of-possession flow) PLUS a binding recorded here: + // when redeemed, the joining device is assigned the bound principal and granted + // the bound role on the share. A plain join token has no invites row → v1 join. + ` +CREATE TABLE invites ( + token_hash TEXT PRIMARY KEY, + principal_id TEXT NOT NULL, + share TEXT NOT NULL, + role INTEGER NOT NULL, + can_reshare INTEGER NOT NULL DEFAULT 0 +); `, } @@ -383,37 +396,126 @@ type Member struct { } // EffectiveRole returns a device's role on a share and whether the share is in -// explicit-ACL mode. In legacy mode (the v1 default — no member grants yet) every -// known device is an implicit RoleOwner, so v1 behavior is preserved exactly. In -// explicit mode the device's principal must hold a member row, else RoleViewer-1 -// (0) = deny-by-default. An unknown/revoked device gets 0 in either mode. +// explicit-ACL mode. Thin wrapper over EffectiveMember for the push write gate. func (d *DB) EffectiveRole(deviceID, share string) (role int, explicit bool, err error) { + role, _, explicit, err = d.EffectiveMember(deviceID, share) + return role, explicit, err +} + +// EffectiveMember returns a device's role, its reshare (+s) right, and whether +// the share is in explicit-ACL mode. In legacy mode (the v1 default — no member +// grants) every known device is an implicit RoleOwner with reshare, so v1 behavior +// is preserved exactly. In explicit mode the device's principal must hold a member +// row, else role 0 (deny-by-default). An unknown/revoked device gets 0. +func (d *DB) EffectiveMember(deviceID, share string) (role int, canReshare, explicit bool, err error) { var pid string err = d.sql.QueryRow(`SELECT principal_id FROM devices WHERE id=? AND revoked=0`, deviceID).Scan(&pid) if errors.Is(err, sql.ErrNoRows) { - return 0, false, nil + return 0, false, false, nil } if err != nil { - return 0, false, err + return 0, false, false, err } - var mode string - err = d.sql.QueryRow(`SELECT acl_mode FROM shares WHERE name=?`, share).Scan(&mode) - if errors.Is(err, sql.ErrNoRows) { - mode = "legacy" // unknown share: stay v1-permissive, push fails later if truly absent - } else if err != nil { - return 0, false, err + mode, err := d.ACLMode(share) + if err != nil { + return 0, false, false, err } if mode != "explicit" { - return RoleOwner, false, nil + return RoleOwner, true, false, nil // implicit owner can reshare } - err = d.sql.QueryRow(`SELECT role FROM members WHERE share=? AND principal_id=?`, share, pid).Scan(&role) + var cr int + err = d.sql.QueryRow(`SELECT role, can_reshare FROM members WHERE share=? AND principal_id=?`, share, pid).Scan(&role, &cr) if errors.Is(err, sql.ErrNoRows) { - return 0, true, nil // deny-by-default + return 0, false, true, nil // deny-by-default } if err != nil { - return 0, true, err + return 0, false, true, err } - return role, true, nil + return role, cr != 0, true, nil +} + +// DevicePrincipal returns the principal a device belongs to. +func (d *DB) DevicePrincipal(deviceID string) (string, error) { + var pid string + err := d.sql.QueryRow(`SELECT principal_id FROM devices WHERE id=?`, deviceID).Scan(&pid) + return pid, err +} + +// RoleOf returns a principal's current role on a share (0 if none/legacy). +func (d *DB) RoleOf(share, principalID string) (int, error) { + var role int + err := d.sql.QueryRow(`SELECT role FROM members WHERE share=? AND principal_id=?`, share, principalID).Scan(&role) + if errors.Is(err, sql.ErrNoRows) { + return 0, nil + } + return role, err +} + +// MayGrant reports whether a caller holding callerRole (and the +s bit) may set a +// principal currently at targetCurrentRole to grantRole. Pure attenuation: a +// compromised client can't escalate because the hub re-checks this server-side. +// - grantRole must be a real role; +// - viewers can't grant; editors need +s; admins/owners always may; +// - you can never grant ABOVE your own role (delegation only narrows); +// - you can never touch a principal who currently outranks you (no demoting up). +func MayGrant(callerRole int, callerCanReshare bool, targetCurrentRole, grantRole int) bool { + if grantRole < RoleViewer || grantRole > RoleOwner { + return false + } + if callerRole < RoleEditor { + return false + } + if callerRole < RoleAdmin && !callerCanReshare { + return false + } + return grantRole <= callerRole && targetCurrentRole <= callerRole +} + +// Invite is the binding redeemed when an invite token is used at /v1/join. +type Invite struct { + Principal string + Share string + Role int + CanReshare bool +} + +// CreateInvite mints an invite: a redeemable join token (in tokens) plus its +// binding (in invites), in one transaction. +func (d *DB) CreateInvite(tokenHash string, expiresAt int64, inv Invite) error { + tx, err := d.sql.Begin() + if err != nil { + return err + } + defer tx.Rollback() + if _, err := tx.Exec(`INSERT INTO tokens (hash, expires_at) VALUES (?,?)`, tokenHash, nullable(expiresAt)); err != nil { + return err + } + cr := 0 + if inv.CanReshare { + cr = 1 + } + if _, err := tx.Exec( + `INSERT INTO invites (token_hash, principal_id, share, role, can_reshare) VALUES (?,?,?,?,?)`, + tokenHash, inv.Principal, inv.Share, inv.Role, cr); err != nil { + return err + } + return tx.Commit() +} + +// InviteBinding returns the binding for a token hash (ok=false for a plain token). +func (d *DB) InviteBinding(tokenHash string) (inv Invite, ok bool, err error) { + var cr int + err = d.sql.QueryRow( + `SELECT principal_id, share, role, can_reshare FROM invites WHERE token_hash=?`, tokenHash). + Scan(&inv.Principal, &inv.Share, &inv.Role, &cr) + if errors.Is(err, sql.ErrNoRows) { + return Invite{}, false, nil + } + if err != nil { + return Invite{}, false, err + } + inv.CanReshare = cr != 0 + return inv, true, nil } // EnsurePrincipal creates a principal if absent (idempotent). diff --git a/internal/hub/meta/meta_test.go b/internal/hub/meta/meta_test.go index 54da6cd..92d37c3 100644 --- a/internal/hub/meta/meta_test.go +++ b/internal/hub/meta/meta_test.go @@ -459,6 +459,62 @@ func TestRolesLegacyAndExplicit(t *testing.T) { } } +// TestMayGrant locks down the invite attenuation rules (the security core): a +// caller can never grant above their own role, never touch a superior, viewers +// can't grant, and editors need the +s reshare bit. +func TestMayGrant(t *testing.T) { + cases := []struct { + name string + callerRole int + reshare bool + targetCurrent, grant int + want bool + }{ + {"owner grants editor", RoleOwner, false, 0, RoleEditor, true}, + {"owner grants owner (co-owner)", RoleOwner, false, 0, RoleOwner, true}, + {"admin grants admin", RoleAdmin, false, 0, RoleAdmin, true}, + {"admin can't grant owner (above self)", RoleAdmin, false, 0, RoleOwner, false}, + {"editor with +s grants editor", RoleEditor, true, 0, RoleEditor, true}, + {"editor with +s can't grant admin", RoleEditor, true, 0, RoleAdmin, false}, + {"editor WITHOUT +s can't grant", RoleEditor, false, 0, RoleViewer, false}, + {"viewer can't grant", RoleViewer, true, 0, RoleViewer, false}, + {"can't demote a superior owner", RoleEditor, true, RoleOwner, RoleViewer, false}, + {"invalid role rejected", RoleOwner, false, 0, 999, false}, + {"zero role (unmembered) can't grant", 0, false, 0, RoleViewer, false}, + } + for _, c := range cases { + if got := MayGrant(c.callerRole, c.reshare, c.targetCurrent, c.grant); got != c.want { + t.Errorf("%s: MayGrant(%d,%v,%d,%d)=%v, want %v", c.name, c.callerRole, c.reshare, c.targetCurrent, c.grant, got, c.want) + } + } +} + +// TestInviteBinding round-trips an invite and confirms a plain token has none. +func TestInviteBinding(t *testing.T) { + db := open(t) + if err := db.CreateInvite("h1", 1000, Invite{Principal: "bob", Share: "proj", Role: RoleEditor, CanReshare: true}); err != nil { + t.Fatal(err) + } + inv, ok, err := db.InviteBinding("h1") + if err != nil || !ok { + t.Fatalf("InviteBinding = %v, %v", ok, err) + } + if inv.Principal != "bob" || inv.Share != "proj" || inv.Role != RoleEditor || !inv.CanReshare { + t.Fatalf("binding = %+v", inv) + } + // The invite token is redeemable like any join token. + if redeemed, _ := db.RedeemToken("h1", 500); !redeemed { + t.Fatal("invite token should redeem via the normal token path") + } + // A plain token has no binding. + if err := db.CreateToken("plain", 1000); err != nil { + t.Fatal(err) + } + if _, ok, _ := db.InviteBinding("plain"); ok { + t.Fatal("a plain join token must have no invite binding") + } +} + // TestMigrationFromV1WithData is the realistic upgrade path: a populated v1 // database (user_version 0, global snapshot PK) is migrated in place. Data must // survive, a backup must be written, and the v1 idempotent-push legacy — a share diff --git a/internal/hub/server.go b/internal/hub/server.go index 9551cbe..0e336ce 100644 --- a/internal/hub/server.go +++ b/internal/hub/server.go @@ -70,6 +70,7 @@ func (s *Server) Handler() http.Handler { mux.HandleFunc("GET "+proto.PathHead, s.auth(s.handleHead)) mux.HandleFunc("GET "+proto.PathLog, s.auth(s.handleLog)) mux.HandleFunc("GET "+proto.PathMembers, s.auth(s.handleMembers)) + mux.HandleFunc("POST "+proto.PathInvite, s.auth(s.handleInvite)) mux.HandleFunc("GET "+proto.PathEvents, s.auth(s.handleEvents)) mux.HandleFunc("GET "+proto.PathMetrics, s.handleMetrics) return mux @@ -138,9 +139,96 @@ func (s *Server) handleJoin(w http.ResponseWriter, r *http.Request) { writeErr(w, http.StatusInternalServerError, err.Error()) return } + // If this was an invite token (M8a), apply its binding: the device joins as the + // bound principal with the bound role on the share. The grant was already + // attenuation-checked when the invite was minted (handleInvite). A plain join + // token has no binding → v1 behavior (device stays principal 'owner'). + if inv, ok, err := s.db.InviteBinding(HashToken(req.Token)); err != nil { + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } else if ok { + if err := s.db.SetDevicePrincipal(deviceID, inv.Principal); err != nil { + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + if err := s.db.SetMember(inv.Share, inv.Principal, inv.Role, inv.CanReshare); err != nil { + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + } writeJSON(w, http.StatusOK, proto.JoinResponse{DeviceID: deviceID, Bearer: bearer}) } +// handleInvite mints an invite token for a share (M8a). The caller's effective +// role + reshare bit must permit the requested grant (attenuation, enforced here +// server-side so a compromised client can't escalate). On a legacy share the +// caller is an implicit owner: minting an invite seeds the caller's own principal +// as owner and flips the share to explicit, so the caller never locks themselves +// (or their other devices, same principal) out. +func (s *Server) handleInvite(w http.ResponseWriter, r *http.Request, deviceID string) { + var req proto.InviteRequest + if !decode(w, r, &req) { + return + } + grantRole, ok := meta.ParseRole(req.Role) + if !ok { + writeErr(w, http.StatusBadRequest, "unknown role "+req.Role) + return + } + if req.Principal == "" { + writeErr(w, http.StatusBadRequest, "missing principal") + return + } + + // Serialize with publish so the legacy→explicit flip + self-seed is atomic + // against a concurrent first grant. + s.publishMu.Lock() + defer s.publishMu.Unlock() + + callerRole, callerReshare, explicit, err := s.db.EffectiveMember(deviceID, req.Share) + if err != nil { + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + targetCurrent, err := s.db.RoleOf(req.Share, req.Principal) + if err != nil { + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + if !meta.MayGrant(callerRole, callerReshare, targetCurrent, grantRole) { + writeErr(w, http.StatusForbidden, "your role may not grant this") + return + } + // Preserve the caller's access across the legacy→explicit flip: seed the + // caller's principal as owner before the share stops being open. + if !explicit { + callerPrincipal, err := s.db.DevicePrincipal(deviceID) + if err != nil { + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + if err := s.db.SetMember(req.Share, callerPrincipal, meta.RoleOwner, true); err != nil { + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + } + if err := s.db.EnsurePrincipal(req.Principal, req.Principal, time.Now().Unix()); err != nil { + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + tok, err := randomBearer() + if err != nil { + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + inv := meta.Invite{Principal: req.Principal, Share: req.Share, Role: grantRole, CanReshare: req.Reshare} + if err := s.db.CreateInvite(HashToken(tok), time.Now().Add(24*time.Hour).Unix(), inv); err != nil { + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + writeJSON(w, http.StatusOK, proto.InviteResponse{Token: tok}) +} + func (s *Server) handlePublish(w http.ResponseWriter, r *http.Request, deviceID string) { var req proto.PublishRequest if !decode(w, r, &req) { diff --git a/internal/hub/server_test.go b/internal/hub/server_test.go index ef366f5..e8cfd8c 100644 --- a/internal/hub/server_test.go +++ b/internal/hub/server_test.go @@ -272,6 +272,82 @@ func TestPushWriteGate(t *testing.T) { } } +// joinWith enrolls a fresh device using token and returns its JoinResponse. +func joinWith(t *testing.T, base, token string) proto.JoinResponse { + t.Helper() + pub, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + st, body := do(t, "POST", base+proto.PathJoin, "", mustJSON(t, proto.JoinRequest{ + Token: token, Name: "dev", Pubkey: pub, + Signature: ed25519.Sign(priv, proto.JoinChallenge(token, pub)), + })) + if st != http.StatusOK { + t.Fatalf("join status = %d, body = %s", st, body) + } + var j proto.JoinResponse + if err := json.Unmarshal(body, &j); err != nil { + t.Fatal(err) + } + return j +} + +// TestInviteFlow is the M8a device-facing invite security contract: an owner +// invites a collaborator, who joins via the invite token and lands with the bound +// role; the legacy→explicit flip preserves the owner's access; and attenuation is +// enforced (an editor without +s can't invite). +func TestInviteFlow(t *testing.T) { + base, db := testHub(t) + now := time.Now().Unix() + + // Owner device joins a legacy share and publishes it. + if err := db.CreateToken(HashToken("owntok"), now+3600); err != nil { + t.Fatal(err) + } + owner := joinWith(t, base, "owntok") + if st, _ := do(t, "POST", base+proto.PathPublish, owner.Bearer, mustJSON(t, proto.PublishRequest{Share: "proj"})); st != http.StatusOK { + t.Fatal("publish failed") + } + + // Owner invites principal "bob" as editor. + st, body := do(t, "POST", base+proto.PathInvite, owner.Bearer, mustJSON(t, proto.InviteRequest{ + Share: "proj", Principal: "bob", Role: "editor", + })) + if st != http.StatusOK { + t.Fatalf("invite status = %d, body = %s", st, body) + } + var invResp proto.InviteResponse + if err := json.Unmarshal(body, &invResp); err != nil { + t.Fatal(err) + } + + // The share flipped to explicit but the OWNER kept access (self-seed). + if mode, _ := db.ACLMode("proj"); mode != "explicit" { + t.Fatalf("share should be explicit after invite, got %q", mode) + } + bogus := mustJSON(t, proto.PushRequest{Share: "proj", ManifestHash: strings.Repeat("a", 64)}) + if st, _ := do(t, "POST", base+proto.PathPush, owner.Bearer, bogus); st == http.StatusForbidden { + t.Fatal("owner must keep write access across the legacy→explicit flip") + } + + // Bob's device redeems the invite → enrolled as principal bob with editor. + bob := joinWith(t, base, invResp.Token) + if pid, _ := db.DevicePrincipal(bob.DeviceID); pid != "bob" { + t.Fatalf("invited device principal = %q, want bob", pid) + } + if st, _ := do(t, "POST", base+proto.PathPush, bob.Bearer, bogus); st == http.StatusForbidden { + t.Fatal("invited editor must pass the write gate") + } + + // Attenuation: bob (editor, NO +s) cannot invite anyone. + if st, _ := do(t, "POST", base+proto.PathInvite, bob.Bearer, mustJSON(t, proto.InviteRequest{ + Share: "proj", Principal: "carol", Role: "viewer", + })); st != http.StatusForbidden { + t.Fatalf("editor without +s must not invite, got %d", st) + } +} + // TestHandleMembers covers GET /v1/members: a fresh share reads as legacy, and // after a grant it lists the member with the role name and reshare bit. func TestHandleMembers(t *testing.T) { diff --git a/internal/transport/client.go b/internal/transport/client.go index e8b8d6e..df710f0 100644 --- a/internal/transport/client.go +++ b/internal/transport/client.go @@ -183,6 +183,15 @@ func (c *Client) Members(share string) (proto.MembersResponse, error) { return resp, err } +// Invite mints an invite token binding (principal, share, role) — the invitee +// redeems it with `devbox join`. reshare grants the +s delegation bit. +func (c *Client) Invite(share, principal, role string, reshare bool) (string, error) { + var resp proto.InviteResponse + req := proto.InviteRequest{Share: share, Principal: principal, Role: role, Reshare: reshare} + err := c.do(http.MethodPost, proto.PathInvite, true, req, &resp) + return resp.Token, err +} + // do sends a JSON request (nil body for GET) and decodes a JSON response into // out (nil out discards the body). It sets the bearer header when auth is true. func (c *Client) do(method, path string, auth bool, body, out any) error { diff --git a/pkg/proto/proto.go b/pkg/proto/proto.go index f739895..d554604 100644 --- a/pkg/proto/proto.go +++ b/pkg/proto/proto.go @@ -14,9 +14,25 @@ const ( PathLog = "/v1/log" // GET ?share=, auth: snapshot history PathEvents = "/v1/events" // GET ?share=, auth: SSE stream of change events PathMembers = "/v1/members" // GET ?share=, auth: who can access a share (M8a) + PathInvite = "/v1/invite" // POST, auth: mint an invite token for a share (M8a) PathMetrics = "/metrics" // GET, no auth: Prometheus text exposition ) +// InviteRequest asks the hub to mint an invite: a join token that, when redeemed, +// binds the joining device to Principal with Role on Share. The caller must hold a +// role that permits the grant (server-side attenuation); +s lets an editor delegate. +type InviteRequest struct { + Share string `json:"share"` + Principal string `json:"principal"` + Role string `json:"role"` // viewer|editor|admin|owner + Reshare bool `json:"reshare"` // grant the +s delegation bit +} + +// InviteResponse returns the raw invite token; the invitee runs `devbox join`. +type InviteResponse struct { + Token string `json:"token"` +} + // SnapshotInfo is one entry in a share's history. type SnapshotInfo struct { ID string `json:"id"`