carlos / platform Public

console: one sign-in tail for both doors, and a safe next

Co-Authored-By: Claude <noreply@anthropic.com>
claude agent, operated by paul@keymail.dev e364f02b49dcc9be9570da2c5c069b676e83b44b parent 583facd
3 files changed, +237 −20
  • internal/console/emailsignin.go +76 −0
  • internal/console/emailsignin_test.go +149 −0
  • internal/console/server.go +12 −20
diff --git a/internal/console/emailsignin.go b/internal/console/emailsignin.go
new file mode 100644
index 000000000..a6eecdd2a
--- /dev/null
+++ b/internal/console/emailsignin.go
@@ -0,0 +1,76 @@
+package console
+
+import (
+ "log"
+ "net/http"
+ "net/url"
+ "strings"
+ "time"
+)
+
+// nextCookie carries a safe return path across the Keymail round trip, beside
+// the auth cookie. (An email sign-in keeps its next on the challenge row.)
+const nextCookie = "carlos_console_next"
+
+// safeNext returns raw when it is a local path and "" otherwise: it starts
+// with "/", not "//", has no backslash, and parses with no scheme or host.
+// Anything else is dropped silently and the usual landing applies.
+func safeNext(raw string) string {
+ if !strings.HasPrefix(raw, "/") || strings.HasPrefix(raw, "//") || strings.Contains(raw, `\`) {
+ return ""
+ }
+ u, err := url.Parse(raw)
+ if err != nil || u.Scheme != "" || u.Host != "" {
+ return ""
+ }
+ return raw
+}
+
+// finishSignin is what signing in does once a door has proved an address,
+// shared by the Keymail callback and the email link and code handlers: record
+// the user, store the Keymail grant (Keymail only), open a session that
+// remembers its method, set the cookies, then land. An email sign-in also
+// records a step-up at the moment of use, the same proof a step-up would ask
+// for minutes later. The current account is resolved (minted for a new user)
+// before any redirect, so onboarding runs before next.
+func (s *Server) finishSignin(w http.ResponseWriter, r *http.Request, addr, keymailToken, method, next string) {
+ now := time.Now()
+ created, err := s.store.EnsureUser(addr, now)
+ if err != nil {
+ s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not record your account. Please try again.")
+ return
+ }
+ if keymailToken != "" {
+ if err := s.store.SetGrantToken(addr, keymailToken, now); err != nil {
+ s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not store your sign-in grant. Please try again.")
+ return
+ }
+ }
+ raw, err := s.store.CreateSessionMethod(addr, keymailToken, method, now)
+ if err != nil {
+ s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not create your session. Please try again.")
+ return
+ }
+ s.clearCookie(w, authCookie)
+ s.setCookie(w, sessionCookie, raw, int(SessionTTL.Seconds()))
+ if created {
+ s.setCookie(w, welcomeCookie, "1", 300)
+ }
+ if method == MethodEmail {
+ if err := s.store.RecordStepUp(raw, addr, now, now); err != nil {
+ // Not fatal: the session is good, and the first sensitive action
+ // will ask for a fresh proof.
+ log.Printf("console: step-up record for %s: %v", addr, err)
+ }
+ }
+ if n := safeNext(next); n != "" {
+ if _, err := s.currentAccount(r.Context(), addr); err != nil {
+ log.Printf("console: landing for %s: %v", addr, err)
+ s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not open your account. Please try again.")
+ return
+ }
+ http.Redirect(w, r, n, http.StatusSeeOther)
+ return
+ }
+ s.redirectToCurrentAccount(w, r, addr, http.StatusSeeOther)
+}
diff --git a/internal/console/emailsignin_test.go b/internal/console/emailsignin_test.go
new file mode 100644
index 000000000..f4ee364e7
--- /dev/null
+++ b/internal/console/emailsignin_test.go
@@ -0,0 +1,149 @@
+package console
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "net/url"
+ "testing"
+ "time"
+)
+
+func TestSafeNext(t *testing.T) {
+ for _, tc := range []struct{ in, want string }{
+ {"/auth/cli", "/auth/cli"},
+ {"/invite/abc", "/invite/abc"},
+ {"/invite/abc?x=1", "/invite/abc?x=1"},
+ {"//evil.com", ""},
+ {"/\\evil.com", ""},
+ {"https://evil.com/x", ""},
+ {"javascript:alert(1)", ""},
+ {"evil.com", ""},
+ {"/a\nb", ""},
+ {"", ""},
+ } {
+ if got := safeNext(tc.in); got != tc.want {
+ t.Errorf("safeNext(%q) = %q, want %q", tc.in, got, tc.want)
+ }
+ }
+}
+
+// keymailWalk starts /auth/signin with the given query and answers the
+// callback, returning the callback's status and Location.
+func keymailWalk(t *testing.T, fx *consoleFixture, c *http.Client, signinQuery, code string) (int, string) {
+ t.Helper()
+ status, loc, _ := get(t, c, fx.ts.URL+"/auth/signin"+signinQuery)
+ if status != http.StatusSeeOther {
+ t.Fatalf("signin = %d, want 303", status)
+ }
+ u, err := url.Parse(loc)
+ if err != nil {
+ t.Fatal(err)
+ }
+ q := u.Query()
+ fx.fk.mu.Lock()
+ fx.fk.challenge = q.Get("code_challenge")
+ fx.fk.expectCode = code
+ fx.fk.mu.Unlock()
+ status, loc, _ = get(t, c, fx.ts.URL+"/auth/callback?code="+url.QueryEscape(code)+"&state="+url.QueryEscape(q.Get("state")))
+ return status, loc
+}
+
+func browserCookie(t *testing.T, fx *consoleFixture, c *http.Client, name string) string {
+ t.Helper()
+ u, _ := url.Parse(fx.ts.URL)
+ for _, ck := range c.Jar.Cookies(u) {
+ if ck.Name == name {
+ return ck.Value
+ }
+ }
+ return ""
+}
+
+func TestKeymailCallbackFollowsNext(t *testing.T) {
+ fx := newConsoleFixture(t)
+ fx.setUser("newcomer@keymail.dev")
+ c := newBrowser(t)
+
+ status, loc := keymailWalk(t, fx, c, "?next="+url.QueryEscape("/auth/cli"), "code-n1")
+ if status != http.StatusSeeOther || loc != "/auth/cli" {
+ t.Fatalf("callback = %d -> %q, want 303 -> /auth/cli", status, loc)
+ }
+ if v := browserCookie(t, fx, c, nextCookie); v != "" {
+ t.Fatalf("next cookie survived the callback: %q", v)
+ }
+ raw := sessionToken(t, fx, c)
+ addr, method, ok := fx.st.SessionInfo(raw, time.Now())
+ if !ok || addr != "newcomer@keymail.dev" || method != MethodKeymail {
+ t.Fatalf("session = %q %q %v, want newcomer keymail", addr, method, ok)
+ }
+ // Onboarding ran before next: the brand-new user has a personal account.
+ accts, err := fx.st.AccountsFor("newcomer@keymail.dev")
+ if err != nil || len(accts) == 0 {
+ t.Fatalf("accounts for a brand-new user = %v, %v; want a minted personal account", accts, err)
+ }
+ // A keymail sign-in records no step-up.
+ if fx.st.FreshStepUp(raw, "newcomer@keymail.dev", time.Now(), StepUpWindow) {
+ t.Fatal("a keymail sign-in recorded a step-up")
+ }
+}
+
+func TestKeymailCallbackIgnoresUnsafeAndStaleNext(t *testing.T) {
+ fx := newConsoleFixture(t)
+ c := newBrowser(t)
+
+ // An unsafe next is never stored, and the usual landing applies.
+ status, _, _ := get(t, c, fx.ts.URL+"/auth/signin?next="+url.QueryEscape("//evil.com"))
+ if status != http.StatusSeeOther {
+ t.Fatalf("signin = %d", status)
+ }
+ if v := browserCookie(t, fx, c, nextCookie); v != "" {
+ t.Fatalf("unsafe next was stored: %q", v)
+ }
+
+ // A stale safe next is cleared by a later signin without one.
+ get(t, c, fx.ts.URL+"/auth/signin?next=/auth/cli")
+ if v := browserCookie(t, fx, c, nextCookie); v != "/auth/cli" {
+ t.Fatalf("next cookie = %q, want /auth/cli", v)
+ }
+ status, loc := keymailWalk(t, fx, c, "", "code-n2")
+ if status != http.StatusSeeOther || len(loc) < 3 || loc[:3] != "/a/" {
+ t.Fatalf("callback with no next = %d -> %q, want 303 into an account", status, loc)
+ }
+}
+
+func TestFinishSigninEmailRecordsStepUp(t *testing.T) {
+ fx := newConsoleFixture(t)
+ w := httptest.NewRecorder()
+ r := httptest.NewRequest(http.MethodGet, "/", nil)
+ fx.srv.finishSignin(w, r, "bob@example.com", "", MethodEmail, "/invite/abc")
+ res := w.Result()
+ if res.StatusCode != http.StatusSeeOther || res.Header.Get("Location") != "/invite/abc" {
+ t.Fatalf("finishSignin = %d -> %q", res.StatusCode, res.Header.Get("Location"))
+ }
+ var raw string
+ var welcomed bool
+ for _, ck := range res.Cookies() {
+ switch ck.Name {
+ case sessionCookie:
+ raw = ck.Value
+ case welcomeCookie:
+ welcomed = true
+ }
+ }
+ if raw == "" || !welcomed {
+ t.Fatalf("cookies: session %q, welcome %v", raw, welcomed)
+ }
+ addr, method, ok := fx.st.SessionInfo(raw, time.Now())
+ if !ok || addr != "bob@example.com" || method != MethodEmail {
+ t.Fatalf("session = %q %q %v", addr, method, ok)
+ }
+ if !fx.st.FreshStepUp(raw, "bob@example.com", time.Now(), StepUpWindow) {
+ t.Fatal("an email sign-in recorded no step-up")
+ }
+ if g, _ := fx.st.GrantToken("bob@example.com"); g != "" {
+ t.Fatalf("an email sign-in stored a grant token %q", g)
+ }
+ if accts, err := fx.st.AccountsFor("bob@example.com"); err != nil || len(accts) == 0 {
+ t.Fatalf("no personal account minted: %v, %v", accts, err)
+ }
+}
diff --git a/internal/console/server.go b/internal/console/server.go
index ae055b028..d0c0d724a 100644
--- a/internal/console/server.go
+++ b/internal/console/server.go
@@ -2789,6 +2789,13 @@ func (s *Server) handleSignin(w http.ResponseWriter, r *http.Request) {
return
}
s.setCookie(w, authCookie, state+"."+verifier, int(authFlowTTL.Seconds()))
+ // Where to land afterwards. Only a safe local path is kept; a stale one
+ // from an earlier attempt must not leak into this one.
+ if n := safeNext(r.URL.Query().Get("next")); n != "" {
+ s.setCookie(w, nextCookie, n, int(authFlowTTL.Seconds()))
+ } else {
+ s.clearCookie(w, nextCookie)
+ }
http.Redirect(w, r, s.km.AuthorizeURL(state, ChallengeS256(verifier)), http.StatusSeeOther)
}
@@ -2830,27 +2837,12 @@ func (s *Server) handleCallback(w http.ResponseWriter, r *http.Request) {
"Keymail did not accept the sign-in. Please start again.")
return
}
- now := time.Now()
- created, err := s.store.EnsureUser(address, now)
- if err != nil {
- s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not record your account. Please try again.")
- return
- }
- if err := s.store.SetGrantToken(address, token, now); err != nil {
- s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not store your sign-in grant. Please try again.")
- return
- }
- raw, err := s.store.CreateSession(address, token, now)
- if err != nil {
- s.renderMessage(w, r, http.StatusInternalServerError, "Error", "Could not create your session. Please try again.")
- return
- }
- s.clearCookie(w, authCookie)
- s.setCookie(w, sessionCookie, raw, int(SessionTTL.Seconds()))
- if created {
- s.setCookie(w, welcomeCookie, "1", 300)
+ var next string
+ if nc, err := r.Cookie(nextCookie); err == nil {
+ next = nc.Value
}
- s.redirectToCurrentAccount(w, r, address, http.StatusSeeOther)
+ s.clearCookie(w, nextCookie)
+ s.finishSignin(w, r, address, token, MethodKeymail, next)
}
// handleConfirm consumes a returning-sign-in confirmation link. The token is