Keymail sign-in in Calendar, without an allowlist oracle
Calendar set force=1 on every permitted POST /signin, so a Keymail address never reached Keymail (Paul, 2026-10-06: "I do want it to use keymail"). The reason was an oracle: a permitted Keymail address would have redirected out while a non-permitted one got ?sent=1. Now every address reaches Begin and the ceremony depends on the domain alone. A Keymail address, permitted or not, gets the same continuation page (connect.OAuthContinuation, both modes; a 303 out of the form POST is refused by Safari's form-action). Any other address gets ?sent=1 and admissionMailer mails it only when the allowlist holds it, still counting refusals in the log without the address. Authorize after verification is unchanged; its bare-text 403 becomes the door with ?err=refused (doorOnRefusal) until rastrillo has a hook. The form now carries force on ?force=1&err=keymail, which it never had to before. Tests stub classification and Keymail in-process (keymailtest).
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
9 files changed,
+635
−87
AGENTS.md+1 −0internal/calendar/auth.go+10 −71internal/calendar/auth_keymail.go+138 −0internal/calendar/keymail_signin_test.go+250 −0internal/calendar/keymailtest/keymailtest.go+190 −0internal/calendar/render.go+3 −1internal/calendar/routes.go+7 −11internal/calendar/signin.go+31 −1internal/calendar/templates/signin.html+5 −3
CI passed — run details
CI log
=== vet === go vet ./... go vet -tags browser ./internal/calendartest/ === fmt === === test === go test ./... ? amadan.net/oficina/calendar/cmd/calendar [no test files] ok amadan.net/oficina/calendar/internal/calendar 4.893s ? amadan.net/oficina/calendar/internal/calendar/icons [no test files] ? amadan.net/oficina/calendar/internal/calendar/keymailtest [no test files] ? amadan.net/oficina/calendar/internal/calendar/seal [no test files] ok amadan.net/oficina/calendar/internal/calendartest 2.499s ok amadan.net/oficina/calendar/internal/guardstest 0.053s ? amadan.net/oficina/calendar/scripts/writeestilo [no test files] === migration-check === go tool rastrillo migration check rastrillo migration check: models and migrations agree
diff --git a/AGENTS.md b/AGENTS.md| index 37c2eeb..733b7b2 100644 |
| --- a/AGENTS.md |
| +++ b/AGENTS.md |
| @@ -61,6 +61,7 @@ pass by reading a file the data has not reached. |
| | 5 | Reminders are per PERSON, not per event | Per-event reminders — two people on one meeting want different warnings, and the fix needs a person column anyway | This session, 2026-09-02 | |
| | 6 | Delivery is at-least-once; every ambiguous case resolves towards sending | At-most-once — a reminder that never arrives is worse than one that arrives twice | This session, 2026-09-02 | |
| | 7 | Local sign-in is a magic link, with no passkey second factor | Passkeys — `passkey.Config` derives its relying party from this instance's host, so one person in three team instances enrols three credentials. Same ruling docs made | This session, 2026-09-02 | |
| +| 7a | Local sign-in uses Keymail for an address whose domain runs Keymail, and the magic link for every other address — chosen by the domain alone, never by the allowlist (an oracle otherwise). The Keymail hop is a continuation page, never a 303 out of the form POST (Safari applies form-action to it) | Forcing every address to a magic link | Paul, 2026-10-06 ("I do want it to use keymail") | |
| | 8 | A new event defaults to the person's PERSONAL calendar | Defaulting to the team calendar — the cost of forgetting to change a dropdown should fall on the side of privacy | This session, 2026-09-02 | |
| | H1 | **Optional Home sign-in connects to an existing person after fresh local proof and explicit confirmation; local sign-in remains available** | Treating the Home subject as an email or allocating a new person | User-approved suite connection, 2026-09-10 | |
| | B1 | A booking is confirmed by a BUTTON on the page the mailed link opens — a same-origin POST — never on submit and never on GET | Instant confirmation; confirming on the GET, which every link-scanning mail gateway would press | Booking spec §1, 2026-09-07 | |
diff --git a/internal/calendar/auth.go b/internal/calendar/auth.go| index baf95fd..da93b7c 100644 |
| --- a/internal/calendar/auth.go |
| +++ b/internal/calendar/auth.go |
| @@ -1,5 +1,7 @@ |
| -// Local verification uses an emailed single-use link. Optional Home sign-in |
| -// resolves an explicitly connected existing account; it never creates a person. |
| +// Local sign-in is Keymail for an address whose domain runs Keymail and an |
| +// emailed single-use link for every other address, decided by the domain |
| +// alone (beginSignin). Optional Home sign-in resolves an explicitly |
| +// connected existing account; it never creates a person. |
| package calendar |
| import ( |
| @@ -9,7 +11,6 @@ import ( |
| "database/sql" |
| "fmt" |
| "log/slog" |
| - "net/http" |
| "net/url" |
| "regexp" |
| "strings" |
| @@ -182,78 +183,16 @@ func resolveAllowlist(cfg Config) (allowlist, error) { |
| return allowlist{}, fmt.Errorf("calendar: $CALENDAR_ALLOWED_ADDRESSES is empty and Env is %q, not %q — refusing to start with no allowlist configured; set it to this instance's address(es)", cfg.Env, "development") |
| } |
| -// gateBegin wraps rauth.Auth.Begin so a non-permitted address never |
| -// reaches it. Begin is what sends the mail, while rauth.Config.Authorize |
| -// is checked afterwards, at the callback, once a link has already been |
| -// mailed and clicked — so gating only Authorize would leave this app's |
| -// mail-sending identity an open relay for any address a stranger types |
| -// into the form. |
| -// |
| -// A non-permitted address gets exactly the response Begin's own success |
| -// path sends: the same 303, to the same signinPath+"?sent=1", built the |
| -// same way. That is deliberate. Any observable difference — a different |
| -// status, a different body, even a differently-cased query string — |
| -// would turn this endpoint into a membership oracle, letting an |
| -// attacker learn which addresses this instance admits by watching how |
| -// its response to each one differs. |
| -// |
| -// force=1 is set unconditionally on every permitted request. Begin |
| -// otherwise auto-upgrades an address that resolves to a claimed keymail |
| -// inbox to the keymail ceremony, which redirects somewhere else |
| -// entirely — reopening the same oracle one level narrower, since an |
| -// attacker who suspects an address is keymail-hosted could tell "on the |
| -// allowlist" from "not" by which way the response went. This app never |
| -// wants that ceremony anyway (see the package comment), so forcing the |
| -// plain-link path here makes it a guarantee for every request this |
| -// handler forwards rather than only for the ones built by our own form. |
| -// The refusal is COUNTED IN THE LOG, without the address. |
| -// |
| -// The response has to stay silent; the log does not, and the two rules |
| -// that made this route undiagnosable were pulling in the same |
| -// direction only by accident. The oracle defence forbids telling the |
| -// CLIENT anything, and the logs rule (AGENTS.md §Logs) forbids writing |
| -// an ADDRESS anywhere. Neither forbids recording that a refusal |
| -// happened. Without this line a correctly-configured instance and one |
| -// whose allowlist is missing the only address anybody types are |
| -// indistinguishable from outside AND from `carlos logs`: the operator's |
| -// single remaining move is to read the environment variable and compare |
| -// it by eye, which is how this was actually found after somebody sat |
| -// waiting for a link that was never going to arrive. |
| -// |
| -// The count is the whole payload. "signin refused" with a running total |
| -// is enough to answer "is this instance refusing everything?", which is |
| -// the only question the log needs to answer, and it names nobody. |
| -func gateBegin(next http.HandlerFunc, list allowlist, signinPath string, logger *slog.Logger, refusals *atomic.Int64) http.HandlerFunc { |
| - return func(w http.ResponseWriter, r *http.Request) { |
| - // A malformed body reads back as address == "" below, which is |
| - // never on a non-empty allowlist — the same answer Begin would |
| - // itself reach, just reached before any mail could go out. |
| - _ = r.ParseForm() |
| - if list.allows(r.FormValue("address")) { |
| - if r.Form == nil { |
| - r.Form = url.Values{} |
| - } |
| - r.Form.Set("force", "1") |
| - next(w, r) |
| - return |
| - } |
| - if logger != nil { |
| - logger.Warn("calendar: signin refused by allowlist", |
| - "stage", "signin.gate", "refusals_since_boot", refusals.Add(1)) |
| - } |
| - http.Redirect(w, r, signinPath+"?sent=1", http.StatusSeeOther) |
| - } |
| -} |
| - |
| // newAuthPlugin builds the one *rauth.Auth this process shares. One per |
| // process, never one per request: the underlying flow carries its |
| // rate-limiter budget on the value, so a plugin per request would get a |
| // fresh empty budget every time — no rate limiting at all, silently. |
| // |
| -// Authorize is list.allows as well as gateBegin's gate. The two defend |
| -// different things: gateBegin stops the mail going out, Authorize stops |
| -// a link that was somehow minted for a non-permitted address (mailed |
| -// before the allowlist changed, say) from minting a session. |
| +// Authorize is list.allows as well as admissionMailer. The two defend |
| +// different things: admissionMailer stops the mail going out, Authorize |
| +// stops a session being minted for a non-permitted address, whether |
| +// Keymail verified it or a link was somehow minted for it (mailed |
| +// before the allowlist changed, say). |
| func newAuthPlugin(origin string, writer *sql.DB, instanceKey string, mailer mail.Sender, list allowlist, logger *slog.Logger, homeEnabled bool) (*rauth.Auth, error) { |
| signin, signedIn := "/signin", "/" |
| if homeEnabled { |
| @@ -265,7 +204,7 @@ func newAuthPlugin(origin string, writer *sql.DB, instanceKey string, mailer mai |
| SignedInPath: signedIn, |
| Origin: origin, |
| InstanceKey: instanceKey, |
| - Mailer: mailer, |
| + Mailer: admissionMailer{next: mailer, list: list, logger: logger, refusals: new(atomic.Int64)}, |
| Authorize: list.allows, |
| Subject: chrome.EmailSubject("Calendar"), |
| Logger: logger, |
diff --git a/internal/calendar/auth_keymail.go b/internal/calendar/auth_keymail.go| new file mode 100644 |
| index 0000000..bd037ba |
| --- /dev/null |
| +++ b/internal/calendar/auth_keymail.go |
| @@ -0,0 +1,138 @@ |
| +package calendar |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "log/slog" |
| + "net/http" |
| + "strings" |
| + "sync/atomic" |
| + |
| + "amadan.net/oficina/home/connect" |
| + "amadan.net/rastrillo/rastrillo/mail" |
| +) |
| + |
| +// beginSignin is POST /signin, in both modes: rauth's Begin for EVERY |
| +// address, under connect.OAuthContinuation. What the form answers |
| +// depends on the address's domain alone, never on the allowlist — any |
| +// difference between a permitted and a non-permitted address would |
| +// turn this endpoint into a membership oracle. |
| +// |
| +// - A Keymail address (keymail.dev itself, or a domain delegating to |
| +// Keymail with a `_keymail` TXT record), permitted or not, goes to |
| +// Keymail. Begin answers with a 303 to Keymail's authorize URL, |
| +// which OAuthContinuation turns into a page (renderKeymail): CSP's |
| +// form-action 'self' covers a form submission's whole redirect |
| +// chain in Safari, so a 303 out of the POST would be refused. |
| +// Admission is asked only after Keymail has verified the address, |
| +// by rauth's Authorize, and its refusal is the door saying so |
| +// (doorOnRefusal) — told only to someone who has just proved they |
| +// hold the address. |
| +// - Any other address is answered ?sent=1, and admissionMailer mails |
| +// the link only if the allowlist holds it, so this app's sending |
| +// identity is no open relay for whatever a stranger types. |
| +// |
| +// Both kinds of address spend the same rate budgets and parse the same |
| +// way. The one outcome only a permitted address can reach is ?err=1 |
| +// from a send that failed: an operational fault, not an answer. |
| +// |
| +// It used to gate the allowlist in front of Begin and set force=1 on |
| +// every permitted request, which kept Keymail out of Calendar |
| +// altogether. Paul ruled on 2026-10-06 that Calendar uses Keymail. |
| +// force now arrives only from the form rastrillo lands a failed |
| +// Keymail exchange on (?force=1&err=keymail), and asks for an emailed |
| +// link instead, so nobody is stuck. |
| +func beginSignin(origin string, begin http.HandlerFunc, render func(http.ResponseWriter, *http.Request, string)) http.HandlerFunc { |
| + return connect.OAuthContinuation(origin, begin, render) |
| +} |
| + |
| +// admissionMailer is the mail half of the allowlist: Begin runs for |
| +// every address, and this is where a non-permitted one is quietly not |
| +// mailed. rauth has stored an expiring token by then; one never |
| +// delivered is never redeemed, and Authorize would refuse it if it |
| +// were. |
| +// |
| +// The refusal is COUNTED IN THE LOG, without the address. The response |
| +// has to stay silent; the log does not. The oracle defence forbids |
| +// telling the CLIENT anything, and the logs rule (AGENTS.md §Logs) |
| +// forbids writing an ADDRESS anywhere, but neither forbids recording |
| +// that a refusal happened. Without this line a correctly-configured |
| +// instance and one whose allowlist is missing the only address anybody |
| +// types are indistinguishable from outside AND from `carlos logs`. |
| +type admissionMailer struct { |
| + next mail.Sender |
| + list allowlist |
| + logger *slog.Logger |
| + refusals *atomic.Int64 |
| +} |
| + |
| +func (m admissionMailer) Send(ctx context.Context, to, subject, body string) error { |
| + if !m.list.allows(to) { |
| + if m.logger != nil { |
| + m.logger.Warn("calendar: signin refused by allowlist", |
| + "stage", "signin.gate", "refusals_since_boot", m.refusals.Add(1)) |
| + } |
| + return nil |
| + } |
| + return m.next.Send(ctx, to, subject, body) |
| +} |
| + |
| +// authRefusal is the bare-text body rastrillo/auth's admit() writes, |
| +// with a 403, when a verified address is not admitted. rastrillo at the |
| +// version pinned here has no hook to render anything else, so |
| +// doorOnRefusal recognises this exact answer; TestKeymailRefusalIsTheDoor |
| +// pins it, so a bump that changes the sentence fails loudly. |
| +const authRefusal = "This address is verified but not admitted here." |
| + |
| +// doorOnRefusal wraps rauth's Callback and Verify, the handlers that end |
| +// in admission, and turns its bare-text refusal into the door: a 303 to |
| +// the local form with ?err=refused, which says the address cannot sign |
| +// in here and offers the form for a different one. Every other answer, |
| +// cookies included, passes through untouched. Remove it when rastrillo |
| +// has a refusal hook and the pin is bumped. |
| +func doorOnRefusal(next http.HandlerFunc, form string) http.HandlerFunc { |
| + return func(w http.ResponseWriter, r *http.Request) { |
| + rec := &bufferedResponse{header: make(http.Header)} |
| + next(rec, r) |
| + if rec.status == http.StatusForbidden && strings.TrimSpace(rec.body.String()) == authRefusal { |
| + for _, c := range rec.header.Values("Set-Cookie") { |
| + w.Header().Add("Set-Cookie", c) |
| + } |
| + w.Header().Set("Cache-Control", "no-store") |
| + http.Redirect(w, r, form+"?err=refused", http.StatusSeeOther) |
| + return |
| + } |
| + for name, values := range rec.header { |
| + for _, v := range values { |
| + w.Header().Add(name, v) |
| + } |
| + } |
| + if rec.status == 0 { |
| + rec.status = http.StatusOK |
| + } |
| + w.WriteHeader(rec.status) |
| + _, _ = w.Write(rec.body.Bytes()) |
| + } |
| +} |
| + |
| +// bufferedResponse holds a whole answer so doorOnRefusal can decide what |
| +// to send after seeing it. Callback and Verify answer with a redirect |
| +// or a line of text, never anything large. |
| +type bufferedResponse struct { |
| + header http.Header |
| + status int |
| + body bytes.Buffer |
| +} |
| + |
| +func (b *bufferedResponse) Header() http.Header { return b.header } |
| +func (b *bufferedResponse) WriteHeader(status int) { |
| + if b.status == 0 { |
| + b.status = status |
| + } |
| +} |
| +func (b *bufferedResponse) Write(p []byte) (int, error) { |
| + if b.status == 0 { |
| + b.status = http.StatusOK |
| + } |
| + return b.body.Write(p) |
| +} |
diff --git a/internal/calendar/keymail_signin_test.go b/internal/calendar/keymail_signin_test.go| new file mode 100644 |
| index 0000000..06e8013 |
| --- /dev/null |
| +++ b/internal/calendar/keymail_signin_test.go |
| @@ -0,0 +1,250 @@ |
| +package calendar |
| + |
| +import ( |
| + "bytes" |
| + "context" |
| + "encoding/base64" |
| + "encoding/json" |
| + "fmt" |
| + "html" |
| + "io" |
| + "log/slog" |
| + "net/http" |
| + "net/http/httptest" |
| + "net/url" |
| + "os" |
| + "path/filepath" |
| + "regexp" |
| + "strings" |
| + "sync" |
| + "testing" |
| + |
| + "amadan.net/oficina/calendar/internal/calendar/keymailtest" |
| + "amadan.net/oficina/home/connect" |
| + assertioncrypto "amadan.net/rastrillo/rastrillo/crypto" |
| +) |
| + |
| +// TestMain keeps Keymail classification inside the process: every DNS |
| +// query is answered NXDOMAIN and only the Keymail fixtures a test |
| +// registers answer HTTPS (keymailtest). |
| +func TestMain(m *testing.M) { |
| + restore, err := keymailtest.Install() |
| + if err != nil { |
| + fmt.Fprintln(os.Stderr, "keymailtest.Install:", err) |
| + os.Exit(1) |
| + } |
| + code := m.Run() |
| + restore() |
| + os.Exit(code) |
| +} |
| + |
| +const ( |
| + keymailHost = "keymail.calendar.test" |
| + keymailMember = "paul@" + keymailHost |
| + keymailStranger = "stranger@" + keymailHost |
| + plainMember = "paul@example.test" |
| +) |
| + |
| +// countingMailer remembers every address it was asked to write to. |
| +type countingMailer struct { |
| + mu sync.Mutex |
| + to []string |
| +} |
| + |
| +func (m *countingMailer) Send(_ context.Context, to, _, _ string) error { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + m.to = append(m.to, to) |
| + return nil |
| +} |
| + |
| +func (m *countingMailer) sent() []string { |
| + m.mu.Lock() |
| + defer m.mu.Unlock() |
| + return append([]string(nil), m.to...) |
| +} |
| + |
| +type keymailFixture struct { |
| + app *App |
| + origin string |
| + mail *countingMailer |
| + km *keymailtest.Server |
| +} |
| + |
| +// newKeymailFixture builds an app admitting plainMember and |
| +// keymailMember, beside a Keymail deployment holding keymailMember and |
| +// keymailStranger. home configures Home, which moves the local form to |
| +// /signin/local. |
| +func newKeymailFixture(t *testing.T, home bool) *keymailFixture { |
| + t.Helper() |
| + km := keymailtest.Serve(t, keymailHost, keymailMember, keymailStranger) |
| + mail := &countingMailer{} |
| + cfg := Config{DBPath: filepath.Join(t.TempDir(), "calendar.db"), Env: "development", Origin: TestOrigin, |
| + AllowedAddresses: plainMember + "," + keymailMember, Mailer: mail, |
| + Logger: slog.New(slog.NewTextHandler(io.Discard, nil))} |
| + if home { |
| + key, err := assertioncrypto.Generate() |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + manifest, _ := json.Marshal(map[string]string{"key": base64.StdEncoding.EncodeToString(key.SignPub())}) |
| + cfg.Origin = homeTestOrigin |
| + cfg.Home = &connect.Credentials{Issuer: homeTestIssuer, ConsumerID: "calendar-test", KeysBase64: base64.StdEncoding.EncodeToString(manifest), DEKBase64: base64.StdEncoding.EncodeToString(bytes.Repeat([]byte{7}, 32))} |
| + } |
| + a, err := New(cfg) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(func() { a.Close() }) |
| + return &keymailFixture{app: a, origin: cfg.Origin, mail: mail, km: km} |
| +} |
| + |
| +func (f *keymailFixture) post(form url.Values, cookies ...*http.Cookie) *httptest.ResponseRecorder { |
| + r := httptest.NewRequest(http.MethodPost, f.origin+"/signin", strings.NewReader(form.Encode())) |
| + r.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + r.Header.Set("Origin", f.origin) |
| + for _, c := range cookies { |
| + r.AddCookie(c) |
| + } |
| + w := httptest.NewRecorder() |
| + f.app.mux.ServeHTTP(w, r) |
| + return w |
| +} |
| + |
| +func (f *keymailFixture) get(path string, cookies ...*http.Cookie) *httptest.ResponseRecorder { |
| + r := httptest.NewRequest(http.MethodGet, f.origin+path, nil) |
| + for _, c := range cookies { |
| + r.AddCookie(c) |
| + } |
| + w := httptest.NewRecorder() |
| + f.app.mux.ServeHTTP(w, r) |
| + return w |
| +} |
| + |
| +var authorizeHref = regexp.MustCompile(`href="(https://` + regexp.QuoteMeta(keymailHost) + `/oauth/authorize\?[^"]+)"`) |
| + |
| +// continuation asserts rec is the page between the form and Keymail — |
| +// a 200 document with a meta refresh, never a 303 out of the form POST |
| +// (Safari applies form-action to that redirect) — and returns the |
| +// authorize URL it carries. |
| +func continuation(t *testing.T, label string, rec *httptest.ResponseRecorder) *url.URL { |
| + t.Helper() |
| + if rec.Code != http.StatusOK || rec.Header().Get("Location") != "" { |
| + t.Fatalf("%s: %d %q, want 200 and the continuation page to Keymail", label, rec.Code, rec.Header().Get("Location")) |
| + } |
| + body := rec.Body.String() |
| + m := authorizeHref.FindStringSubmatch(body) |
| + if m == nil || !strings.Contains(body, `http-equiv="refresh"`) { |
| + t.Fatalf("%s: no Keymail continuation on the page:\n%s", label, body) |
| + } |
| + u, err := url.Parse(html.UnescapeString(m[1])) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + return u |
| +} |
| + |
| +// TestKeymailAddressGoesToKeymailWhetherPermittedOrNot: in both modes, |
| +// whether an address goes to Keymail depends on its domain alone. A |
| +// permitted and a non-permitted Keymail address get the same first |
| +// answer, the continuation page, and neither is mailed. Before, every |
| +// permitted address was forced to an emailed link and a non-permitted |
| +// one was answered ?sent=1. |
| +func TestKeymailAddressGoesToKeymailWhetherPermittedOrNot(t *testing.T) { |
| + for _, home := range []bool{false, true} { |
| + t.Run(fmt.Sprintf("home=%v", home), func(t *testing.T) { |
| + f := newKeymailFixture(t, home) |
| + member := f.post(url.Values{"address": {keymailMember}}) |
| + stranger := f.post(url.Values{"address": {keymailStranger}}) |
| + mu := continuation(t, "permitted Keymail address", member) |
| + su := continuation(t, "non-permitted Keymail address", stranger) |
| + mask := func(rec *httptest.ResponseRecorder, u *url.URL) string { |
| + return strings.ReplaceAll(rec.Body.String(), html.EscapeString(u.String()), "AUTHORIZE") |
| + } |
| + if a, b := mask(member, mu), mask(stranger, su); a != b { |
| + t.Errorf("the two Keymail answers differ beyond the authorize URL:\n%s\n----\n%s", a, b) |
| + } |
| + if got := f.mail.sent(); len(got) != 0 { |
| + t.Errorf("a Keymail address was mailed: %v", got) |
| + } |
| + if n := f.km.Lookups(); n != 2 { |
| + t.Errorf("Keymail saw %d lookups, want 2", n) |
| + } |
| + }) |
| + } |
| +} |
| + |
| +// TestNonPermittedPlainAddressIsAnsweredSentAndNotMailed: an address |
| +// with no Keymail gets ?sent=1, permitted or not; only the permitted |
| +// one is mailed. |
| +func TestNonPermittedPlainAddressIsAnsweredSentAndNotMailed(t *testing.T) { |
| + f := newKeymailFixture(t, false) |
| + for _, address := range []string{"someone@else.test", plainMember} { |
| + rec := f.post(url.Values{"address": {address}}) |
| + if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/signin?sent=1" { |
| + t.Fatalf("POST /signin %q: %d %q, want 303 /signin?sent=1", address, rec.Code, rec.Header().Get("Location")) |
| + } |
| + } |
| + if got := f.mail.sent(); len(got) != 1 || got[0] != plainMember { |
| + t.Fatalf("mail = %v, want one, to %s", got, plainMember) |
| + } |
| +} |
| + |
| +// TestKeymailFailureFallsBackToAnEmailLink: the page rastrillo lands a |
| +// failed Keymail exchange on (?force=1&err=keymail) carries force, so |
| +// the retry mails a link instead of returning to Keymail; the ordinary |
| +// form carries none. |
| +func TestKeymailFailureFallsBackToAnEmailLink(t *testing.T) { |
| + f := newKeymailFixture(t, false) |
| + forced := `name="force" value="1"` |
| + if strings.Contains(f.get("/signin").Body.String(), forced) { |
| + t.Fatal("the ordinary form forces an email link") |
| + } |
| + if !strings.Contains(f.get("/signin?force=1&err=keymail").Body.String(), forced) { |
| + t.Fatal("the err=keymail form does not carry force; a failed Keymail sign-in would loop back to Keymail") |
| + } |
| + rec := f.post(url.Values{"address": {keymailMember}, "force": {"1"}}) |
| + if rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/signin?sent=1" { |
| + t.Fatalf("forced POST: %d %q", rec.Code, rec.Header().Get("Location")) |
| + } |
| + if got := f.mail.sent(); len(got) != 1 || got[0] != keymailMember { |
| + t.Fatalf("mail = %v, want one link to %s", got, keymailMember) |
| + } |
| + if f.km.Lookups() != 0 { |
| + t.Error("a forced sign-in classified the address") |
| + } |
| +} |
| + |
| +// TestKeymailRefusalIsTheDoor: a non-permitted address Keymail verified |
| +// is refused after verification on the door, with the form for a |
| +// different address, not in rastrillo's bare text; an admitted one is |
| +// signed in. Both modes. |
| +func TestKeymailRefusalIsTheDoor(t *testing.T) { |
| + for _, home := range []bool{false, true} { |
| + t.Run(fmt.Sprintf("home=%v", home), func(t *testing.T) { |
| + f := newKeymailFixture(t, home) |
| + form := "/signin" |
| + if home { |
| + form = "/signin/local" |
| + } |
| + roundTrip := func(address string) *httptest.ResponseRecorder { |
| + begin := f.post(url.Values{"address": {address}}) |
| + u := continuation(t, address, begin) |
| + return f.get("/auth/callback?"+url.Values{"state": {u.Query().Get("state")}, "code": {f.km.Approve(address)}}.Encode(), begin.Result().Cookies()...) |
| + } |
| + if cb := roundTrip(keymailMember); cb.Code != http.StatusSeeOther || strings.Contains(cb.Header().Get("Location"), "err=") { |
| + t.Fatalf("permitted callback: %d %q", cb.Code, cb.Header().Get("Location")) |
| + } |
| + cb := roundTrip(keymailStranger) |
| + if cb.Code != http.StatusSeeOther || cb.Header().Get("Location") != form+"?err=refused" { |
| + t.Fatalf("non-permitted callback: %d %q, want 303 %s?err=refused (bare text is the bug)\n%s", cb.Code, cb.Header().Get("Location"), form, cb.Body.String()) |
| + } |
| + door := f.get(form + "?err=refused").Body.String() |
| + for _, want := range []string{"estilo-door", `name="address"`, "can’t sign in to Calendar"} { |
| + if !strings.Contains(door, want) { |
| + t.Errorf("refusal door lacks %q:\n%s", want, door) |
| + } |
| + } |
| + }) |
| + } |
| +} |
diff --git a/internal/calendar/keymailtest/keymailtest.go b/internal/calendar/keymailtest/keymailtest.go| new file mode 100644 |
| index 0000000..92ad056 |
| --- /dev/null |
| +++ b/internal/calendar/keymailtest/keymailtest.go |
| @@ -0,0 +1,190 @@ |
| +// Package keymailtest keeps sign-in's Keymail classification inside the |
| +// test process. It is imported by tests only. |
| +// |
| +// rastrillo/auth (at the version this app pins) builds its classifier |
| +// with no seams: TXT lookups go through net.DefaultResolver and the |
| +// well-known probe, the federation lookup and the token exchange go |
| +// through http.DefaultTransport. So those two globals are the hooks, |
| +// exactly as oficina/docs' auth_keymail_test.go uses them. Install |
| +// replaces both for the life of the test binary: |
| +// |
| +// - every DNS query is answered NXDOMAIN by a resolver on loopback, |
| +// so no DNS packet leaves the process, and a domain with no |
| +// `_keymail` record is probed directly — keymail.dev's own shape; |
| +// - an https request to a host registered with Serve is answered |
| +// in-process by that fixture; anything else falls through to the |
| +// real transport, where the resolver above makes a name |
| +// unreachable (IP literals, which httptest servers use, still work). |
| +// |
| +// Every address at a domain nobody registered therefore classifies as |
| +// "not Keymail", which is what every pre-existing sign-in test assumes. |
| +package keymailtest |
| + |
| +import ( |
| + "context" |
| + "crypto/rand" |
| + "encoding/hex" |
| + "encoding/json" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "strings" |
| + "sync" |
| + "time" |
| +) |
| + |
| +var ( |
| + mu sync.Mutex |
| + servers = map[string]*Server{} |
| +) |
| + |
| +// Install swaps net.DefaultResolver and http.DefaultTransport for the |
| +// stubs described in the package comment and returns a function that |
| +// puts them back. Call it once, from TestMain. |
| +func Install() (restore func(), err error) { |
| + dns, err := net.ListenPacket("udp", "127.0.0.1:0") |
| + if err != nil { |
| + return nil, err |
| + } |
| + go answerNXDOMAIN(dns) |
| + oldResolver, oldTransport := net.DefaultResolver, http.DefaultTransport |
| + net.DefaultResolver = &net.Resolver{PreferGo: true, Dial: func(ctx context.Context, _, _ string) (net.Conn, error) { |
| + return (&net.Dialer{}).DialContext(ctx, "udp", dns.LocalAddr().String()) |
| + }} |
| + http.DefaultTransport = transport{next: oldTransport} |
| + return func() { |
| + net.DefaultResolver, http.DefaultTransport = oldResolver, oldTransport |
| + _ = dns.Close() |
| + }, nil |
| +} |
| + |
| +// answerNXDOMAIN echoes each query back as a "no such name" answer. |
| +func answerNXDOMAIN(conn net.PacketConn) { |
| + b := make([]byte, 4096) |
| + for { |
| + n, addr, err := conn.ReadFrom(b) |
| + if err != nil { |
| + return |
| + } |
| + if n < 12 { |
| + continue |
| + } |
| + reply := append([]byte(nil), b[:n]...) |
| + reply[2], reply[3] = 0x81, 0x83 // response, recursion, NXDOMAIN |
| + for i := 6; i < 12; i++ { |
| + reply[i] = 0 // no answer, authority or additional records |
| + } |
| + _, _ = conn.WriteTo(reply, addr) |
| + } |
| +} |
| + |
| +type transport struct{ next http.RoundTripper } |
| + |
| +func (t transport) RoundTrip(r *http.Request) (*http.Response, error) { |
| + mu.Lock() |
| + s := servers[r.URL.Host] |
| + mu.Unlock() |
| + if s == nil || r.URL.Scheme != "https" { |
| + return t.next.RoundTrip(r) |
| + } |
| + rec := httptest.NewRecorder() |
| + s.ServeHTTP(rec, r) |
| + res := rec.Result() |
| + res.Request = r |
| + return res, nil |
| +} |
| + |
| +// Server is one Keymail deployment at one host: the well-known |
| +// document, the federation lookup for the accounts it holds, and the |
| +// token exchange for the codes Approve hands out. |
| +type Server struct { |
| + host string |
| + |
| + mu sync.Mutex |
| + accounts map[string]bool |
| + codes map[string]string |
| + lookups int |
| + tokens int |
| +} |
| + |
| +// Serve registers a Keymail deployment at host (which is also the |
| +// address domain it answers for, since nothing publishes a `_keymail` |
| +// record) holding the given accounts. It is unregistered when the test |
| +// ends. |
| +func Serve(t interface{ Cleanup(func()) }, host string, accounts ...string) *Server { |
| + s := &Server{host: host, accounts: map[string]bool{}, codes: map[string]string{}} |
| + for _, a := range accounts { |
| + s.accounts[strings.ToLower(a)] = true |
| + } |
| + mu.Lock() |
| + servers[host] = s |
| + mu.Unlock() |
| + t.Cleanup(func() { |
| + mu.Lock() |
| + delete(servers, host) |
| + mu.Unlock() |
| + }) |
| + return s |
| +} |
| + |
| +// Approve is Keymail's consent screen saying yes for address: it |
| +// returns the code the browser would carry back to /auth/callback. |
| +func (s *Server) Approve(address string) string { |
| + var b [12]byte |
| + _, _ = rand.Read(b[:]) |
| + code := hex.EncodeToString(b[:]) |
| + s.mu.Lock() |
| + s.codes[code] = address |
| + s.mu.Unlock() |
| + return code |
| +} |
| + |
| +// Lookups is how many federation lookups reached this deployment. |
| +func (s *Server) Lookups() int { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + return s.lookups |
| +} |
| + |
| +// Tokens is how many token exchanges reached this deployment. |
| +func (s *Server) Tokens() int { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + return s.tokens |
| +} |
| + |
| +func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Content-Type", "application/json") |
| + switch r.URL.Path { |
| + case "/.well-known/keymail": |
| + _ = json.NewEncoder(w).Encode(map[string]any{"version": "1", "reauth": true}) |
| + case "/api/federation/lookup": |
| + s.mu.Lock() |
| + s.lookups++ |
| + ok := s.accounts[strings.ToLower(r.URL.Query().Get("addr"))] |
| + s.mu.Unlock() |
| + if !ok { |
| + w.WriteHeader(http.StatusNotFound) |
| + } |
| + _ = json.NewEncoder(w).Encode(map[string]bool{"ok": ok}) |
| + case "/api/oauth/token": |
| + var in map[string]string |
| + _ = json.NewDecoder(r.Body).Decode(&in) |
| + s.mu.Lock() |
| + s.tokens++ |
| + address, ok := s.codes[in["code"]] |
| + delete(s.codes, in["code"]) |
| + s.mu.Unlock() |
| + if r.Method != http.MethodPost || !ok { |
| + w.WriteHeader(http.StatusBadRequest) |
| + _ = json.NewEncoder(w).Encode(map[string]string{"error": "invalid_grant"}) |
| + return |
| + } |
| + _ = json.NewEncoder(w).Encode(map[string]any{ |
| + "access_token": "synthetic", "token_type": "bearer", |
| + "address": address, "auth_time": time.Now().Unix(), |
| + }) |
| + default: |
| + w.WriteHeader(http.StatusNotFound) |
| + } |
| +} |
diff --git a/internal/calendar/render.go b/internal/calendar/render.go| index 5af6b8a..f01e82a 100644 |
| --- a/internal/calendar/render.go |
| +++ b/internal/calendar/render.go |
| @@ -68,7 +68,9 @@ func init() { |
| t = template.Must(t.ParseFS(appFS, "templates/layout.html", "templates/_chip.html", |
| "templates/_quickadd.html", "templates/_quickpane.html", "templates/_bookingpane.html", |
| "templates/"+name+".html")) |
| - t = template.Must(t.ParseFS(connect.Templates(), "templates/home_link.html")) |
| + // home_link for the account pages; oauth for the Keymail |
| + // continuation's meta refresh (home-oauth-head) on signin. |
| + t = template.Must(t.ParseFS(connect.Templates(), "templates/home_link.html", "templates/oauth.html")) |
| pages[name] = template.Must(t.ParseFS(credits.Templates(), "templates/*.html")) |
| } |
| } |
diff --git a/internal/calendar/routes.go b/internal/calendar/routes.go| index 421decf..5f0cf92 100644 |
| --- a/internal/calendar/routes.go |
| +++ b/internal/calendar/routes.go |
| @@ -6,7 +6,6 @@ import ( |
| "amadan.net/oficina/home/connect" |
| "amadan.net/oficina/home/handoff" |
| "net/http" |
| - "sync/atomic" |
| "github.com/go-chi/chi/v5" |
| @@ -58,25 +57,22 @@ func (a *App) routes(h *handlers, authPlugin *rauth.Auth, list allowlist, origin |
| r.Get("/signin", h.signin) |
| r.Get("/signed-out", h.signedOut) |
| } |
| - // One counter for the life of the router, so the log line can say |
| - // how many refusals this boot has seen rather than only that one |
| - // happened. routes runs once per App, so the closure below is the |
| - // only holder and no reset can race it. |
| - var refusals atomic.Int64 |
| signinPath := "/signin" |
| if a.home != nil { |
| signinPath = "/signin/local" |
| } |
| - begin := gateBegin(authPlugin.Begin, list, signinPath, a.logger, &refusals) |
| + begin := beginSignin(origin, authPlugin.Begin, h.renderKeymail) |
| + callback := doorOnRefusal(authPlugin.Callback, signinPath) |
| + verify := doorOnRefusal(authPlugin.Verify, signinPath) |
| if a.home != nil { |
| r.Post("/signin", a.home.routes.LocalGuard(begin)) |
| - r.Get("/auth/callback", a.home.routes.LocalGuard(authPlugin.Callback)) |
| - r.Get("/auth/verify", a.home.routes.LocalGuard(authPlugin.Verify)) |
| + r.Get("/auth/callback", a.home.routes.LocalGuard(callback)) |
| + r.Get("/auth/verify", a.home.routes.LocalGuard(verify)) |
| r.Post("/signout", a.home.routes.Signout) |
| } else { |
| r.Post("/signin", begin) |
| - r.Get("/auth/callback", authPlugin.Callback) |
| - r.Get("/auth/verify", authPlugin.Verify) |
| + r.Get("/auth/callback", callback) |
| + r.Get("/auth/verify", verify) |
| r.Post("/signout", signOutToSignedOut(authPlugin.Signout)) |
| } |
diff --git a/internal/calendar/signin.go b/internal/calendar/signin.go| index 5bee915..09261ea 100644 |
| --- a/internal/calendar/signin.go |
| +++ b/internal/calendar/signin.go |
| @@ -5,6 +5,7 @@ import ( |
| "amadan.net/oficina/estilo.git/chrome" |
| "amadan.net/oficina/estilo.git/sky" |
| + "amadan.net/oficina/home/connect" |
| ) |
| // The sign-in pages are the Oficina door (estilo chrome): one card on the |
| @@ -37,6 +38,12 @@ func (h *handlers) signin(w http.ResponseWriter, r *http.Request) { |
| Action: "/signin", |
| OpenSource: &chrome.Link{Href: "/help/open-source", Label: "Open source"}, |
| } |
| + if q.Get("force") != "" { |
| + // A failed Keymail exchange lands here as ?force=1&err=keymail. |
| + // Posting force back asks for an emailed link instead, so the |
| + // retry does not return to the Keymail that just failed. |
| + form.Hidden = []chrome.Hidden{{Name: "force", Value: "1"}} |
| + } |
| switch q.Get("err") { |
| case "": |
| case "rate": |
| @@ -45,6 +52,12 @@ func (h *handlers) signin(w http.ResponseWriter, r *http.Request) { |
| form.AddressError = "That does not look like an email address." |
| case "expired": |
| form.Error = "That link has expired. Ask for a new one." |
| + case "keymail": |
| + form.Error = "Your Keymail sign-in couldn’t be completed. Enter your email to get a link instead." |
| + case "refused": |
| + // Keymail or a link verified the address and the allowlist does |
| + // not hold it (doorOnRefusal). The form is the way on. |
| + form.Error = "That address can’t sign in to Calendar. Use a different address, or ask whoever runs this team to add it." |
| default: |
| form.Error = "That link did not work. Ask for a new one." |
| } |
| @@ -67,11 +80,28 @@ func (h *handlers) signin(w http.ResponseWriter, r *http.Request) { |
| } |
| // signinData is the sign-in page's own view data: exactly one of the |
| -// three door cards. |
| +// door cards. Continue is set beside Sent on the page between the form |
| +// and Keymail (renderKeymail): its meta refresh goes on to Keymail. |
| type signinData struct { |
| Form *chrome.SignIn |
| Sent *chrome.SignInNotice |
| SignedOut *chrome.SignInNotice |
| + Continue *connect.OAuthData |
| +} |
| + |
| +// renderKeymail is the page between the form and Keymail, in both modes |
| +// (beginSignin): the door's own card saying where the person is going, |
| +// a meta refresh that goes there by itself, and a link that does when |
| +// the refresh is blocked. A navigation from a page, unlike a redirect |
| +// from a form POST, is outside form-action. |
| +func (h *handlers) renderKeymail(w http.ResponseWriter, r *http.Request, destination string) { |
| + p := connect.OAuthPage(destination) |
| + notice := chrome.SignInNotice{ |
| + Icon: assets.Path("static/brand/icon.svg"), App: "Calendar", Sky: sky.For(r.Host), |
| + Heading: p.Title, Body: "Taking you to Keymail to finish signing in.", |
| + Link: &chrome.Link{Href: p.URL, Label: p.ActionLabel}, |
| + } |
| + render(w, "signin", h.page(r, p.Title, signinData{Sent: ¬ice, Continue: &p})) |
| } |
| // signedOutDoor is where Home sign-out lands, drawn as the door: the |
diff --git a/internal/calendar/templates/signin.html b/internal/calendar/templates/signin.html| index 0eac71b..6668e24 100644 |
| --- a/internal/calendar/templates/signin.html |
| +++ b/internal/calendar/templates/signin.html |
| @@ -1,8 +1,10 @@ |
| {{define "title"}}{{.Title}}{{end}} |
| {{/* The Oficina door (estilo chrome). Exactly one card: the form, the |
| - check-your-email notice, or where Home sign-out lands. The form posts |
| - its address as "address", the name gateBegin and the auth plugin |
| - read. */}} |
| + check-your-email notice, the card between the form and Keymail (with |
| + .Data.Continue's meta refresh in head), or where Home sign-out lands. |
| + The form posts its address as "address", the name the auth plugin |
| + reads. */}} |
| +{{define "head"}}{{with .Data.Continue}}{{template "home-oauth-head" .}}{{end}}{{end}} |
| {{define "content"}} |
| {{- with .Data.Form}}{{template "estilo-signin" .}}{{end}} |
| {{- with .Data.Sent}}{{template "estilo-signin-sent" .}}{{end}} |