oficina / equipo Public

fix: use random invitation secrets and keep direct roster adds

codex agent, operated by paul@keymail.dev pushed by claude agent, operated by paul@keymail.dev f01a407dedbb2ee3f35a89802921874f9793520f parent 2a3e6e3
15 files changed, +598 −185
  • docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md +99 −0
  • internal/equipo/copy.go +7 −3
  • internal/equipo/handlers.go +9 −0
  • internal/equipo/invite_handlers.go +2 −9
  • internal/equipo/setup/application.go +13 −0
  • internal/equipo/setup/invite_cookie.go +77 −0
  • internal/equipo/setup/invite_cookie_test.go +56 −0
  • internal/equipo/setup/invite_handlers.go +47 −14
  • internal/equipo/setup/invites.go +39 −15
  • internal/equipo/templates/invite.html +3 −3
  • internal/equipo/templates/people.html +8 −1
  • internal/plan3test/conversation_browser_test.go +0 −6
  • internal/plan3test/harness_fixture.go +7 −0
  • internal/plan3test/invites_fixture.go +92 −4
  • internal/plan3test/invites_test.go +139 −130

CI failed — run details

diff --git a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
index 4903eb8e..b89d4abf 100644
--- a/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
+++ b/docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md
@@ -3815,3 +3815,102 @@ Twelve behavior mutations produced the expected failing assertions. Each source
- `.superpowers` is ignored by git. The requested full report is saved there; source changes and the appended controller evidence are committed. No push, merge or deployment occurred. Existing release certification blockers are outside this task.
Full report: `.superpowers/sdd/2026-11-04-equipo-plan-3-coordinator/task-15-report.md`. Mutation scratch is removed after report creation; no persistent process was started.
+
+
+## Fix round 1
+
+Status: DONE_WITH_CONCERNS. All seven controller rulings are implemented. This section supersedes the original report's derived-secret, repeat-sharing and reopen-after-sign-in descriptions.
+
+Commit subject: `fix: use random invitation secrets and keep direct roster adds`.
+Author: `codex <codex~paul@keymail.dev>`. Local commit only; no push.
+
+### Changes
+
+- Create each invitation secret from 32 bytes read from `crypto/rand`, separately from its public ID. Persist only the keyed verification hash. The inviting owner's first successful create response contains the share link. Creation retries return the saved metadata with an empty ShareURL. The owner can revoke and issue a new invitation when the original link is lost.
+- Validate the secret on the first GET, including pending state, expiry and current inviter authority. Exchange it for a 15-minute encrypted cookie, then issue a 303 to `/invites/{id}` without query parameters. The cookie is HttpOnly, Secure, SameSite=Lax and scoped to that invitation path. AES-GCM authenticates the invitation ID as additional data; the sealed payload carries the secret and a server-checked expiry. Acceptance reads the cookie, never a submitted secret. The intended verified identity and current roster checks still run in the acceptance transaction. Referrer-Policy remains no-referrer.
+- Restore the complete owner direct-add form from the parent of `2a3e6e3`, byte for byte, including the existing `people.add` key. Invitations remain an additional action.
+- Generate a bounded same-origin sign-in return path from an allowlisted invitation ID of at most 128 characters. Use the pinned auth library's existing `return_to` flow. The clean sign-in page retains the hidden return field, and an offline auth-link verification returns to the invitation page. Pending sessions still cannot access team resources before acceptance.
+- Add a current-owner-only pending invitation query and People list. Each row has a scriptless revoke form with revision and request ID. Existing same-origin CSRF protection applies to the list's revoke action. Query errors produce failure rather than an empty list. Accepted, revoked and expired invitations are excluded.
+- Assert exact error categories for another identity (Forbidden), wrong secret (NotFound), expired/revoked/single-use invitations (InvitationExpired), and stale roster revisions (Conflict).
+- Treat a removed, demoted or revision-changed inviter as an invalid invitation and render `invite.expired`. Reserve `invite.wrong_person` for recipient identity mismatch. Creation authorization failures use the generic failure path.
+
+The owner-read callback now uses the existing transaction-bound owner guard through setup.Application. Shared HTTP assertions moved to the existing fixture harness, and repeated denial/CSRF/state setup uses shared invitation fixture helpers. No test cases were dropped to meet the size limits. The reactivation test now compares the new session epoch with the time immediately before acceptance, avoiding a second-boundary race in its old assertion.
+
+### Tests first and verification
+
+Before implementation, `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestInvite' -count=1` exited 1. Failures included HTTP 200 instead of 303 for the exchange, replay returning the share link, missing Add a person, and HTTP 403 instead of 410 for a lapsed inviter. `CGO_ENABLED=0 go test ./internal/plan3test -run '^TestInviteRandomSecret$' -count=1` exited 1 with `secret is derived from public ID`. The cookie test first failed to compile because the cookie methods and key/clock fields did not yet exist.
+
+| Final command | Result |
+| --- | --- |
+| `CGO_ENABLED=0 go test ./internal/equipo/setup ./internal/plan3test -run '^TestInvite\|^TestPersonAPIBrowserCSRF$' -count=1` | PASS, exit 0; setup 0.003s, integration 3.564s. Includes migration upgrade, real auth verification, acceptance, replay, roster, audit, CSRF, cookie and People cases. |
+| `CGO_ENABLED=0 go test ./internal/equipotest -run '^(TestSigninAdmission\|TestSigninCSRF\|TestRoster)' -count=1` | PASS, exit 0, 7.516s. |
+| `make migration-check` | PASS, exit 0; targeted TestMigrationModels, 0.262s. No schema changes were needed. |
+| `CGO_ENABLED=0 go vet ./internal/equipo ./internal/equipo/setup ./internal/plan3test` | PASS, exit 0. |
+| `CGO_ENABLED=0 go run honnef.co/go/tools/cmd/staticcheck@v0.7.0 ./internal/equipo ./internal/equipo/setup ./internal/plan3test` | PASS, exit 0. |
+| `gofmt -l internal/equipo internal/plan3test` | PASS, exit 0, no output. |
+| `git diff --check` | PASS, exit 0. |
+
+Intermediate verification found a fixture helper calling `expectHTTP` while that function lived in a `_test.go` file. Staticcheck rejected the non-test package; moving the unchanged shared assertion into harness_fixture.go fixed it. One targeted run caught the existing reactivation timing assertion crossing a second boundary; the corrected before-acceptance comparison passed. Temporary scope/unused-variable compile errors during fixture consolidation were corrected before the final checks. No full suite, make ci, provider run, live sign-in or enrolment ran.
+
+The direct-add form was compared with `git show 2a3e6e3^:internal/equipo/templates/people.html` and is byte-identical. Direct Go line counts are root 10,798 source / 437 test; setup 876 / 65; integration harness 616 / 7,998. All remain within unchanged limits. No budget exceptions were added.
+
+### Guard mutations
+
+Each mutation below was applied separately, tested, restored from the exact saved file in a finally block, and tested again with the identical command. All twelve produced behavior failures (exit 1), then passed after restoration (exit 0). No mutation remains.
+
+| Guard | Targeted command | Observed failure | Restored |
+| --- | --- | --- | --- |
+| random secret | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestInviteRandomSecret$ -count=1` | secret is derived from public ID | PASS, exit 0 |
+| one-time share | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestInviteReplayAndExpiry$ -count=1` | issuance replay changed result | PASS, exit 0 |
+| exchange token | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestInviteVerifiedAddress$ -count=1` | HTTP 303, want 404 for an invalid secret | PASS, exit 0 |
+| cookie binding | `CGO_ENABLED=0 go test ./internal/equipo/setup -run ^TestInviteCookieGuards$ -count=1` | cookie crossed invitations <nil> | PASS, exit 0 |
+| cookie expiry | `CGO_ENABLED=0 go test ./internal/equipo/setup -run ^TestInviteCookieGuards$ -count=1` | expired cookie accepted <nil> | PASS, exit 0 |
+| cookie attributes | `CGO_ENABLED=0 go test ./internal/equipo/setup -run ^TestInviteCookieGuards$ -count=1` | unsafe cookie | PASS, exit 0 |
+| clean redirect | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestInviteVerifiedAddress$ -count=1` | exchange redirect contains secret or wrong path | PASS, exit 0 |
+| return path | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestInviteSignInPendingMember$ -count=1` | clean invitation return_to missing | PASS, exit 0 |
+| return path bound | `CGO_ENABLED=0 go test ./internal/equipo/setup -run ^TestInviteReturnPathBound$ -count=1` | 129-character invitation ID accepted | PASS, exit 0 |
+| inviter lapse category | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestInviteCurrentAuthority/lapsed_issuer -count=1` | got You do not have access to this page. Ask an owner for access., want This invitation is no longer valid. Ask a team owner for a new one. | PASS, exit 0 |
+| pending owner | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestInvitePeopleManagement$ -count=1` | list allowed non-owner <nil> | PASS, exit 0 |
+| direct add | `CGO_ENABLED=0 go test ./internal/plan3test -run ^TestInvitePeopleManagement$ -count=1` | page text "Add a person": want present=true | PASS, exit 0 |
+
+### Pending copy
+
+Every new or changed runtime entry below is individually marked `COPY REVIEW REQUIRED` in copy.go. The existing people.add text is retained unchanged. No review server or reviewer agent was started, as instructed.
+
+| Key | Draft text |
+| --- | --- |
+| `invite.pending` (new) | Pending invitations |
+| `invite.share_unavailable` (new) | This link was already shown. Revoke this invitation and create a new one if you need another link. |
+| `invite.signin` (changed) | Sign in to verify your address and return to this invitation. |
+| `invite.share` (changed) | Save and share this link with the invited person. It expires after seven days and is shown only once. |
+| `invite.expired` (changed) | This invitation is no longer valid. Ask a team owner for a new one. |
+
+The unchanged Task 15 pending entries remain: invite.welcome, invite.accept, invite.wrong_person, invite.verify, invite.create and invite.revoke. Their draft text remains in the original inventory above. No other runtime prose was added.
+
+### Self-review and remaining concerns
+
+Reviewed random generation, hash-only database persistence, no replay secret recovery, authenticated cookie binding and expiry, clean redirects/forms, current-owner list access, fail-closed lookup errors, unchanged transactional acceptance/audit checks, exact refusal categories, restoration of direct add, sign-in return propagation and CSRF. Test fixtures use local databases and offline session/auth-link records. No new server or background process was started.
+
+The requested scriptless exchange necessarily receives the secret in the first request's query string. The redirect prevents it appearing in subsequent invitation requests and forms; it cannot redact an upstream proxy's initial access log. Deployment must continue omitting or redacting invitation query strings in such logs. The application adds no request logging. Cookie protection always requires Secure, as ruled.
+
+Copy remains pending review before release. Existing Task 16 onboarding and Task 20 pending-recipient API integration notes still apply. No API routes or onboarding tables were added in this fix. Root source and integration test limits each have two lines of headroom.
+
+### Files changed in this round
+
+- internal/equipo/copy.go
+- internal/equipo/handlers.go
+- internal/equipo/invite_handlers.go
+- internal/equipo/setup/application.go
+- internal/equipo/setup/invites.go
+- internal/equipo/setup/invite_handlers.go
+- internal/equipo/setup/invite_cookie.go (new)
+- internal/equipo/setup/invite_cookie_test.go (new)
+- internal/equipo/templates/invite.html
+- internal/equipo/templates/people.html
+- internal/plan3test/invites_test.go
+- internal/plan3test/invites_fixture.go
+- internal/plan3test/harness_fixture.go
+- internal/plan3test/conversation_browser_test.go (shared helper moved, tests unchanged)
+- docs/superpowers/plans/CONTROLLER-REPORT-plan-3.md (this section appended under Task 15)
+
+Full report: `.superpowers/sdd/2026-11-04-equipo-plan-3-coordinator/task-15-report.md`. That ignored report is saved locally; the controller report and code are committed. Task scratch is removed after recording this evidence. Go caches stayed at their defaults. No push, merge or deployment. Safe to close after the local commit.
diff --git a/internal/equipo/copy.go b/internal/equipo/copy.go
index fd159fb3..0e12db3b 100644
--- a/internal/equipo/copy.go
+++ b/internal/equipo/copy.go
@@ -57,13 +57,17 @@ var pageCopy = map[string]string{
// COPY REVIEW REQUIRED: invite.wrong_person
"invite.wrong_person": "Sign in with the address this invitation was sent to.",
// COPY REVIEW REQUIRED: invite.signin
- "invite.signin": "Sign in to verify your address, then open this invitation again.",
+ "invite.signin": "Sign in to verify your address and return to this invitation.",
// COPY REVIEW REQUIRED: invite.verify
"invite.verify": "Sign in",
// COPY REVIEW REQUIRED: invite.create
"invite.create": "Invite a person",
// COPY REVIEW REQUIRED: invite.share
- "invite.share": "Share this link with the invited person. It expires after seven days.",
+ "invite.share": "Save and share this link with the invited person. It expires after seven days and is shown only once.",
+ // COPY REVIEW REQUIRED: invite.pending
+ "invite.pending": "Pending invitations",
+ // COPY REVIEW REQUIRED: invite.share_unavailable
+ "invite.share_unavailable": "This link was already shown. Revoke this invitation and create a new one if you need another link.",
// COPY REVIEW REQUIRED: invite.revoke
"invite.revoke": "Revoke invitation",
@@ -931,4 +935,4 @@ func CoordinatorToolCopy() runnerproto.CoordinatorToolCopy {
}
// COPY REVIEW REQUIRED: invite.expired
-const copyInviteExpired = "This invitation has expired or was revoked. Ask a team owner for a new one."
+const copyInviteExpired = "This invitation is no longer valid. Ask a team owner for a new one."
diff --git a/internal/equipo/handlers.go b/internal/equipo/handlers.go
index 9a65d93d..d04d861a 100644
--- a/internal/equipo/handlers.go
+++ b/internal/equipo/handlers.go
@@ -29,6 +29,7 @@ type budgetForm struct {
}
type pageData struct {
Invite setup.InviteView
+ Invitations []Invitation
Specialists []Specialist
Library library.View
SpecialistNames map[string]string
@@ -278,6 +279,14 @@ func (a *application) people(w http.ResponseWriter, r *http.Request) {
a.failure(w, r, err)
return
}
+ if data.Owner {
+ data.Invitations, err = a.store.PendingInvitations(r.Context(), Actor{Address: data.Address})
+ if err != nil {
+ a.failure(w, r, err)
+ return
+ }
+ data.RequestID = rand.Text()
+ }
a.renderLive(w, r, "people", data)
}
func (a *application) settings(w http.ResponseWriter, r *http.Request) {
diff --git a/internal/equipo/invite_handlers.go b/internal/equipo/invite_handlers.go
index 12713972..76b409a4 100644
--- a/internal/equipo/invite_handlers.go
+++ b/internal/equipo/invite_handlers.go
@@ -8,7 +8,7 @@ import (
)
func (a *application) invitationHandler() *setup.Handler {
- return &setup.Handler{Store: a.store, Invalid: ErrInvalid, Forbidden: ErrForbidden, Expired: ErrInvitationExpired, Failure: a.failure,
+ return &setup.Handler{Key: a.store.invitationKey, Now: a.store.runnerClock.Now, Store: a.store, Invalid: ErrInvalid, Forbidden: ErrForbidden, Expired: ErrInvitationExpired, Failure: a.failure,
Actor: func(r *http.Request) (Actor, error) {
id, ok := a.auth.SessionFrom(r)
if !ok || id.At.IsZero() {
@@ -24,14 +24,7 @@ func (a *application) invitationHandler() *setup.Handler {
return Actor{Address: id.Address}, nil
},
Owner: func(r *http.Request, actor Actor) error {
- member, err := a.store.Member(r.Context(), actor.Address)
- if err != nil {
- return err
- }
- if !member.Active || member.Role != RoleOwner {
- return ErrForbidden
- }
- return nil
+ return a.store.InvitationOwner(r.Context(), actor)
},
Render: func(w http.ResponseWriter, r *http.Request, status int, v setup.InviteView) {
// Pending invitees receive no team page data or private navigation counts.
diff --git a/internal/equipo/setup/application.go b/internal/equipo/setup/application.go
index fb7470ee..dabb7430 100644
--- a/internal/equipo/setup/application.go
+++ b/internal/equipo/setup/application.go
@@ -57,3 +57,16 @@ func (s *Application) MayVerifyInvitation(ctx context.Context, address string) (
})
return ok, err
}
+
+func (s *Application) ValidateInvitationToken(ctx context.Context, id, secret string) error {
+ return s.Read(ctx, func(tx *gorm.DB) error { return s.At(tx).ValidateToken(id, secret) })
+}
+func (s *Application) PendingInvitations(ctx context.Context, a Actor) (out []Invitation, err error) {
+ a.Address = s.Normalize(a.Address)
+ err = s.Read(ctx, func(tx *gorm.DB) error { out, err = s.At(tx).Pending(a); return err })
+ return
+}
+
+func (s *Application) InvitationOwner(ctx context.Context, a Actor) error {
+ return s.Read(ctx, func(tx *gorm.DB) error { return s.At(tx).deps.Owner(tx, a) })
+}
diff --git a/internal/equipo/setup/invite_cookie.go b/internal/equipo/setup/invite_cookie.go
new file mode 100644
index 00000000..80428163
--- /dev/null
+++ b/internal/equipo/setup/invite_cookie.go
@@ -0,0 +1,77 @@
+package setup
+
+import (
+ "crypto/aes"
+ "crypto/cipher"
+ "crypto/sha256"
+ "encoding/base64"
+ "encoding/json"
+ "net/http"
+ "strings"
+ "time"
+)
+
+const inviteCookieName = "__Secure-equipo_invite"
+const inviteCookieLifetime = 15 * time.Minute
+
+type inviteCookie struct {
+ Secret string
+ Expires int64
+}
+
+func validInviteID(id string) bool {
+ return len(id) > 0 && len(id) <= 128 && strings.IndexFunc(id, func(c rune) bool {
+ return !(c >= 'a' && c <= 'z' || c >= 'A' && c <= 'Z' || c >= '0' && c <= '9' || c == '_' || c == '-')
+ }) == -1
+}
+func (h *Handler) cookieCipher() (cipher.AEAD, error) {
+ if h.Key == "" {
+ return nil, h.Invalid
+ }
+ key := sha256.Sum256([]byte("equipo-invite-cookie\x00" + h.Key))
+ block, err := aes.NewCipher(key[:])
+ if err != nil {
+ return nil, err
+ }
+ return cipher.NewGCMWithRandomNonce(block)
+}
+func (h *Handler) issueCookie(w http.ResponseWriter, id, secret string) error {
+ aead, err := h.cookieCipher()
+ if err != nil {
+ return err
+ }
+ expires := h.Now().Add(inviteCookieLifetime)
+ raw, err := json.Marshal(inviteCookie{Secret: secret, Expires: expires.Unix()})
+ if err != nil {
+ return err
+ }
+ sealed := aead.Seal(nil, nil, raw, []byte(id))
+ http.SetCookie(w, &http.Cookie{Name: inviteCookieName, Value: base64.RawURLEncoding.EncodeToString(sealed), Path: "/invites/" + id, HttpOnly: true, Secure: true, SameSite: http.SameSiteLaxMode, MaxAge: int(inviteCookieLifetime.Seconds()), Expires: expires})
+ return nil
+}
+func (h *Handler) cookieSecret(r *http.Request, id string) (string, error) {
+ c, err := r.Cookie(inviteCookieName)
+ if err != nil || !validInviteID(id) {
+ return "", h.Invalid
+ }
+ raw, err := base64.RawURLEncoding.DecodeString(c.Value)
+ if err != nil {
+ return "", h.Invalid
+ }
+ aead, err := h.cookieCipher()
+ if err != nil {
+ return "", err
+ }
+ raw, err = aead.Open(nil, nil, raw, []byte(id))
+ if err != nil {
+ return "", h.Invalid
+ }
+ var value inviteCookie
+ if json.Unmarshal(raw, &value) != nil || value.Secret == "" {
+ return "", h.Invalid
+ }
+ if h.Now().Unix() >= value.Expires {
+ return "", h.Expired
+ }
+ return value.Secret, nil
+}
diff --git a/internal/equipo/setup/invite_cookie_test.go b/internal/equipo/setup/invite_cookie_test.go
new file mode 100644
index 00000000..45c36e99
--- /dev/null
+++ b/internal/equipo/setup/invite_cookie_test.go
@@ -0,0 +1,56 @@
+package setup
+
+import (
+ "errors"
+ "net/http"
+ "net/http/httptest"
+ "strings"
+ "testing"
+ "time"
+)
+
+func TestInviteCookieGuards(t *testing.T) {
+ now := time.Now()
+ expired, invalid := errors.New("expired"), errors.New("invalid")
+ h := &Handler{Key: "test-key", Now: func() time.Time { return now }, Expired: expired, Invalid: invalid}
+ w := httptest.NewRecorder()
+ if err := h.issueCookie(w, "invitation-id", "random-secret"); err != nil {
+ t.Fatal(err)
+ }
+ c := w.Result().Cookies()[0]
+ if !c.Secure || !c.HttpOnly || c.SameSite != http.SameSiteLaxMode || c.Path != "/invites/invitation-id" || c.MaxAge != 900 {
+ t.Fatal("unsafe cookie")
+ }
+ request := func(value string) *http.Request {
+ r := httptest.NewRequest("POST", "/invites/invitation-id/accept", nil)
+ r.AddCookie(&http.Cookie{Name: c.Name, Value: value})
+ return r
+ }
+ if secret, err := h.cookieSecret(request(c.Value), "invitation-id"); err != nil || secret != "random-secret" {
+ t.Fatal("cookie exchange failed", err)
+ }
+ if _, err := h.cookieSecret(request(c.Value), "another-id"); !errors.Is(err, invalid) {
+ t.Fatal("cookie crossed invitations", err)
+ }
+ if _, err := h.cookieSecret(request("x"+c.Value), "invitation-id"); !errors.Is(err, invalid) {
+ t.Fatal("tampered cookie accepted", err)
+ }
+ if _, err := h.cookieSecret(httptest.NewRequest("POST", "/", nil), "invitation-id"); !errors.Is(err, invalid) {
+ t.Fatal("missing cookie accepted", err)
+ }
+ now = now.Add(15 * time.Minute)
+ if _, err := h.cookieSecret(request(c.Value), "invitation-id"); !errors.Is(err, expired) {
+ t.Fatal("expired cookie accepted", err)
+ }
+}
+
+func TestInviteReturnPathBound(t *testing.T) {
+ for _, id := range []string{"", "../signin", "//evil.example", "x?secret=x", "x#fragment", "x\\evil", strings.Repeat("x", 129)} {
+ if validInviteID(id) {
+ t.Fatalf("unsafe return path ID %q", id)
+ }
+ }
+ if !validInviteID("safe-ID_123") {
+ t.Fatal("valid ID rejected")
+ }
+}
diff --git a/internal/equipo/setup/invite_handlers.go b/internal/equipo/setup/invite_handlers.go
index 8dfad6f1..9ac709d5 100644
--- a/internal/equipo/setup/invite_handlers.go
+++ b/internal/equipo/setup/invite_handlers.go
@@ -5,25 +5,30 @@ import (
"crypto/rand"
"errors"
"net/http"
+ "net/url"
"slices"
"strconv"
+ "time"
"amadan.net/oficina/equipo/internal/equipo/kernel"
"github.com/go-chi/chi/v5"
)
type Operations interface {
+ ValidateInvitationToken(context.Context, string, string) error
CreateInvitation(context.Context, kernel.Actor, string, kernel.Role, kernel.Mutation) (Invitation, error)
AcceptInvitation(context.Context, kernel.Actor, string, string, kernel.Mutation) (kernel.Member, error)
RevokeInvitation(context.Context, kernel.Actor, string, kernel.Mutation) error
Invitation(context.Context, kernel.Actor, string, string) (Invitation, error)
}
type InviteView struct {
- Invitation Invitation
- New, Issued, SignIn bool
- Secret, RequestID, ErrorKey string
+ Invitation Invitation
+ New, Issued, SignIn bool
+ SignInURL, RequestID, ErrorKey string
}
type Handler struct {
+ Key string
+ Now func() time.Time
Store Operations
Actor func(*http.Request) (kernel.Actor, error)
Owner func(*http.Request, kernel.Actor) error
@@ -57,27 +62,50 @@ func (h *Handler) failure(w http.ResponseWriter, r *http.Request, err error) {
}
func (h *Handler) Page(w http.ResponseWriter, r *http.Request) {
privacy(w)
+ id := chi.URLParam(r, "id")
+ if !validInviteID(id) {
+ h.Failure(w, r, h.Invalid)
+ return
+ }
+ path := "/invites/" + id
+ if values, ok := r.URL.Query()["secret"]; ok {
+ if len(values) != 1 {
+ h.Failure(w, r, h.Invalid)
+ return
+ }
+ if err := h.Store.ValidateInvitationToken(r.Context(), id, values[0]); err != nil {
+ h.failure(w, r, err)
+ return
+ }
+ if err := h.issueCookie(w, id, values[0]); err != nil {
+ h.Failure(w, r, err)
+ return
+ }
+ http.Redirect(w, r, path, http.StatusSeeOther)
+ return
+ }
+ secret, err := h.cookieSecret(r, id)
+ if err != nil {
+ h.failure(w, r, err)
+ return
+ }
a, err := h.Actor(r)
if err != nil {
if !errors.Is(err, h.Forbidden) {
h.Failure(w, r, err)
return
}
- h.Render(w, r, 200, InviteView{SignIn: true})
- return
- }
- if len(r.URL.Query()["secret"]) != 1 {
- h.Failure(w, r, h.Invalid)
+ h.Render(w, r, 200, InviteView{SignIn: true, SignInURL: "/signin?return_to=" + url.QueryEscape(path)})
return
}
- secret := r.URL.Query().Get("secret")
- in, err := h.Store.Invitation(r.Context(), a, chi.URLParam(r, "id"), secret)
+ in, err := h.Store.Invitation(r.Context(), a, id, secret)
if err != nil {
h.failure(w, r, err)
return
}
- h.Render(w, r, 200, InviteView{Invitation: in, Secret: secret, RequestID: rand.Text()})
+ h.Render(w, r, 200, InviteView{Invitation: in, RequestID: rand.Text()})
}
+
func (h *Handler) New(w http.ResponseWriter, r *http.Request) {
privacy(w)
a, err := h.Actor(r)
@@ -126,16 +154,21 @@ func (h *Handler) Create(w http.ResponseWriter, r *http.Request) {
}
in, err := h.Store.CreateInvitation(r.Context(), a, r.PostForm.Get("address"), kernel.Role(r.PostForm.Get("role")), m)
if err != nil {
- h.failure(w, r, err)
+ h.Failure(w, r, err)
return
}
h.Render(w, r, 200, InviteView{Invitation: in, Issued: true, RequestID: rand.Text()})
}
func (h *Handler) Accept(w http.ResponseWriter, r *http.Request) {
privacy(w)
- a, m, err := h.form(w, r, "secret", "request_id", "revision")
+ a, m, err := h.form(w, r, "request_id", "revision")
if err == nil {
- _, err = h.Store.AcceptInvitation(r.Context(), a, chi.URLParam(r, "id"), r.PostForm.Get("secret"), m)
+ id := chi.URLParam(r, "id")
+ var secret string
+ secret, err = h.cookieSecret(r, id)
+ if err == nil {
+ _, err = h.Store.AcceptInvitation(r.Context(), a, id, secret, m)
+ }
}
if err != nil {
h.failure(w, r, err)
diff --git a/internal/equipo/setup/invites.go b/internal/equipo/setup/invites.go
index 589bcc04..796a9e41 100644
--- a/internal/equipo/setup/invites.go
+++ b/internal/equipo/setup/invites.go
@@ -83,6 +83,9 @@ func (s *Store) record(id string) (InvitationRecord, error) {
}
func (s *Store) inviter(r InvitationRecord) error {
if err := s.deps.Owner(s.tx, kernel.Actor{Address: r.Inviter}); err != nil {
+ if errors.Is(err, s.deps.Forbidden) || errors.Is(err, s.deps.NotFound) {
+ return s.deps.Expired
+ }
return err
}
m, err := s.deps.Member(s.tx, r.Inviter)
@@ -90,7 +93,7 @@ func (s *Store) inviter(r InvitationRecord) error {
return err
}
if m.Revision != r.InviterRevision {
- return s.deps.Forbidden
+ return s.deps.Expired
}
return nil
}
@@ -141,14 +144,6 @@ func (s *Store) save(a kernel.Actor, op, id string, m kernel.Mutation, input, ou
}
return s.tx.Create(&inviteRequest{Principal: a.Address, Operation: op, Resource: id, RequestID: m.RequestID, InputHash: hash, Result: string(raw)}).Error
}
-func (s *Store) shareURL(id string) string {
- return s.deps.Origin + "/invites/" + id + "?secret=" + url.QueryEscape(s.mac("invite-secret", id))
-}
-func (s *Store) share(r InvitationRecord) Invitation {
- out := r.view()
- out.ShareURL = s.shareURL(r.ID)
- return out
-}
func (s *Store) Create(a kernel.Actor, address string, role kernel.Role, m kernel.Mutation) (Invitation, error) {
if err := s.deps.Owner(s.tx, a); err != nil {
return Invitation{}, err
@@ -166,7 +161,6 @@ func (s *Store) Create(a kernel.Actor, address string, role kernel.Role, m kerne
if err != nil {
return Invitation{}, err
}
- replay.ShareURL = s.shareURL(replay.ID)
return replay, nil
}
if m.Revision != 0 {
@@ -184,9 +178,12 @@ func (s *Store) Create(a kernel.Actor, address string, role kernel.Role, m kerne
return Invitation{}, err
}
r := InvitationRecord{ID: rand.Text(), Address: address, Role: string(role), State: "pending", Inviter: a.Address, Revision: 1, TargetRevision: old.Revision, InviterRevision: inviter.Revision, CreatedAt: s.deps.Now, ExpiresAt: s.deps.Now.Add(7 * 24 * time.Hour)}
- // A random ID and a domain-separated PRF yield a reproducible random secret.
- // Only its keyed verification hash is stored, including in replay records.
- r.SecretHash = s.mac("invite-hash", s.mac("invite-secret", r.ID))
+ var raw [32]byte
+ if _, err := rand.Read(raw[:]); err != nil {
+ return Invitation{}, err
+ }
+ secret := base64.RawURLEncoding.EncodeToString(raw[:])
+ r.SecretHash = s.mac("invite-hash", secret)
if err = s.tx.Create(&r).Error; err != nil {
return Invitation{}, err
}
@@ -196,7 +193,9 @@ func (s *Store) Create(a kernel.Actor, address string, role kernel.Role, m kerne
if err = s.save(a, "create", "", m, input, r.view()); err != nil {
return Invitation{}, err
}
- return s.share(r), nil
+ out := r.view()
+ out.ShareURL = s.deps.Origin + "/invites/" + r.ID + "?secret=" + url.QueryEscape(secret)
+ return out, nil
}
func (s *Store) Get(a kernel.Actor, id, secret string) (Invitation, error) {
r, err := s.record(id)
@@ -316,9 +315,34 @@ func (s *Store) MayVerify(address string) (bool, error) {
if err == nil {
return true, nil
}
- if !errors.Is(err, s.deps.Forbidden) {
+ if !errors.Is(err, s.deps.Expired) {
return false, err
}
}
return false, nil
}
+
+func (s *Store) ValidateToken(id, secret string) error {
+ r, err := s.record(id)
+ if err != nil {
+ return err
+ }
+ if err = s.token(r, secret); err != nil {
+ return err
+ }
+ return s.pending(r)
+}
+func (s *Store) Pending(a kernel.Actor) ([]Invitation, error) {
+ if err := s.deps.Owner(s.tx, a); err != nil {
+ return nil, err
+ }
+ var rows []InvitationRecord
+ if err := s.tx.Where("state=? AND expires_at>?", "pending", s.deps.Now).Order("created_at, id").Find(&rows).Error; err != nil {
+ return nil, err
+ }
+ out := make([]Invitation, 0, len(rows))
+ for _, r := range rows {
+ out = append(out, r.view())
+ }
+ return out, nil
+}
diff --git a/internal/equipo/templates/invite.html b/internal/equipo/templates/invite.html
index 99cc23d2..b091387a 100644
--- a/internal/equipo/templates/invite.html
+++ b/internal/equipo/templates/invite.html
@@ -2,7 +2,7 @@
<h1>{{copy "invite.welcome"}}</h1>
{{with .Invite}}
{{if .ErrorKey}}<p>{{copy .ErrorKey}}</p>
-{{else if .SignIn}}<p>{{copy "invite.signin"}}</p><a rst-btn href="/signin" rel="noreferrer">{{copy "invite.verify"}}</a>
+{{else if .SignIn}}<p>{{copy "invite.signin"}}</p><a rst-btn href="{{.SignInURL}}" rel="noreferrer">{{copy "invite.verify"}}</a>
{{else if .New}}
<form method="post" action="/invites" equipo-form>
<input type="hidden" name="request_id" value="{{.RequestID}}">
@@ -13,9 +13,9 @@
{{else}}
<p>{{.Invitation.Address}} · <span equipo-badge>{{copy (printf "role.%s" .Invitation.Role)}}</span></p>
{{if .Issued}}
-<p>{{copy "invite.share"}}</p><a href="{{.Invitation.ShareURL}}" rel="noreferrer">{{.Invitation.ShareURL}}</a>
+{{if .Invitation.ShareURL}}<p>{{copy "invite.share"}}</p><a href="{{.Invitation.ShareURL}}" rel="noreferrer">{{.Invitation.ShareURL}}</a>{{else}}<p>{{copy "invite.share_unavailable"}}</p>{{end}}
<form method="post" action="/invites/{{.Invitation.ID}}/revoke"><input type="hidden" name="request_id" value="{{.RequestID}}"><input type="hidden" name="revision" value="{{.Invitation.Revision}}"><button rst-btn type="submit">{{copy "invite.revoke"}}</button></form>
{{else}}
-<form method="post" action="/invites/{{.Invitation.ID}}/accept"><input type="hidden" name="secret" value="{{.Secret}}"><input type="hidden" name="request_id" value="{{.RequestID}}"><input type="hidden" name="revision" value="{{.Invitation.Revision}}"><button rst-btn="primary" type="submit">{{copy "invite.accept"}}</button></form>
+<form method="post" action="/invites/{{.Invitation.ID}}/accept"><input type="hidden" name="request_id" value="{{.RequestID}}"><input type="hidden" name="revision" value="{{.Invitation.Revision}}"><button rst-btn="primary" type="submit">{{copy "invite.accept"}}</button></form>
{{end}}{{end}}{{end}}
{{end}}
diff --git a/internal/equipo/templates/people.html b/internal/equipo/templates/people.html
index a8ea306c..5aee618a 100644
--- a/internal/equipo/templates/people.html
+++ b/internal/equipo/templates/people.html
@@ -8,5 +8,12 @@
<button rst-btn type="submit">{{copy "form.save"}}</button></form>
{{else}}<p>{{copy (roleKey .Role)}} · {{if .Active}}{{copy "people.active"}}{{else}}{{copy "people.inactive"}}{{end}}</p>{{end}}
</section>{{end}}
-{{if .Owner}}<a rst-btn="primary" href="/invites/new">{{copy "invite.create"}}</a>{{end}}
+{{if .Owner}}<section equipo-card><h2>{{copy "people.add"}}</h2><form method="post" action="/team/members" equipo-form>
+<input type="hidden" name="revision" value="0"><input type="hidden" name="active" value="true">
+<label>{{copy "people.address"}}<input rst-input type="email" name="address" required></label>
+<label>{{copy "people.role"}}<select rst-input name="role"><option value="member">{{copy "role.member"}}</option><option value="owner">{{copy "role.owner"}}</option></select></label>
+<button rst-btn="primary" type="submit">{{copy "form.save"}}</button></form></section>{{end}}
+{{if .Owner}}<h2>{{copy "invite.pending"}}</h2>
+{{range .Invitations}}<section equipo-card><p>{{.Address}} · <span equipo-badge>{{copy (printf "role.%s" .Role)}}</span></p><form method="post" action="/invites/{{.ID}}/revoke"><input type="hidden" name="request_id" value="{{$.RequestID}}"><input type="hidden" name="revision" value="{{.Revision}}"><button rst-btn type="submit">{{copy "invite.revoke"}}</button></form></section>{{end}}
+<a rst-btn="primary" href="/invites/new">{{copy "invite.create"}}</a>{{end}}
{{end}}
diff --git a/internal/plan3test/conversation_browser_test.go b/internal/plan3test/conversation_browser_test.go
index dfd975db..7c84fc50 100644
--- a/internal/plan3test/conversation_browser_test.go
+++ b/internal/plan3test/conversation_browser_test.go
@@ -32,12 +32,6 @@ func formPost(t *testing.T, f *fixture, actor equipo.Actor, path string, v url.V
func actionForm(id string, revision int64) url.Values {
return url.Values{"request_id": {id}, "revision": {fmt.Sprint(revision)}}
}
-func expectHTTP(t *testing.T, w *httptest.ResponseRecorder, code int) {
- t.Helper()
- if w.Code != code {
- t.Fatalf("HTTP %d, want %d: %s", w.Code, code, w.Body.String())
- }
-}
func planForm(p taskplan.Plan, id string) url.Values {
v := actionForm(id, p.Revision)
v.Set("kind", string(p.Kind))
diff --git a/internal/plan3test/harness_fixture.go b/internal/plan3test/harness_fixture.go
index c5161910..5647c511 100644
--- a/internal/plan3test/harness_fixture.go
+++ b/internal/plan3test/harness_fixture.go
@@ -104,3 +104,10 @@ func (f *fixture) createTask(t *testing.T) equipo.Task {
must(t, err)
return task
}
+
+func expectHTTP(t *testing.T, w *httptest.ResponseRecorder, code int) {
+ t.Helper()
+ if w.Code != code {
+ t.Fatalf("HTTP %d, want %d: %s", w.Code, code, w.Body.String())
+ }
+}
diff --git a/internal/plan3test/invites_fixture.go b/internal/plan3test/invites_fixture.go
index 325644a0..39c707f6 100644
--- a/internal/plan3test/invites_fixture.go
+++ b/internal/plan3test/invites_fixture.go
@@ -6,6 +6,7 @@ import (
"amadan.net/rastrillo/rastrillo/migrate"
"amadan.net/rastrillo/rastrillo/sessions"
"crypto/rand"
+ "errors"
"io"
"log/slog"
"net/http"
@@ -38,19 +39,28 @@ func inviteSession(t *testing.T, f *fixture, a equipo.Actor) {
f.exec(t, "INSERT INTO sessions(token_hash,subject,method,auth_time,created_at,expires_at) VALUES(?,?,?,?,?,?)", sessions.HashToken(token), a.Address, "keymail", now.Format(time.RFC3339Nano), now.Format(time.RFC3339Nano), now.Add(time.Hour).Format(time.RFC3339Nano))
f.Cookies[a.Address] = &http.Cookie{Name: "rastrillo_session", Value: token, Path: "/"}
}
-func inviteForm(in equipo.Invitation, secret, key string) url.Values {
- return url.Values{"secret": {secret}, "request_id": {key}, "revision": {"1"}}
+func inviteForm(key string) url.Values {
+ return url.Values{"request_id": {key}, "revision": {"1"}}
}
-func verifyInviteIdentity(t *testing.T, f *fixture, address string) *httptest.ResponseRecorder {
+func verifyInviteIdentity(t *testing.T, f *fixture, address string, returnTo ...string) *httptest.ResponseRecorder {
t.Helper()
token := rand.Text()
f.exec(t, "INSERT INTO auth_links(hash,address,purpose,expires_at) VALUES(?,?,?,?)", sessions.HashToken(token), address, "signin", time.Now().Add(time.Hour).UTC().Format(time.RFC3339))
- r := httptest.NewRequest("POST", "/auth/verify", strings.NewReader(url.Values{"token": {token}}.Encode()))
+ values := url.Values{"token": {token}}
+ if len(returnTo) != 0 {
+ values.Set("return_to", returnTo[0])
+ }
+ r := httptest.NewRequest("POST", "/auth/verify", strings.NewReader(values.Encode()))
r.Header.Set("Origin", origin)
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
w := httptest.NewRecorder()
f.Handler.ServeHTTP(w, r)
+ for _, c := range w.Result().Cookies() {
+ if c.Name == "rastrillo_session" && c.Value != "" {
+ f.Cookies[address] = c
+ }
+ }
return w
}
@@ -73,3 +83,81 @@ func inviteUpgradeFixture(t *testing.T) *fixture {
f.exec(t, "INSERT INTO audit_events(actor,kind,record_id) VALUES('saved@example.com','old.audit','old')")
return f
}
+
+func inviteRequest(t *testing.T, f *fixture, actor equipo.Actor, method, path string, values url.Values, cookie *http.Cookie, sites ...string) *httptest.ResponseRecorder {
+ t.Helper()
+ r := httptest.NewRequest(method, path, strings.NewReader(values.Encode()))
+ if c := f.Cookies[actor.Address]; c != nil {
+ r.AddCookie(c)
+ }
+ if cookie != nil {
+ r.AddCookie(cookie)
+ }
+ if len(sites) == 0 {
+ sites = []string{origin}
+ }
+ r.Header.Set("Origin", sites[0])
+ r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
+ w := httptest.NewRecorder()
+ f.Handler.ServeHTTP(w, r)
+ return w
+}
+func exchangeInvite(t *testing.T, f *fixture, in equipo.Invitation) *http.Cookie {
+ t.Helper()
+ w := inviteRequest(t, f, equipo.Actor{}, "GET", in.ShareURL, nil, nil)
+ expectHTTP(t, w, 303)
+ if w.Header().Get("Location") != "/invites/"+in.ID {
+ t.Fatal("exchange redirect contains secret or wrong path")
+ }
+ for _, c := range w.Result().Cookies() {
+ if c.Path == "/invites/"+in.ID {
+ if !c.HttpOnly || !c.Secure || c.SameSite != http.SameSiteLaxMode || c.MaxAge <= 0 || c.MaxAge > 900 {
+ t.Fatal("unsafe invite cookie", c.Name)
+ }
+ return c
+ }
+ }
+ t.Fatal("missing path-scoped invite cookie")
+ return nil
+}
+
+func wantInviteError(t *testing.T, got, want error) {
+ t.Helper()
+ if !errors.Is(got, want) {
+ t.Fatalf("got %v, want %v", got, want)
+ }
+}
+func inviteCSRF(t *testing.T, f *fixture, actor equipo.Actor, path string, values url.Values, cookie *http.Cookie) {
+ t.Helper()
+ for _, site := range []string{"https://evil.example", ""} {
+ expectHTTP(t, inviteRequest(t, f, actor, "POST", path, values, cookie, site), 403)
+ }
+}
+func invalidateInvite(t *testing.T, f *fixture, in equipo.Invitation, state string) {
+ t.Helper()
+ switch state {
+ case "expired":
+ f.exec(t, "UPDATE invitations SET expires_at=? WHERE id=?", time.Now().Add(-time.Hour), in.ID)
+ case "revoked":
+ for range 2 {
+ must(t, f.Store.RevokeInvitation(ctx, owner, in.ID, equipo.Mutation{RequestID: "revoke", Revision: 1}))
+ }
+ case "removed inviter":
+ must(t, f.Store.SetMember(ctx, peer, owner.Address, equipo.RoleMember, false, 1))
+ case "unavailable roster":
+ f.exec(t, "ALTER TABLE members RENAME TO unavailable_members")
+ case "unavailable invites":
+ f.exec(t, "ALTER TABLE invitations RENAME TO unavailable_invitations")
+ default:
+ t.Fatal("unknown invitation fixture state", state)
+ }
+}
+
+func inviteText(t *testing.T, body string, present bool, texts ...string) {
+ t.Helper()
+ for _, text := range texts {
+ if strings.Contains(body, text) != present {
+ t.Fatalf("page text %q: want present=%t", text, present)
+ }
+ }
+}
diff --git a/internal/plan3test/invites_test.go b/internal/plan3test/invites_test.go
index 659001c9..a453afdf 100644
--- a/internal/plan3test/invites_test.go
+++ b/internal/plan3test/invites_test.go
@@ -1,9 +1,13 @@
package plan3test
import (
+ "crypto/hmac"
+ "crypto/sha256"
+ "encoding/base64"
"errors"
"net/http/httptest"
"net/url"
+ "regexp"
"strings"
"testing"
"time"
@@ -16,44 +20,33 @@ func TestInviteVerifiedAddress(t *testing.T) {
in, secret := issueInvite(t, f, invitee.Address)
inviteSession(t, f, invitee)
for _, a := range []equipo.Actor{owner, {}} {
- if _, err := f.Store.AcceptInvitation(ctx, a, in.ID, secret, equipo.Mutation{RequestID: "wrong", Revision: 1}); !errors.Is(err, equipo.ErrForbidden) {
- t.Fatal("wrong identity accepted", err)
- }
+ _, err := f.Store.AcceptInvitation(ctx, a, in.ID, secret, equipo.Mutation{RequestID: "wrong", Revision: 1})
+ wantInviteError(t, err, equipo.ErrForbidden)
}
- w := f.get(t, invitee, in.ShareURL)
+ cookie := exchangeInvite(t, f, in)
+ w := inviteRequest(t, f, invitee, "GET", "/invites/"+in.ID, nil, cookie)
expectHTTP(t, w, 200)
if f.count(t, "SELECT count(*) FROM members WHERE address=?", invitee.Address) != 0 {
t.Fatal("GET created member")
}
+ inviteText(t, w.Body.String(), false, secret)
if w.Header().Get("Referrer-Policy") != "no-referrer" || w.Header().Get("Cache-Control") != "no-store" {
t.Fatal("missing privacy headers")
}
expectHTTP(t, f.get(t, invitee, "/invites/"+in.ID+"?secret=invalid"), 404)
- expectHTTP(t, f.get(t, owner, in.ShareURL), 403)
- r := httptest.NewRequest("POST", "/invites/"+in.ID+"/accept", strings.NewReader(inviteForm(in, secret, "unauth").Encode()))
- r.Header.Set("Origin", origin)
- r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- w = httptest.NewRecorder()
- f.Handler.ServeHTTP(w, r)
- if w.Code != 303 && w.Code != 401 && w.Code != 403 {
- t.Fatal("unverified accepted", w.Code)
- }
+ expectHTTP(t, inviteRequest(t, f, owner, "GET", "/invites/"+in.ID, nil, cookie), 403)
+ expectHTTP(t, inviteRequest(t, f, equipo.Actor{}, "POST", "/invites/"+in.ID+"/accept", inviteForm("unauth"), cookie), 403)
if f.count(t, "SELECT count(*) FROM members WHERE address=?", invitee.Address) != 0 {
t.Fatal("unverified created member")
}
- for _, site := range []string{"https://evil.example", ""} {
- r := httptest.NewRequest("POST", "/invites/"+in.ID+"/accept", strings.NewReader(inviteForm(in, secret, "csrf").Encode()))
- r.AddCookie(f.Cookies[invitee.Address])
- r.Header.Set("Origin", site)
- r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
- w := httptest.NewRecorder()
- f.Handler.ServeHTTP(w, r)
- expectHTTP(t, w, 403)
- }
- values := inviteForm(in, secret, "accept")
+ inviteCSRF(t, f, invitee, "/invites/"+in.ID+"/accept", inviteForm("csrf"), cookie)
+ expectHTTP(t, inviteRequest(t, f, invitee, "POST", "/invites/"+in.ID+"/accept", inviteForm("no-cookie"), nil), 422)
+ other, _ := issueInvite(t, f, invitee.Address)
+ expectHTTP(t, inviteRequest(t, f, invitee, "POST", "/invites/"+other.ID+"/accept", inviteForm("wrong-cookie"), cookie), 422)
+ values := inviteForm("accept")
values.Set("address", owner.Address)
expectHTTP(t, formPost(t, f, invitee, "/invites/"+in.ID+"/accept", values), 422)
- expectHTTP(t, formPost(t, f, invitee, "/invites/"+in.ID+"/accept", inviteForm(in, secret, "accept")), 303)
+ expectHTTP(t, inviteRequest(t, f, invitee, "POST", "/invites/"+in.ID+"/accept", inviteForm("accept"), cookie), 303)
m, err := f.Store.Member(ctx, invitee.Address)
must(t, err)
if !m.Active || m.Role != equipo.RoleMember {
@@ -68,13 +61,14 @@ func TestInviteReplayAndExpiry(t *testing.T) {
must(t, err)
again, err := f.Store.CreateInvitation(ctx, owner, invitee.Address, equipo.RoleMember, m)
must(t, err)
- if in != again {
+ originalURL := in.ShareURL
+ in.ShareURL = ""
+ if in != again || again.ShareURL != "" {
t.Fatal("issuance replay changed result")
}
- if _, err = f.Store.CreateInvitation(ctx, owner, invitee.Address, equipo.RoleOwner, m); !errors.Is(err, equipo.ErrConflict) {
- t.Fatal("changed replay accepted", err)
- }
- u, _ := url.Parse(in.ShareURL)
+ _, err = f.Store.CreateInvitation(ctx, owner, invitee.Address, equipo.RoleOwner, m)
+ wantInviteError(t, err, equipo.ErrConflict)
+ u, _ := url.Parse(originalURL)
secret := u.Query().Get("secret")
am := equipo.Mutation{RequestID: "accept", Revision: 1}
member, err := f.Store.AcceptInvitation(ctx, invitee, in.ID, secret, am)
@@ -87,27 +81,20 @@ func TestInviteReplayAndExpiry(t *testing.T) {
for _, tc := range []struct {
a equipo.Actor
secret, key string
- }{{peer, secret, "accept"}, {invitee, secret, "new"}, {invitee, "wrong", "accept"}} {
- if _, err = f.Store.AcceptInvitation(ctx, tc.a, in.ID, tc.secret, equipo.Mutation{RequestID: tc.key, Revision: 1}); err == nil {
- t.Fatal("used token accepted")
- }
+ want error
+ }{{peer, secret, "accept", equipo.ErrForbidden}, {invitee, secret, "new", equipo.ErrInvitationExpired}, {invitee, "wrong", "accept", equipo.ErrNotFound}} {
+ _, err = f.Store.AcceptInvitation(ctx, tc.a, in.ID, tc.secret, equipo.Mutation{RequestID: tc.key, Revision: 1})
+ wantInviteError(t, err, tc.want)
}
f.exec(t, "UPDATE members SET active=0 WHERE address=?", invitee.Address)
- if _, err = f.Store.AcceptInvitation(ctx, invitee, in.ID, secret, am); !errors.Is(err, equipo.ErrForbidden) {
- t.Fatal("removed recipient replay accepted", err)
- }
+ _, err = f.Store.AcceptInvitation(ctx, invitee, in.ID, secret, am)
+ wantInviteError(t, err, equipo.ErrForbidden)
for _, state := range []string{"expired", "revoked"} {
t.Run(state, func(t *testing.T) {
in, secret := issueInvite(t, f, state+"@example.com")
- if state == "expired" {
- f.exec(t, "UPDATE invitations SET expires_at=? WHERE id=?", time.Now().Add(-time.Hour), in.ID)
- } else {
- must(t, f.Store.RevokeInvitation(ctx, owner, in.ID, equipo.Mutation{RequestID: "revoke", Revision: 1}))
- must(t, f.Store.RevokeInvitation(ctx, owner, in.ID, equipo.Mutation{RequestID: "revoke", Revision: 1}))
- }
- if _, err := f.Store.AcceptInvitation(ctx, equipo.Actor{Address: in.Address}, in.ID, secret, am); err == nil {
- t.Fatal("inactive invitation accepted")
- }
+ invalidateInvite(t, f, in, state)
+ _, err := f.Store.AcceptInvitation(ctx, equipo.Actor{Address: in.Address}, in.ID, secret, am)
+ wantInviteError(t, err, equipo.ErrInvitationExpired)
})
}
var hash string
@@ -120,29 +107,32 @@ func TestInviteReplayAndExpiry(t *testing.T) {
}
}
func TestInviteCurrentAuthority(t *testing.T) {
- t.Run("removed issuer", func(t *testing.T) {
- f := newFixture(t)
- in, secret := issueInvite(t, f, invitee.Address)
- must(t, f.Store.SetMember(ctx, peer, owner.Address, equipo.RoleMember, false, 1))
- if _, err := f.Store.CreateInvitation(ctx, owner, "next@example.com", equipo.RoleMember, equipo.Mutation{RequestID: "stale"}); !errors.Is(err, equipo.ErrForbidden) {
- t.Fatal("removed owner issued invite", err)
- }
- if err := f.Store.RevokeInvitation(ctx, owner, in.ID, equipo.Mutation{RequestID: "stale", Revision: 1}); !errors.Is(err, equipo.ErrForbidden) {
- t.Fatal("removed owner revoked", err)
- }
- if _, err := f.Store.AcceptInvitation(ctx, invitee, in.ID, secret, equipo.Mutation{RequestID: "accept", Revision: 1}); !errors.Is(err, equipo.ErrForbidden) {
- t.Fatal("removed inviter granted membership", err)
- }
- })
+ for _, active := range []bool{false, true} {
+ t.Run("lapsed issuer", func(t *testing.T) {
+ f := newFixture(t)
+ in, secret := issueInvite(t, f, invitee.Address)
+ inviteSession(t, f, invitee)
+ must(t, f.Store.SetMember(ctx, peer, owner.Address, equipo.RoleMember, active, 1))
+ _, err := f.Store.CreateInvitation(ctx, owner, "next@example.com", equipo.RoleMember, equipo.Mutation{RequestID: "stale"})
+ wantInviteError(t, err, equipo.ErrForbidden)
+ err = f.Store.RevokeInvitation(ctx, owner, in.ID, equipo.Mutation{RequestID: "stale", Revision: 1})
+ wantInviteError(t, err, equipo.ErrForbidden)
+ _, err = f.Store.AcceptInvitation(ctx, invitee, in.ID, secret, equipo.Mutation{RequestID: "accept", Revision: 1})
+ wantInviteError(t, err, equipo.ErrInvitationExpired)
+ w := f.get(t, invitee, in.ShareURL)
+ expectHTTP(t, w, 410)
+ inviteText(t, w.Body.String(), false, "Sign in with the address")
+ })
+ }
t.Run("last owner", func(t *testing.T) {
f := newFixture(t)
- if _, err := f.Store.CreateInvitation(ctx, owner, owner.Address, equipo.RoleMember, equipo.Mutation{RequestID: "demote"}); !errors.Is(err, equipo.ErrConflict) {
- t.Fatal("invite can demote owner", err)
- }
+ _, err := f.Store.CreateInvitation(ctx, owner, owner.Address, equipo.RoleMember, equipo.Mutation{RequestID: "demote"})
+ wantInviteError(t, err, equipo.ErrConflict)
must(t, f.Store.SetMember(ctx, owner, peer.Address, equipo.RoleMember, true, 1))
- if err := f.Store.SetMember(ctx, owner, owner.Address, equipo.RoleMember, true, 1); !errors.Is(err, equipo.ErrLastOwner) {
- t.Fatal("last owner not protected", err)
- }
+ err = f.Store.SetMember(ctx, owner, owner.Address, equipo.RoleMember, true, 1)
+ wantInviteError(t, err, equipo.ErrLastOwner)
+ _, err = equipo.NewStore(f.DB).CreateInvitation(ctx, owner, invitee.Address, equipo.RoleMember, equipo.Mutation{RequestID: "unconfigured"})
+ wantInviteError(t, err, equipo.ErrUnavailable)
})
t.Run("atomic audit", func(t *testing.T) {
f := newFixture(t)
@@ -166,14 +156,17 @@ func TestInviteCurrentAuthority(t *testing.T) {
}
func TestInviteSignInPendingMember(t *testing.T) {
f := newFixture(t)
- in, secret := issueInvite(t, f, invitee.Address)
+ in, _ := issueInvite(t, f, invitee.Address)
+ cookie := exchangeInvite(t, f, in)
+ page := inviteRequest(t, f, equipo.Actor{}, "GET", "/invites/"+in.ID, nil, cookie)
+ expectHTTP(t, page, 200)
+ inviteText(t, page.Body.String(), true, "return_to=%2Finvites%2F"+in.ID)
+ inviteText(t, inviteRequest(t, f, equipo.Actor{}, "GET", "/signin?return_to="+url.QueryEscape("/invites/"+in.ID), nil, nil).Body.String(), true, `name="return_to" value="/invites/`+in.ID+`"`)
// An offline auth_links fixture drives the real verifier and NewAuth admission gate.
- w := verifyInviteIdentity(t, f, invitee.Address)
+ w := verifyInviteIdentity(t, f, invitee.Address, "/invites/"+in.ID)
expectHTTP(t, w, 303)
- for _, c := range w.Result().Cookies() {
- if c.Name == "rastrillo_session" && c.Value != "" {
- f.Cookies[invitee.Address] = c
- }
+ if w.Header().Get("Location") != "/invites/"+in.ID {
+ t.Fatal("verification lost invite return")
}
if f.Cookies[invitee.Address] == nil {
t.Fatal("pending invite could not verify identity")
@@ -182,8 +175,8 @@ func TestInviteSignInPendingMember(t *testing.T) {
expectHTTP(t, f.get(t, invitee, path), 403)
}
expectHTTP(t, formPost(t, f, invitee, "/conversation", url.Values{"request_id": {"blocked"}, "body": {"no"}}), 403)
- expectHTTP(t, f.get(t, invitee, in.ShareURL), 200)
- expectHTTP(t, formPost(t, f, invitee, "/invites/"+in.ID+"/accept", inviteForm(in, secret, "accept")), 303)
+ expectHTTP(t, inviteRequest(t, f, invitee, "GET", "/invites/"+in.ID, nil, cookie), 200)
+ expectHTTP(t, inviteRequest(t, f, invitee, "POST", "/invites/"+in.ID+"/accept", inviteForm("accept"), cookie), 303)
expectHTTP(t, f.get(t, invitee, "/conversation"), 200)
}
@@ -196,11 +189,11 @@ func TestInviteGuards(t *testing.T) {
secret := u.Query().Get("secret")
_, err = f.Store.AcceptInvitation(ctx, peer, in.ID, secret, equipo.Mutation{RequestID: "first", Revision: 1})
must(t, err)
- if _, err = f.Store.AcceptInvitation(ctx, peer, in.ID, secret, equipo.Mutation{RequestID: "second", Revision: 2}); err == nil {
- t.Fatal("single-use invitation reused")
- }
+ _, err = f.Store.AcceptInvitation(ctx, peer, in.ID, secret, equipo.Mutation{RequestID: "second", Revision: 2})
+ wantInviteError(t, err, equipo.ErrInvitationExpired)
replay, err := f.Store.CreateInvitation(ctx, owner, peer.Address, equipo.RoleOwner, equipo.Mutation{RequestID: "existing"})
must(t, err)
+ in.ShareURL = ""
if in != replay {
t.Fatal("creation replay changed after acceptance")
}
@@ -209,13 +202,11 @@ func TestInviteGuards(t *testing.T) {
f := newFixture(t)
in, secret := issueInvite(t, f, invitee.Address)
must(t, f.Store.SetMember(ctx, owner, invitee.Address, equipo.RoleMember, true, 0))
- if _, err := f.Store.AcceptInvitation(ctx, invitee, in.ID, secret, equipo.Mutation{RequestID: "changed", Revision: 1}); !errors.Is(err, equipo.ErrConflict) {
- t.Fatal("stale target revision accepted", err)
- }
+ _, err := f.Store.AcceptInvitation(ctx, invitee, in.ID, secret, equipo.Mutation{RequestID: "changed", Revision: 1})
+ wantInviteError(t, err, equipo.ErrConflict)
must(t, f.Store.SetMember(ctx, owner, invitee.Address, equipo.RoleMember, false, 1))
- if _, err := f.Store.AcceptInvitation(ctx, invitee, in.ID, secret, equipo.Mutation{RequestID: "accept", Revision: 1}); !errors.Is(err, equipo.ErrConflict) {
- t.Fatal("stale invite undid roster change", err)
- }
+ _, err = f.Store.AcceptInvitation(ctx, invitee, in.ID, secret, equipo.Mutation{RequestID: "accept", Revision: 1})
+ wantInviteError(t, err, equipo.ErrConflict)
})
t.Run("role changed after issue", func(t *testing.T) {
f := newFixture(t)
@@ -223,9 +214,8 @@ func TestInviteGuards(t *testing.T) {
must(t, err)
must(t, f.Store.SetMember(ctx, owner, peer.Address, equipo.RoleMember, true, 1))
u, _ := url.Parse(in.ShareURL)
- if _, err = f.Store.AcceptInvitation(ctx, peer, in.ID, u.Query().Get("secret"), equipo.Mutation{RequestID: "accept", Revision: 1}); !errors.Is(err, equipo.ErrConflict) {
- t.Fatal("invite restored old role", err)
- }
+ _, err = f.Store.AcceptInvitation(ctx, peer, in.ID, u.Query().Get("secret"), equipo.Mutation{RequestID: "accept", Revision: 1})
+ wantInviteError(t, err, equipo.ErrConflict)
})
t.Run("removed owner replay", func(t *testing.T) {
f := newFixture(t)
@@ -233,9 +223,8 @@ func TestInviteGuards(t *testing.T) {
_, err := f.Store.CreateInvitation(ctx, owner, invitee.Address, equipo.RoleMember, m)
must(t, err)
must(t, f.Store.SetMember(ctx, peer, owner.Address, equipo.RoleMember, false, 1))
- if _, err = f.Store.CreateInvitation(ctx, owner, invitee.Address, equipo.RoleMember, m); !errors.Is(err, equipo.ErrForbidden) {
- t.Fatal("stale owner replay released link", err)
- }
+ _, err = f.Store.CreateInvitation(ctx, owner, invitee.Address, equipo.RoleMember, m)
+ wantInviteError(t, err, equipo.ErrForbidden)
})
t.Run("reactivation", func(t *testing.T) {
f := newFixture(t)
@@ -243,45 +232,19 @@ func TestInviteGuards(t *testing.T) {
must(t, f.Store.SetMember(ctx, owner, invitee.Address, equipo.RoleMember, false, 1))
in, secret := issueInvite(t, f, invitee.Address)
inviteSession(t, f, invitee)
+ before := time.Now().Unix()
member, err := f.Store.AcceptInvitation(ctx, invitee, in.ID, secret, equipo.Mutation{RequestID: "accept", Revision: 1})
must(t, err)
- if !member.Active || member.SessionEpoch <= time.Now().Unix() || f.count(t, "SELECT count(*) FROM sessions WHERE subject=?", invitee.Address) != 0 {
+ if !member.Active || member.SessionEpoch <= before || f.count(t, "SELECT count(*) FROM sessions WHERE subject=?", invitee.Address) != 0 {
t.Fatal("reactivation revived removed sessions")
}
})
- t.Run("new store no key", func(t *testing.T) {
- f := newFixture(t)
- _, err := equipo.NewStore(f.DB).CreateInvitation(ctx, owner, invitee.Address, equipo.RoleMember, equipo.Mutation{RequestID: "unconfigured"})
- if !errors.Is(err, equipo.ErrUnavailable) {
- t.Fatal("unconfigured store issued a secret", err)
- }
- })
- t.Run("owner browser routes", func(t *testing.T) {
- f := newFixture(t)
- expectHTTP(t, f.get(t, owner, "/invites/new"), 200)
- w := formPost(t, f, owner, "/invites", url.Values{"address": {invitee.Address}, "role": {"member"}, "request_id": {"browser"}})
- expectHTTP(t, w, 200)
- if !strings.Contains(w.Body.String(), "?secret=") || w.Header().Get("Referrer-Policy") != "no-referrer" {
- t.Fatal("owner sharing link missing")
- }
- in, err := f.Store.CreateInvitation(ctx, owner, invitee.Address, equipo.RoleMember, equipo.Mutation{RequestID: "browser"})
- must(t, err)
- expectHTTP(t, formPost(t, f, owner, "/invites/"+in.ID+"/revoke", url.Values{"request_id": {"revoke"}, "revision": {"1"}}), 303)
- inviteSession(t, f, invitee)
- expectHTTP(t, f.get(t, invitee, in.ShareURL), 410)
- r := httptest.NewRequest("GET", in.ShareURL, nil)
- r.Header.Set("Authorization", "Bearer runner-fixture")
- w = httptest.NewRecorder()
- f.Handler.ServeHTTP(w, r)
- expectHTTP(t, w, 401)
- })
t.Run("failed authority lookup", func(t *testing.T) {
f := newFixture(t)
in, secret := issueInvite(t, f, invitee.Address)
f.exec(t, "ALTER TABLE members RENAME TO unavailable_members")
- if _, err := f.Store.AcceptInvitation(ctx, invitee, in.ID, secret, equipo.Mutation{RequestID: "accept", Revision: 1}); !errors.Is(err, equipo.ErrUnavailable) {
- t.Fatal("roster error did not deny acceptance", err)
- }
+ _, err := f.Store.AcceptInvitation(ctx, invitee, in.ID, secret, equipo.Mutation{RequestID: "accept", Revision: 1})
+ wantInviteError(t, err, equipo.ErrUnavailable)
})
}
@@ -290,18 +253,7 @@ func TestInviteSignInInactiveInvitation(t *testing.T) {
t.Run(state, func(t *testing.T) {
f := newFixture(t)
in, _ := issueInvite(t, f, invitee.Address)
- switch state {
- case "expired":
- f.exec(t, "UPDATE invitations SET expires_at=? WHERE id=?", time.Now().Add(-time.Hour), in.ID)
- case "revoked":
- must(t, f.Store.RevokeInvitation(ctx, owner, in.ID, equipo.Mutation{RequestID: "revoke", Revision: 1}))
- case "removed inviter":
- must(t, f.Store.SetMember(ctx, peer, owner.Address, equipo.RoleMember, false, 1))
- case "unavailable roster":
- f.exec(t, "ALTER TABLE members RENAME TO unavailable_members")
- case "unavailable invites":
- f.exec(t, "ALTER TABLE invitations RENAME TO unavailable_invitations")
- }
+ invalidateInvite(t, f, in, state)
w := verifyInviteIdentity(t, f, invitee.Address)
expectHTTP(t, w, 403)
if f.count(t, "SELECT count(*) FROM sessions WHERE subject=?", invitee.Address) != 0 {
@@ -310,3 +262,60 @@ func TestInviteSignInInactiveInvitation(t *testing.T) {
})
}
}
+
+func TestInviteRandomSecret(t *testing.T) {
+ f := newFixture(t)
+ in, secret := issueInvite(t, f, invitee.Address)
+ raw, err := base64.RawURLEncoding.DecodeString(secret)
+ if err != nil || len(raw) < 32 {
+ t.Fatal("secret needs at least 32 random bytes")
+ }
+ h := hmac.New(sha256.New, []byte("plan3-fixture"))
+ h.Write([]byte("invite-secret\x00" + in.ID))
+ if secret == base64.RawURLEncoding.EncodeToString(h.Sum(nil)) {
+ t.Fatal("secret is derived from public ID")
+ }
+ if strings.Contains(in.ID, secret) || f.count(t, "SELECT count(*) FROM invitation_requests WHERE result LIKE ?", "%"+secret+"%") != 0 {
+ t.Fatal("secret persisted")
+ }
+}
+
+func TestInvitePeopleManagement(t *testing.T) {
+ f := newFixture(t)
+ expectHTTP(t, f.get(t, owner, "/invites/new"), 200)
+ w := formPost(t, f, owner, "/invites", url.Values{"address": {invitee.Address}, "role": {"member"}, "request_id": {"browser"}})
+ expectHTTP(t, w, 200)
+ if !strings.Contains(w.Body.String(), "?secret=") || w.Header().Get("Referrer-Policy") != "no-referrer" {
+ t.Fatal("owner sharing link missing")
+ }
+ inviteText(t, formPost(t, f, owner, "/invites", url.Values{"address": {invitee.Address}, "role": {"member"}, "request_id": {"browser"}}).Body.String(), false, "?secret=")
+ share := regexp.MustCompile(`href="([^"]+\?secret=[^"]+)"`).FindStringSubmatch(w.Body.String())[1]
+ in, err := f.Store.CreateInvitation(ctx, owner, invitee.Address, equipo.RoleMember, equipo.Mutation{RequestID: "browser"})
+ must(t, err)
+ action := "/invites/" + in.ID + "/revoke"
+ w = f.get(t, owner, "/people")
+ expectHTTP(t, w, 200)
+ inviteText(t, w.Body.String(), true, "Add a person", `name="revision" value="0"`, action, invitee.Address, `name="request_id"`, `href="/invites/new"`)
+ inviteText(t, w.Body.String(), false, "?secret=")
+ must(t, f.Store.SetMember(ctx, owner, peer.Address, equipo.RoleMember, true, 1))
+ w = f.get(t, peer, "/people")
+ expectHTTP(t, w, 200)
+ inviteText(t, w.Body.String(), false, action, invitee.Address)
+ values := url.Values{"request_id": {"list-revoke"}, "revision": {"1"}}
+ expectHTTP(t, inviteRequest(t, f, peer, "POST", action, values, nil), 403)
+ inviteCSRF(t, f, owner, action, values, nil)
+ if _, err := f.Store.PendingInvitations(ctx, peer); !errors.Is(err, equipo.ErrForbidden) {
+ t.Fatal("list allowed non-owner", err)
+ }
+ expectHTTP(t, formPost(t, f, owner, action, values), 303)
+ inviteText(t, f.get(t, owner, "/people").Body.String(), false, action)
+ inviteSession(t, f, invitee)
+ expectHTTP(t, f.get(t, invitee, share), 410)
+ r := httptest.NewRequest("GET", share, nil)
+ r.Header.Set("Authorization", "Bearer runner-fixture")
+ w = httptest.NewRecorder()
+ f.Handler.ServeHTTP(w, r)
+ expectHTTP(t, w, 401)
+ f.exec(t, "ALTER TABLE invitations RENAME TO unavailable_invitations")
+ expectHTTP(t, f.get(t, owner, "/people"), 503)
+}