feat(M8a): adversarial auth audit — close +s escalation + add invite revocation 🛡️
Some checks are pending
CI / vet-build-test (push) Waiting to run
Some checks are pending
CI / vet-build-test (push) Waiting to run
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 <token>'. - 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.
This commit is contained in:
parent
060e147112
commit
f8135b9d07
8 changed files with 396 additions and 34 deletions
|
|
@ -349,6 +349,31 @@ func inviteCmd() *cobra.Command {
|
||||||
},
|
},
|
||||||
}
|
}
|
||||||
cmd.Flags().BoolVar(&reshare, "reshare", false, "grant the +s bit (lets them delegate)")
|
cmd.Flags().BoolVar(&reshare, "reshare", false, "grant the +s bit (lets them delegate)")
|
||||||
|
cmd.AddCommand(&cobra.Command{
|
||||||
|
Use: "revoke <token>",
|
||||||
|
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 <hub> <token>")
|
||||||
|
}
|
||||||
|
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
|
return cmd
|
||||||
}
|
}
|
||||||
|
|
||||||
|
|
|
||||||
124
docs/M8a-audit.md
Normal file
124
docs/M8a-audit.md
Normal file
|
|
@ -0,0 +1,124 @@
|
||||||
|
<!-- ════════════════════════════════════════════════════════════════════ -->
|
||||||
|
<div align="center">
|
||||||
|
|
||||||
|
# 🛡️ M8a Auth — Adversarial Security Audit
|
||||||
|
|
||||||
|

|
||||||
|

|
||||||
|

|
||||||
|

|
||||||
|
|
||||||
|
*The M7.5 treatment for v2's new privilege surface — before anyone relies on it for multi-owner shares.*
|
||||||
|
|
||||||
|
</div>
|
||||||
|
|
||||||
|
> **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<br/>token + PoP"] -->|RedeemToken CAS| BIND["apply server-side<br/>invite binding"]
|
||||||
|
INV["POST /invite<br/>(authed device)"] -->|EffectiveMember<br/>+ MayGrant +s| MINT["mint invite<br/>(attenuated)"]
|
||||||
|
REV["POST /invite/revoke<br/>(authed device)"] -->|MayGrant authority| KILL["delete token<br/>+ binding"]
|
||||||
|
PUSH["POST /push<br/>(authed device)"] -->|Writable + role≥editor<br/>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 <token>`. 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).
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
<div align="center">
|
||||||
|
|
||||||
|
*Six finders, thirteen agents, two real holes closed — the write-gate held the whole time. 🛡️*
|
||||||
|
|
||||||
|
</div>
|
||||||
119
internal/hub/audit_test.go
Normal file
119
internal/hub/audit_test.go
Normal file
|
|
@ -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)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
@ -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
|
// MayGrant reports whether a caller holding callerRole (and the +s bit) may set a
|
||||||
// principal currently at targetCurrentRole to grantRole. Pure attenuation: a
|
// principal currently at targetCurrentRole to grantRole, optionally conferring the
|
||||||
// compromised client can't escalate because the hub re-checks this server-side.
|
// +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;
|
// - grantRole must be a real role;
|
||||||
// - viewers can't grant; editors need +s; admins/owners always may;
|
// - 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 grant ABOVE your own role (delegation only narrows);
|
||||||
// - you can never touch a principal who currently outranks you (no demoting up).
|
// - 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 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 {
|
if grantRole < RoleViewer || grantRole > RoleOwner {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
|
@ -461,6 +464,9 @@ func MayGrant(callerRole int, callerCanReshare bool, targetCurrentRole, grantRol
|
||||||
if callerRole < RoleAdmin && !callerCanReshare {
|
if callerRole < RoleAdmin && !callerCanReshare {
|
||||||
return false
|
return false
|
||||||
}
|
}
|
||||||
|
if grantReshare && !callerCanReshare && callerRole < RoleOwner {
|
||||||
|
return false
|
||||||
|
}
|
||||||
return grantRole <= callerRole && targetCurrentRole <= callerRole
|
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
|
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).
|
// EnsurePrincipal creates a principal if absent (idempotent).
|
||||||
func (d *DB) EnsurePrincipal(id, name string, createdAt int64) error {
|
func (d *DB) EnsurePrincipal(id, name string, createdAt int64) error {
|
||||||
_, err := d.sql.Exec(
|
_, err := d.sql.Exec(
|
||||||
|
|
|
||||||
|
|
@ -468,23 +468,30 @@ func TestMayGrant(t *testing.T) {
|
||||||
callerRole int
|
callerRole int
|
||||||
reshare bool
|
reshare bool
|
||||||
targetCurrent, grant int
|
targetCurrent, grant int
|
||||||
|
grantReshare bool
|
||||||
want bool
|
want bool
|
||||||
}{
|
}{
|
||||||
{"owner grants editor", RoleOwner, false, 0, RoleEditor, true},
|
{"owner grants editor", RoleOwner, false, 0, RoleEditor, false, true},
|
||||||
{"owner grants owner (co-owner)", RoleOwner, false, 0, RoleOwner, true},
|
{"owner grants owner (co-owner)", RoleOwner, false, 0, RoleOwner, false, true},
|
||||||
{"admin grants admin", RoleAdmin, false, 0, RoleAdmin, true},
|
{"admin grants admin", RoleAdmin, false, 0, RoleAdmin, false, true},
|
||||||
{"admin can't grant owner (above self)", RoleAdmin, false, 0, RoleOwner, false},
|
{"admin can't grant owner (above self)", RoleAdmin, false, 0, RoleOwner, false, false},
|
||||||
{"editor with +s grants editor", RoleEditor, true, 0, RoleEditor, true},
|
{"editor with +s grants editor", RoleEditor, true, 0, RoleEditor, false, true},
|
||||||
{"editor with +s can't grant admin", RoleEditor, true, 0, RoleAdmin, false},
|
{"editor with +s can't grant admin", RoleEditor, true, 0, RoleAdmin, false, false},
|
||||||
{"editor WITHOUT +s can't grant", RoleEditor, false, 0, RoleViewer, false},
|
{"editor WITHOUT +s can't grant", RoleEditor, false, 0, RoleViewer, false, false},
|
||||||
{"viewer can't grant", RoleViewer, true, 0, RoleViewer, false},
|
{"viewer can't grant", RoleViewer, true, 0, RoleViewer, false, false},
|
||||||
{"can't demote a superior owner", RoleEditor, true, RoleOwner, RoleViewer, false},
|
{"can't demote a superior owner", RoleEditor, true, RoleOwner, RoleViewer, false, false},
|
||||||
{"invalid role rejected", RoleOwner, false, 0, 999, false},
|
{"invalid role rejected", RoleOwner, false, 0, 999, false, false},
|
||||||
{"zero role (unmembered) can't grant", 0, false, 0, RoleViewer, 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 {
|
for _, c := range cases {
|
||||||
if got := MayGrant(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, want %v", c.name, c.callerRole, c.reshare, c.targetCurrent, c.grant, 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)
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
|
||||||
|
|
@ -68,6 +68,7 @@ func (s *Server) Handler() http.Handler {
|
||||||
mux := http.NewServeMux()
|
mux := http.NewServeMux()
|
||||||
mux.HandleFunc("POST "+proto.PathJoin, s.handleJoin)
|
mux.HandleFunc("POST "+proto.PathJoin, s.handleJoin)
|
||||||
mux.HandleFunc("POST "+proto.PathPublish, s.auth(s.handlePublish))
|
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("POST "+proto.PathHave, s.auth(s.handleHave))
|
||||||
mux.HandleFunc("PUT "+proto.PathBlob+"{hash}", s.auth(s.handleBlob))
|
mux.HandleFunc("PUT "+proto.PathBlob+"{hash}", s.auth(s.handleBlob))
|
||||||
mux.HandleFunc("GET "+proto.PathBlob+"{hash}", s.auth(s.handleGetBlob))
|
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())
|
writeErr(w, http.StatusInternalServerError, err.Error())
|
||||||
return
|
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")
|
writeErr(w, http.StatusForbidden, "your role may not grant this")
|
||||||
return
|
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})
|
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) {
|
func (s *Server) handlePublish(w http.ResponseWriter, r *http.Request, deviceID string) {
|
||||||
var req proto.PublishRequest
|
var req proto.PublishRequest
|
||||||
if !decode(w, r, &req) {
|
if !decode(w, r, &req) {
|
||||||
|
|
|
||||||
|
|
@ -192,6 +192,11 @@ func (c *Client) Invite(share, principal, role string, reshare bool) (string, er
|
||||||
return resp.Token, err
|
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
|
// 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.
|
// 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 {
|
func (c *Client) do(method, path string, auth bool, body, out any) error {
|
||||||
|
|
|
||||||
|
|
@ -15,6 +15,7 @@ const (
|
||||||
PathEvents = "/v1/events" // GET ?share=, auth: SSE stream of change events
|
PathEvents = "/v1/events" // GET ?share=, auth: SSE stream of change events
|
||||||
PathMembers = "/v1/members" // GET ?share=, auth: who can access a share (M8a)
|
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)
|
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
|
PathMetrics = "/metrics" // GET, no auth: Prometheus text exposition
|
||||||
)
|
)
|
||||||
|
|
||||||
|
|
@ -33,6 +34,17 @@ type InviteResponse struct {
|
||||||
Token string `json:"token"`
|
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.
|
// SnapshotInfo is one entry in a share's history.
|
||||||
type SnapshotInfo struct {
|
type SnapshotInfo struct {
|
||||||
ID string `json:"id"`
|
ID string `json:"id"`
|
||||||
|
|
|
||||||
Loading…
Reference in a new issue