From f8135b9d07ab122fd716dc501f7a58889c7c5623 Mon Sep 17 00:00:00 2001 From: shoemoney Date: Tue, 23 Jun 2026 20:27:12 -0500 Subject: [PATCH] =?UTF-8?q?feat(M8a):=20adversarial=20auth=20audit=20?= =?UTF-8?q?=E2=80=94=20close=20+s=20escalation=20+=20add=20invite=20revoca?= =?UTF-8?q?tion=20=F0=9F=9B=A1=EF=B8=8F?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit P2 adversarial audit (6 finders + skeptic verification, 13 agents). Two real findings fixed with regression tests; rest documented as single-owner residuals. - FIX (+s attenuation): MayGrant never constrained the GRANTED reshare bit, so an invite could confer +s the caller didn't hold (req.Reshare copied verbatim). MayGrant now takes grantReshare and rejects conferring +s you don't hold (owners unconstrained) β€” attenuation is total over role + target + reshare. - FIX (invite revocation): invites were unrevocable 24h bearer capabilities β€” no way to kill a leaked/regretted one. Added meta.RevokeInvite (token+binding in one tx), POST /v1/invite/revoke (only a caller who could mint it may revoke), and 'devbox invite revoke '. - Tests: TestMayGrant (+5 +s cases), TestInviteCannotGrantReshareCallerLacks, TestInviteRevoke. go test ./... -race clean (18 pkgs). - docs/M8a-audit.md: findings, confirmed defenses, accepted residuals. Confirmed-defended under attack: single-use redeem (atomic CAS), role bounding, revoke-at-auth (revoked=0 in bearer+role lookups), cross-share binding, PoP. --- cmd/devbox/main.go | 25 +++++++ docs/M8a-audit.md | 124 +++++++++++++++++++++++++++++++++ internal/hub/audit_test.go | 119 +++++++++++++++++++++++++++++++ internal/hub/meta/meta.go | 37 ++++++++-- internal/hub/meta/meta_test.go | 43 +++++++----- internal/hub/server.go | 43 +++++++++++- internal/transport/client.go | 5 ++ pkg/proto/proto.go | 34 ++++++--- 8 files changed, 396 insertions(+), 34 deletions(-) create mode 100644 docs/M8a-audit.md create mode 100644 internal/hub/audit_test.go diff --git a/cmd/devbox/main.go b/cmd/devbox/main.go index d41474b..d2ba068 100644 --- a/cmd/devbox/main.go +++ b/cmd/devbox/main.go @@ -349,6 +349,31 @@ func inviteCmd() *cobra.Command { }, } cmd.Flags().BoolVar(&reshare, "reshare", false, "grant the +s bit (lets them delegate)") + cmd.AddCommand(&cobra.Command{ + Use: "revoke ", + Short: "πŸ—‘οΈ revoke a pending invite token before it's redeemed", + Args: cobra.ExactArgs(1), + 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) + if err := c.RevokeInvite(args[0]); err != nil { + return err + } + fmt.Fprintln(cmd.OutOrStdout(), "πŸ—‘οΈ invite revoked β€” it can no longer be redeemed") + return nil + }, + }) return cmd } diff --git a/docs/M8a-audit.md b/docs/M8a-audit.md new file mode 100644 index 0000000..48c715e --- /dev/null +++ b/docs/M8a-audit.md @@ -0,0 +1,124 @@ + +
+ +# πŸ›‘οΈ M8a Auth β€” Adversarial Security Audit + +![scope](https://img.shields.io/badge/scope-teams%20%C2%B7%20invites%20%C2%B7%20attenuation%20%C2%B7%20write--gate-blueviolet?style=for-the-badge) +![method](https://img.shields.io/badge/method-%F0%9F%A4%96%2013%20parallel%20agents-ff3df0?style=for-the-badge) +![found](https://img.shields.io/badge/fixed-2%20findings%20%2B%20regression%20tests-success?style=for-the-badge) +![race](https://img.shields.io/badge/go%20test-%2Drace%20clean-success?style=for-the-badge) + +*The M7.5 treatment for v2's new privilege surface β€” before anyone relies on it for multi-owner shares.* + +
+ +> **Date:** 2026-06-23 Β· **Method:** 6 parallel adversarial finders (one per attack class) + a +> per-finding skeptic verification pass + a full manual read of the auth path. **13 agents**, +> 5 candidate findings confirmed by the verifiers, then triaged by severity & exploitability: +> **2 fixed** with regression tests, **3 documented** as accepted residuals of the single-owner +> trust model. The auth core held up well β€” 20 distinct defenses were positively confirmed. + +--- + +## 🎯 Threat model + +devbox's hub is **single-owner-first**: you self-host it on hardware you control, so the hub is +trusted. M8a adds **multi-principal shares**, so the new attack surface is **a malicious _client_** +trying to exceed its granted role. Every privilege decision is therefore re-checked **server-side**; +the client is never trusted for its own role. + +```mermaid +flowchart LR + J["POST /v1/join
token + PoP"] -->|RedeemToken CAS| BIND["apply server-side
invite binding"] + INV["POST /invite
(authed device)"] -->|EffectiveMember
+ MayGrant +s| MINT["mint invite
(attenuated)"] + REV["POST /invite/revoke
(authed device)"] -->|MayGrant authority| KILL["delete token
+ binding"] + PUSH["POST /push
(authed device)"] -->|Writable + roleβ‰₯editor
scoped to share| WRITE["accept snapshot"] + style J fill:#1e3a5a,stroke:#4F9CF9,color:#fff + style INV fill:#5a4a1e,stroke:#ffd43b,color:#fff + style REV fill:#5a1e2e,stroke:#ff6b6b,color:#fff + style PUSH fill:#1e5a2e,stroke:#51cf66,color:#fff +``` + +--- + +## πŸ”¬ Findings + +| # | Class | Verdict | Disposition | +|---|---|---|---| +| 1 | Invite is an unrevocable bearer capability | 🟠 real (med) | **FIXED** β€” added `/v1/invite/revoke` | +| 2 | Invite could confer `+s` the caller lacks | 🟠 real (attenuation gap) | **FIXED** β€” `MayGrant` now attenuates `+s` | +| 3 | Push gate read not in the snapshot write's lock | 🟑 low | accepted residual | +| 4 | SSE stream not torn down on revocation | 🟑 low | accepted residual | +| 5 | Invite token = bound-principal bearer (theft = takeover) | 🟑 inherent | mitigated by #1 + TLS | +| β€” | Single-use redeem, role bounding, revoke-at-auth, cross-share binding, PoP | βœ… defended | 20 defenses confirmed | +| β€” | "non-transactional join orchestration" | βšͺ refuted | crash-window only, no privilege effect | + +### πŸ› οΈ FIXED #2 β€” `+s` (reshare) attenuation gap +`MayGrant` validated the granted **role** and the target, but **never the granted `+s` bit** β€” +`handleInvite` copied `req.Reshare` (the client `--reshare` flag) straight into the binding. Not a +live escalation today (a granter always out-ranks the grantee, so the grantee never exceeds the +granter), but the `+s` dimension was **unattenuated** and would become a real hole if the role +hierarchy ever changed. **Fix:** `MayGrant(..., grantReshare bool)` now rejects conferring `+s` +unless the caller holds it (owners unconstrained) β€” attenuation is total over all three dimensions. +*Tests:* `TestMayGrant` (+5 cases) Β· `TestInviteCannotGrantReshareCallerLacks` (HTTP). + +### πŸ› οΈ FIXED #1 & #5 β€” invites were unrevocable bearer capabilities +An invite is a 24h single-use token that binds a **specific principal+role**. There was **no way to +kill one** β€” a leaked or regretted invite (or one minted before the inviter was demoted) stayed +redeemable for its whole TTL, and whoever held the string could claim that principal's role. +**Fix:** added `meta.RevokeInvite` (deletes token+binding in one tx) + `POST /v1/invite/revoke` + +`devbox invite revoke `. Only a caller who could have **minted** it (same `MayGrant` +authority on the bound share) may revoke it. *Test:* `TestInviteRevoke` (revoke β†’ redeem fails; +re-revoke is a no-op; a viewer can't revoke an editor invite, and the invite survives that attempt). + +### βœ… Confirmed defenses (held under attack) +- **Single-use redeem:** `RedeemToken` is an atomic compare-and-set (`UPDATE … SET used=1 WHERE used=0 AND not-expired`); sequential **and** concurrent double-redeem both fail. PoP is checked *before* redeem, so a bad request can't burn a token. +- **Role bounding:** caller role/`+s` are server-derived (`EffectiveMember`), never from the request; you can't grant above your own role or touch a principal who out-ranks you. +- **Revocation at auth:** `DeviceByBearer` **and** `EffectiveMember` filter `revoked=0`, so a revoked device is denied on the **next request** β€” no cached credential survives. +- **Cross-share:** redemption binds share/principal/role from the **server-side binding**, never the joiner's request body; an A-invite can't confer B-rights. Write-gate is scoped to `req.Share`. +- **Write-gate:** `!writable || role < RoleEditor β†’ 403`, deny-by-default on explicit shares. + +--- + +## 🧭 Accepted residuals (single-owner threat model β€” by design) + +Not bugs β€” documented edges of the current trust model, deferred until a concrete consumer appears: + +- **#3 Push micro-TOCTOU:** the write-gate's role read isn't in the same lock as the snapshot write, + so a write started a microsecond before a concurrent legacyβ†’explicit flip could still land. + Accepted: the actor *had* access an instant earlier, and serializing every push to close a Β΅s + window isn't worth the throughput. Revocation is eventual on the next request regardless. +- **#4 SSE revocation lag:** a revoked device keeps receiving share-*change notifications* (not data) + on an already-open event stream until it disconnects. Tied to the **M9 read-side-ACL** deferral β€” + reads aren't role-gated yet (single-owner trust). Writes **are** closed immediately. +- **Read-side ACL (M9):** `handleHead`/`handleLog`/`handleGetBlob`/`handleMembers` don't gate reads + by role. Deferred until a genuinely untrusted multi-owner share exists. +- **Legacy multi-principal lockout:** the first invite on a legacy share seeds only the *caller's* + principal as owner; other distinct principals on that legacy share lose access on the flip. + Acceptable under the single-owner assumption a legacy share carries. +- **Invite theft within TTL (#5):** invites are bearer secrets (like any invite link); TLS to the + hub + the new revoke primitive + the 24h TTL bound the exposure. A network MITM of the join + request is out of scope (TLS assumed). + +--- + +## πŸ§ͺ Regression coverage + +| Invariant | Test | State | +|---|---|---| +| `+s` can't be conferred by a caller who lacks it | `TestMayGrant`, `TestInviteCannotGrantReshareCallerLacks` | πŸ†• fails pre-fix | +| pending invite is revocable; only by an authorized caller | `TestInviteRevoke` | πŸ†• fails pre-fix | +| redeemed invite token can't be reused | `TestTokenRedeemOnce` | βœ… pre-existing | +| caller can't grant above their role / demote a superior | `TestMayGrant` | βœ… pre-existing | +| write-gate denies viewers/unmembered/revoked | `TestPushWriteGate` | βœ… pre-existing | +| join requires proof-of-possession | `TestJoinRequiresProofOfPossession` | βœ… pre-existing | + +All green, `go test ./... -race` clean (18 packages). + +--- + +
+ +*Six finders, thirteen agents, two real holes closed β€” the write-gate held the whole time. πŸ›‘οΈ* + +
diff --git a/internal/hub/audit_test.go b/internal/hub/audit_test.go new file mode 100644 index 0000000..7c2d4dd --- /dev/null +++ b/internal/hub/audit_test.go @@ -0,0 +1,119 @@ +package hub + +// P2 adversarial-audit regression tests. Each pins a fix for a confirmed M8a +// finding so a future refactor can't silently reopen it. See docs/M8a-audit.md. + +import ( + "crypto/ed25519" + "crypto/rand" + "encoding/json" + "net/http" + "testing" + "time" + + "github.com/shoemoney/devbox/pkg/proto" +) + +// mintInvite asks the hub to mint an invite and returns its raw token. +func mintInvite(t *testing.T, base, bearer string, req proto.InviteRequest) (int, string) { + t.Helper() + st, body := do(t, "POST", base+proto.PathInvite, bearer, mustJSON(t, req)) + if st != http.StatusOK { + return st, "" + } + var resp proto.InviteResponse + if err := json.Unmarshal(body, &resp); err != nil { + t.Fatal(err) + } + return st, resp.Token +} + +// tryJoin redeems token with a fresh keypair and returns the HTTP status. +func tryJoin(t *testing.T, base, token string) int { + t.Helper() + pub, priv, err := ed25519.GenerateKey(rand.Reader) + if err != nil { + t.Fatal(err) + } + st, _ := do(t, "POST", base+proto.PathJoin, "", mustJSON(t, proto.JoinRequest{ + Token: token, Name: "dev", Pubkey: pub, + Signature: ed25519.Sign(priv, proto.JoinChallenge(token, pub)), + })) + return st +} + +// Finding #2 (privesc): an invite must not confer the +s reshare bit the caller +// doesn't hold. An admin WITHOUT +s could previously mint an invite WITH +s. +func TestInviteCannotGrantReshareCallerLacks(t *testing.T) { + base, db := testHub(t) + now := time.Now().Unix() + if err := db.CreateToken(HashToken("own"), now+3600); err != nil { + t.Fatal(err) + } + owner := joinWith(t, base, "own") + if st, _ := do(t, "POST", base+proto.PathPublish, owner.Bearer, mustJSON(t, proto.PublishRequest{Share: "proj"})); st != http.StatusOK { + t.Fatal("publish failed") + } + + // Owner grants principal "adm" admin, explicitly WITHOUT +s. + if st, _ := mintInvite(t, base, owner.Bearer, proto.InviteRequest{Share: "proj", Principal: "adm", Role: "admin", Reshare: false}); st != http.StatusOK { + t.Fatalf("owner→admin invite status=%d", st) + } + // adm's device redeems and is enrolled as admin (no +s). + _, admTok := mintInvite(t, base, owner.Bearer, proto.InviteRequest{Share: "proj", Principal: "adm2", Role: "admin", Reshare: false}) + adm := joinWith(t, base, admTok) + + // adm (admin, no +s) tries to confer +s → must be denied (the fix). + if st, _ := mintInvite(t, base, adm.Bearer, proto.InviteRequest{Share: "proj", Principal: "carol", Role: "editor", Reshare: true}); st != http.StatusForbidden { + t.Fatalf("admin without +s must NOT confer +s, got %d (escalation reopened)", st) + } + // Sanity: adm CAN still grant the same role without +s (admins may grant). + if st, _ := mintInvite(t, base, adm.Bearer, proto.InviteRequest{Share: "proj", Principal: "dave", Role: "editor", Reshare: false}); st != http.StatusOK { + t.Fatalf("admin must still grant a non-resharing editor, got %d", st) + } + // Owner is unconstrained on +s (top of the hierarchy). + if st, _ := mintInvite(t, base, owner.Bearer, proto.InviteRequest{Share: "proj", Principal: "erin", Role: "editor", Reshare: true}); st != http.StatusOK { + t.Fatalf("owner must be able to confer +s, got %d", st) + } +} + +// Finding #1/#5 (replay/pop): a pending invite must be revocable so a leaked or +// regretted invite can be killed before its TTL — and only by someone who could +// have minted it. +func TestInviteRevoke(t *testing.T) { + base, db := testHub(t) + now := time.Now().Unix() + if err := db.CreateToken(HashToken("own"), now+3600); err != nil { + t.Fatal(err) + } + owner := joinWith(t, base, "own") + if st, _ := do(t, "POST", base+proto.PathPublish, owner.Bearer, mustJSON(t, proto.PublishRequest{Share: "proj"})); st != http.StatusOK { + t.Fatal("publish failed") + } + + // Mint an invite, then revoke it; the token must no longer redeem. + _, tok := mintInvite(t, base, owner.Bearer, proto.InviteRequest{Share: "proj", Principal: "bob", Role: "editor"}) + st, body := do(t, "POST", base+proto.PathInviteRevoke, owner.Bearer, mustJSON(t, proto.InviteRevokeRequest{Token: tok})) + if st != http.StatusOK { + t.Fatalf("revoke status=%d body=%s", st, body) + } + if got := tryJoin(t, base, tok); got != http.StatusUnauthorized { + t.Fatalf("revoked invite must not redeem, got %d", got) + } + // Revoking again is a no-op conflict/not-found (binding already gone). + if st, _ := do(t, "POST", base+proto.PathInviteRevoke, owner.Bearer, mustJSON(t, proto.InviteRevokeRequest{Token: tok})); st == http.StatusOK { + t.Fatal("re-revoking a killed invite must not report success") + } + + // Authority: a mere viewer cannot revoke an editor invite. + _, vtok := mintInvite(t, base, owner.Bearer, proto.InviteRequest{Share: "proj", Principal: "val", Role: "viewer"}) + viewer := joinWith(t, base, vtok) + _, target := mintInvite(t, base, owner.Bearer, proto.InviteRequest{Share: "proj", Principal: "wanda", Role: "editor"}) + if st, _ := do(t, "POST", base+proto.PathInviteRevoke, viewer.Bearer, mustJSON(t, proto.InviteRevokeRequest{Token: target})); st != http.StatusForbidden { + t.Fatalf("viewer must not revoke an editor invite, got %d", st) + } + // And that target invite still redeems (was not killed by the failed attempt). + if got := tryJoin(t, base, target); got != http.StatusOK { + t.Fatalf("invite must survive an unauthorized revoke attempt, got %d", got) + } +} diff --git a/internal/hub/meta/meta.go b/internal/hub/meta/meta.go index 3ffafbe..738efef 100644 --- a/internal/hub/meta/meta.go +++ b/internal/hub/meta/meta.go @@ -445,13 +445,16 @@ func (d *DB) RoleOf(share, principalID string) (int, error) { } // 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. +// principal currently at targetCurrentRole to grantRole, optionally conferring the +// +s reshare bit (grantReshare). 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 { +// - you can never touch a principal who currently outranks you (no demoting up); +// - you can only confer +s if you hold it yourself (owners are unconstrained) — +// the reshare bit is a delegation power, so it attenuates like the role does. +func MayGrant(callerRole int, callerCanReshare bool, targetCurrentRole, grantRole int, grantReshare bool) bool { if grantRole < RoleViewer || grantRole > RoleOwner { return false } @@ -461,6 +464,9 @@ func MayGrant(callerRole int, callerCanReshare bool, targetCurrentRole, grantRol if callerRole < RoleAdmin && !callerCanReshare { return false } + if grantReshare && !callerCanReshare && callerRole < RoleOwner { + return false + } return grantRole <= callerRole && targetCurrentRole <= callerRole } @@ -511,6 +517,29 @@ func (d *DB) InviteBinding(tokenHash string) (inv Invite, ok bool, err error) { return inv, true, nil } +// RevokeInvite kills a still-pending invite: it removes the redeemable token and +// its binding so /v1/join can no longer accept it — the missing primitive for a +// leaked or regretted invite within its TTL. Returns false if nothing was killed +// (already redeemed, already revoked, or never existed). One transaction. +func (d *DB) RevokeInvite(tokenHash string) (bool, error) { + tx, err := d.sql.Begin() + if err != nil { + return false, err + } + defer tx.Rollback() + res, err := tx.Exec(`DELETE FROM tokens WHERE hash=? AND used=0`, tokenHash) + if err != nil { + return false, err + } + if n, _ := res.RowsAffected(); n == 0 { + return false, nil // already redeemed/revoked/unknown — nothing to kill + } + if _, err := tx.Exec(`DELETE FROM invites WHERE token_hash=?`, tokenHash); err != nil { + return false, err + } + return true, tx.Commit() +} + // EnsurePrincipal creates a principal if absent (idempotent). func (d *DB) EnsurePrincipal(id, name string, createdAt int64) error { _, err := d.sql.Exec( diff --git a/internal/hub/meta/meta_test.go b/internal/hub/meta/meta_test.go index 77a24bd..c04066c 100644 --- a/internal/hub/meta/meta_test.go +++ b/internal/hub/meta/meta_test.go @@ -464,27 +464,34 @@ func TestRolesLegacyAndExplicit(t *testing.T) { // 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 + name string + callerRole int + reshare bool + targetCurrent, grant int + grantReshare bool + 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}, + {"owner grants editor", RoleOwner, false, 0, RoleEditor, false, true}, + {"owner grants owner (co-owner)", RoleOwner, false, 0, RoleOwner, false, true}, + {"admin grants admin", RoleAdmin, false, 0, RoleAdmin, false, true}, + {"admin can't grant owner (above self)", RoleAdmin, false, 0, RoleOwner, false, false}, + {"editor with +s grants editor", RoleEditor, true, 0, RoleEditor, false, true}, + {"editor with +s can't grant admin", RoleEditor, true, 0, RoleAdmin, false, false}, + {"editor WITHOUT +s can't grant", RoleEditor, false, 0, RoleViewer, false, false}, + {"viewer can't grant", RoleViewer, true, 0, RoleViewer, false, false}, + {"can't demote a superior owner", RoleEditor, true, RoleOwner, RoleViewer, false, false}, + {"invalid role rejected", RoleOwner, false, 0, 999, false, false}, + {"zero role (unmembered) can't grant", 0, false, 0, RoleViewer, false, false}, + // +s (reshare) attenuation: you can only confer the delegation bit you hold. + {"editor+s confers +s", RoleEditor, true, 0, RoleEditor, true, true}, + {"admin WITHOUT +s can't confer +s", RoleAdmin, false, 0, RoleEditor, true, false}, + {"admin WITH +s confers +s", RoleAdmin, true, 0, RoleEditor, true, true}, + {"owner confers +s unconstrained", RoleOwner, false, 0, RoleEditor, true, true}, + {"editor+s confers +s but role still bounds (no admin)", RoleEditor, true, 0, RoleAdmin, true, 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) + if got := MayGrant(c.callerRole, c.reshare, c.targetCurrent, c.grant, c.grantReshare); got != c.want { + t.Errorf("%s: MayGrant(%d,%v,%d,%d,%v)=%v, want %v", c.name, c.callerRole, c.reshare, c.targetCurrent, c.grant, c.grantReshare, got, c.want) } } } diff --git a/internal/hub/server.go b/internal/hub/server.go index 15b5be8..94ca40a 100644 --- a/internal/hub/server.go +++ b/internal/hub/server.go @@ -68,6 +68,7 @@ func (s *Server) Handler() http.Handler { mux := http.NewServeMux() mux.HandleFunc("POST "+proto.PathJoin, s.handleJoin) mux.HandleFunc("POST "+proto.PathPublish, s.auth(s.handlePublish)) + mux.HandleFunc("POST "+proto.PathInviteRevoke, s.auth(s.handleInviteRevoke)) mux.HandleFunc("POST "+proto.PathHave, s.auth(s.handleHave)) mux.HandleFunc("PUT "+proto.PathBlob+"{hash}", s.auth(s.handleBlob)) mux.HandleFunc("GET "+proto.PathBlob+"{hash}", s.auth(s.handleGetBlob)) @@ -209,7 +210,7 @@ func (s *Server) handleInvite(w http.ResponseWriter, r *http.Request, deviceID s writeErr(w, http.StatusInternalServerError, err.Error()) return } - if !meta.MayGrant(callerRole, callerReshare, targetCurrent, grantRole) { + if !meta.MayGrant(callerRole, callerReshare, targetCurrent, grantRole, req.Reshare) { writeErr(w, http.StatusForbidden, "your role may not grant this") return } @@ -243,6 +244,46 @@ func (s *Server) handleInvite(w http.ResponseWriter, r *http.Request, deviceID s writeJSON(w, http.StatusOK, proto.InviteResponse{Token: tok}) } +// handleInviteRevoke kills a still-pending invite by its raw token. Only a caller +// who could have MINTED it (same MayGrant authority on the bound share) may revoke +// it — so an invite can't be cancelled by someone who couldn't have issued it, and +// the binding isn't probeable by the unauthorized. +func (s *Server) handleInviteRevoke(w http.ResponseWriter, r *http.Request, deviceID string) { + var req proto.InviteRevokeRequest + if !decode(w, r, &req) { + return + } + hash := HashToken(req.Token) + inv, ok, err := s.db.InviteBinding(hash) + if err != nil { + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + if !ok { + writeErr(w, http.StatusNotFound, "no such invite") + return + } + callerRole, callerReshare, _, err := s.db.EffectiveMember(deviceID, inv.Share) + if err != nil { + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + if !meta.MayGrant(callerRole, callerReshare, 0, inv.Role, inv.CanReshare) { + writeErr(w, http.StatusForbidden, "your role may not revoke this invite") + return + } + killed, err := s.db.RevokeInvite(hash) + if err != nil { + writeErr(w, http.StatusInternalServerError, err.Error()) + return + } + if !killed { + writeErr(w, http.StatusConflict, "invite already redeemed or revoked") + return + } + writeJSON(w, http.StatusOK, proto.InviteRevokeResponse{Revoked: true}) +} + 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/transport/client.go b/internal/transport/client.go index 3d81aae..67d54c7 100644 --- a/internal/transport/client.go +++ b/internal/transport/client.go @@ -192,6 +192,11 @@ func (c *Client) Invite(share, principal, role string, reshare bool) (string, er return resp.Token, err } +// RevokeInvite kills a still-pending invite token before it's redeemed. +func (c *Client) RevokeInvite(token string) error { + return c.do(http.MethodPost, proto.PathInviteRevoke, true, proto.InviteRevokeRequest{Token: token}, nil) +} + // 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 d554604..643f39a 100644 --- a/pkg/proto/proto.go +++ b/pkg/proto/proto.go @@ -5,17 +5,18 @@ package proto // Endpoint paths (all under the hub base URL). const ( - PathJoin = "/v1/join" // POST, no auth: redeem a join token, enroll a device - PathPublish = "/v1/publish" // POST, auth: create a share - PathHave = "/v1/have" // POST, auth: which chunk hashes is the hub missing? - PathBlob = "/v1/blob/" // PUT /v1/blob/{hash}, auth: upload one blob's bytes - PathPush = "/v1/push" // POST, auth: commit a snapshot - PathHead = "/v1/head" // GET ?share=, auth: current head snapshot id - 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 + PathJoin = "/v1/join" // POST, no auth: redeem a join token, enroll a device + PathPublish = "/v1/publish" // POST, auth: create a share + PathHave = "/v1/have" // POST, auth: which chunk hashes is the hub missing? + PathBlob = "/v1/blob/" // PUT /v1/blob/{hash}, auth: upload one blob's bytes + PathPush = "/v1/push" // POST, auth: commit a snapshot + PathHead = "/v1/head" // GET ?share=, auth: current head snapshot id + 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) + PathInviteRevoke = "/v1/invite/revoke" // POST, auth: kill a pending invite token (M8a) + PathMetrics = "/metrics" // GET, no auth: Prometheus text exposition ) // InviteRequest asks the hub to mint an invite: a join token that, when redeemed, @@ -33,6 +34,17 @@ type InviteResponse struct { Token string `json:"token"` } +// InviteRevokeRequest kills a still-pending invite by its raw token, so a leaked +// or regretted invite can be cancelled before it's redeemed (within its TTL). +type InviteRevokeRequest struct { + Token string `json:"token"` +} + +// InviteRevokeResponse reports whether a pending invite was actually killed. +type InviteRevokeResponse struct { + Revoked bool `json:"revoked"` +} + // SnapshotInfo is one entry in a share's history. type SnapshotInfo struct { ID string `json:"id"`