Sign in to Base with email or Keymail
Add web.App on chi: sign-in page, magic-link confirm page, sign-out and a member gate in front of "/". Only members (the owner, or invited people) are admitted; a first sign-in marks the member joined. Strangers who prove an address are sent back to /signin with a refusal. Every route sits behind csrf.Protect. Adds BASE_INSTANCE_KEY to config for sealing sign-in state.
Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
11 files changed,
+593
−6
cmd/base/main.go+15 −5docs/copy-pending.md+30 −0go.mod+4 −1go.sum+2 −0internal/config/config.go+4 −0internal/web/app.go+163 −0internal/web/signin.go+50 −0internal/web/templates/confirm.html+11 −0internal/web/templates/signin.html+23 −0internal/webtest/harness_test.go+208 −0internal/webtest/signin_test.go+83 −0
diff --git a/cmd/base/main.go b/cmd/base/main.go| index 1a4447e..d072a03 100644 |
| --- a/cmd/base/main.go |
| +++ b/cmd/base/main.go |
| @@ -2,7 +2,6 @@ package main |
| import ( |
| "context" |
| - "fmt" |
| "log/slog" |
| "net/http" |
| "os" |
| @@ -10,10 +9,12 @@ import ( |
| "amadan.net/rastrillo/rastrillo" |
| "amadan.net/rastrillo/rastrillo/db" |
| _ "amadan.net/rastrillo/rastrillo/locales/en" |
| + "amadan.net/rastrillo/rastrillo/mail" |
| "amadan.net/rastrillo/rastrillo/migrate" |
| "amadan.net/carlos/base/internal/config" |
| "amadan.net/carlos/base/internal/store" |
| + "amadan.net/carlos/base/internal/web" |
| ) |
| func main() { |
| @@ -46,12 +47,21 @@ func run(logger *slog.Logger) error { |
| if err := store.Bootstrap(ctx, d.Writer(), cfg.Owner); err != nil { |
| return err |
| } |
| - // Placeholder until the web package lands. |
| + // Static files are served by the app itself. |
| + handler, err := web.App(d, cfg, mail.FromEnv("CARLOS", logger), noInstaller{}, logger) |
| + if err != nil { |
| + return err |
| + } |
| + // rastrillo.Serve wants a *http.ServeMux; the chi router takes every path. |
| mux := http.NewServeMux() |
| - mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { |
| - fmt.Fprintf(w, "%s\n", cfg.Name) |
| - }) |
| + mux.Handle("/", handler) |
| opts.Mux = mux |
| opts.DBPath = "" |
| return rastrillo.Serve(opts) |
| } |
| + |
| +// noInstaller stands in until the Store's installer lands. |
| +type noInstaller struct{} |
| + |
| +func (noInstaller) Install(context.Context, string) error { return nil } |
| +func (noInstaller) Uninstall(context.Context, string) error { return nil } |
diff --git a/docs/copy-pending.md b/docs/copy-pending.md| new file mode 100644 |
| index 0000000..4f5f900 |
| --- /dev/null |
| +++ b/docs/copy-pending.md |
| @@ -0,0 +1,30 @@ |
| +# Copy pending review |
| + |
| +New user-facing strings, one row each. The controller runs copy-review with Paul. |
| + |
| +| File | Context | Text | |
| +|---|---|---| |
| +| internal/web/templates/signin.html | Sign-in page, title and heading | Sign in to {Base name} | |
| +| internal/web/templates/signin.html | Sign-in page, helper line | Use your work email. | |
| +| internal/web/templates/signin.html | Sign-in page, email field label | Email address | |
| +| internal/web/templates/signin.html | Sign-in page, button | Continue | |
| +| internal/web/templates/signin.html | Stranger refused (verified address that is not a member) | Sign-in isn't available for that address. Ask whoever runs {Base name} to invite you, or try another address. | |
| +| internal/web/templates/signin.html | Keymail problem, button | Send me a link instead | |
| +| internal/web/templates/signin.html | Link sent, heading | Check your email | |
| +| internal/web/templates/signin.html | Link sent, body (with address) | We sent a link to {address}. The link works once and expires soon. | |
| +| internal/web/templates/signin.html | Link sent, body (address unknown) | We sent a link to your inbox. The link works once and expires soon. | |
| +| internal/web/templates/signin.html | Link sent, button | Use a different email | |
| +| internal/web/templates/signin.html | Keymail hand-off, heading | Taking you to Keymail | |
| +| internal/web/templates/signin.html | Keymail hand-off, body | Taking you to Keymail to confirm it's you. | |
| +| internal/web/templates/signin.html | Keymail hand-off, button | Continue to Keymail | |
| +| internal/web/signin.go | Problem: too many tries | Too many tries. Try again in a few minutes. | |
| +| internal/web/signin.go | Problem: bad address | That doesn't look like an email address. | |
| +| internal/web/signin.go | Problem: link expired | That link has expired or was already used. Send a new one. | |
| +| internal/web/signin.go | Problem: Keymail failed | Keymail couldn't confirm it's you. | |
| +| internal/web/signin.go | Problem: generic | Something went wrong. Try again. | |
| +| internal/web/signin.go | Problem: re-authentication | Sign in again to continue. | |
| +| internal/web/signin.go | Problem: security check | Your browser couldn't finish a security check. Try again. | |
| +| internal/web/templates/confirm.html | Emailed link landing, button | Sign in | |
| +| internal/web/app.go | Home placeholder (replaced in Task 4) | {Base name} | |
| + |
| +Most of the sign-in strings are rastrillo's own English, reused as is. |
diff --git a/go.mod b/go.mod| index b4a31b6..f46c5b9 100644 |
| --- a/go.mod |
| +++ b/go.mod |
| @@ -2,7 +2,10 @@ module amadan.net/carlos/base |
| go 1.26.0 |
| -require amadan.net/rastrillo/rastrillo v0.33.0 |
| +require ( |
| + amadan.net/rastrillo/rastrillo v0.33.0 |
| + github.com/go-chi/chi/v5 v5.3.2 |
| +) |
| require ( |
| amadan.net/rastrillo/rastrillo/money v0.1.0 // indirect |
diff --git a/go.sum b/go.sum| index 3bc83a3..89dac51 100644 |
| --- a/go.sum |
| +++ b/go.sum |
| @@ -8,6 +8,8 @@ github.com/chromedp/chromedp v0.21.0 h1:nVHgS2LHyhZJ1l3BWRbG2eFIFYiJMnvkJbELbd8W |
| github.com/chromedp/chromedp v0.21.0/go.mod h1:6z1Y5FdKUxRzxx2qcC5h1xjaBJrSWrZp1mjgITfNZig= |
| github.com/dustin/go-humanize v1.0.1 h1:GzkhY7T5VNhEkwH0PVJgjz+fX1rhBrR7pRT3mDkpeCY= |
| github.com/dustin/go-humanize v1.0.1/go.mod h1:Mu1zIs6XwVuF/gI1OepvI0qD18qycQx+mFykh5fBlto= |
| +github.com/go-chi/chi/v5 v5.3.2 h1:5YQkICvTCSZ25hoRsyJazN0scjzKGiu4VAUc7H1o1nY= |
| +github.com/go-chi/chi/v5 v5.3.2/go.mod h1:R+tYY2hNuVUUjxoPtqUdgBqevM9s9njzkTLutVsOCto= |
| github.com/go-json-experiment/json v0.0.0-20260820222146-c27c302e5fc3 h1:UADEEmDKgfXbtnGJZ97beY5XLo9ZechG1nlU4KnRrkE= |
| github.com/go-json-experiment/json v0.0.0-20260820222146-c27c302e5fc3/go.mod h1:tphK2c80bpPhMOI4v6bIc2xWywPfbqi1Z06+RcrMkDg= |
| github.com/go-sql-driver/mysql v1.7.0 h1:ueSltNNllEqE3qcWBTD0iQd3IpL/6U+mJxLkazJ7YPc= |
diff --git a/internal/config/config.go b/internal/config/config.go| index 592b545..bbeb56a 100644 |
| --- a/internal/config/config.go |
| +++ b/internal/config/config.go |
| @@ -38,6 +38,9 @@ type Config struct { |
| OperateToken string |
| AssertionKey *crypto.Keypair |
| AllowLoggedMail bool |
| + // InstanceKey seals sign-in state (BASE_INSTANCE_KEY). Keep it secret and |
| + // stable: changing it invalidates links and sign-ins in flight. |
| + InstanceKey string |
| } |
| // Load reads the configuration. getenv is os.Getenv in production. |
| @@ -54,6 +57,7 @@ func Load(getenv func(string) string) (Config, error) { |
| InstanceToken: get("PLATFORM_INSTANCE_TOKEN"), |
| OperateToken: get("PLATFORM_OPERATE_TOKEN"), |
| AllowLoggedMail: get("ALLOW_LOGGED_MAIL") == "1", |
| + InstanceKey: get("INSTANCE_KEY"), |
| } |
| if cfg.Origin == "" { |
| return Config{}, errors.New("BASE_ORIGIN is required") |
diff --git a/internal/web/app.go b/internal/web/app.go| new file mode 100644 |
| index 0000000..89e6f31 |
| --- /dev/null |
| +++ b/internal/web/app.go |
| @@ -0,0 +1,163 @@ |
| +// Package web is Base's HTTP surface: sign-in, the member gate and, in later |
| +// tasks, Home and the Store. |
| +package web |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "embed" |
| + "errors" |
| + "io/fs" |
| + "log/slog" |
| + "net/http" |
| + "time" |
| + |
| + "github.com/go-chi/chi/v5" |
| + |
| + "amadan.net/rastrillo/rastrillo/auth" |
| + "amadan.net/rastrillo/rastrillo/csrf" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/mail" |
| + "amadan.net/rastrillo/rastrillo/pow" |
| + |
| + "amadan.net/carlos/base/internal/config" |
| + "amadan.net/carlos/base/internal/look" |
| + "amadan.net/carlos/base/internal/store" |
| +) |
| + |
| +//go:embed templates/*.html |
| +var templateFS embed.FS |
| + |
| +// Installer installs and uninstalls catalogue apps for this Base. The |
| +// implementation arrives with the Store; until then main passes a no-op. |
| +type Installer interface { |
| + Install(ctx context.Context, app string) error |
| + Uninstall(ctx context.Context, app string) error |
| +} |
| + |
| +type app struct { |
| + db *sql.DB |
| + cfg config.Config |
| + inst Installer |
| + logger *slog.Logger |
| + auth *auth.Auth |
| + pages *look.Renderer |
| +} |
| + |
| +// App builds Base's router. d is rastrillo's database handle (auth and |
| +// sessions need it); store functions get d.Writer(). |
| +func App(d *db.DB, cfg config.Config, mailer mail.Sender, inst Installer, logger *slog.Logger) (http.Handler, error) { |
| + if mailer == nil { |
| + return nil, errors.New("web: a mail sender is required") |
| + } |
| + if !mail.IsConfigured(mailer) && !cfg.AllowLoggedMail { |
| + return nil, errors.New("web: set CARLOS_SMTP_HOST and CARLOS_SMTP_FROM so Base can email sign-in links (BASE_ALLOW_LOGGED_MAIL=1 only for local runs)") |
| + } |
| + if cfg.InstanceKey == "" { |
| + return nil, errors.New("web: BASE_INSTANCE_KEY is required") |
| + } |
| + if logger == nil { |
| + logger = slog.Default() |
| + } |
| + sub, err := fs.Sub(templateFS, "templates") |
| + if err != nil { |
| + return nil, err |
| + } |
| + pages, err := look.NewRenderer(sub, nil) |
| + if err != nil { |
| + return nil, err |
| + } |
| + a := &app{db: d.Writer(), cfg: cfg, inst: inst, logger: logger, pages: pages} |
| + guard, err := pow.New(pow.Config{InstanceKey: cfg.InstanceKey, Nonces: pow.SQLNonces(d.Writer()), Difficulty: pow.NoProof, MinAge: pow.DefaultMinAge}) |
| + if err != nil { |
| + return nil, err |
| + } |
| + a.auth, err = auth.New(auth.Config{ |
| + DB: d.Writer(), Origin: cfg.Origin, InstanceKey: cfg.InstanceKey, Mailer: mailer, Logger: logger, |
| + Proof: guard, KeymailServers: []string{"keymail.dev"}, SigninScreen: true, |
| + BeginPath: "/auth/begin", ForgetPath: "/auth/forget", SignedInPath: "/", |
| + Authorize: a.authorize, |
| + Refused: func(w http.ResponseWriter, r *http.Request, _ auth.Identity) { |
| + http.Redirect(w, r, "/signin?refused=1", http.StatusSeeOther) |
| + }, |
| + RenderConfirm: a.renderConfirm, |
| + }) |
| + if err != nil { |
| + return nil, err |
| + } |
| + |
| + r := chi.NewRouter() |
| + r.Use(csrf.Protect(cfg.Origin)) |
| + r.Get("/static/fonts/*", look.FontHandler().ServeHTTP) |
| + r.Get("/static/*", look.Assets.Handler().ServeHTTP) |
| + r.Get("/signin", a.signin) |
| + r.Post("/auth/begin", a.auth.Begin) |
| + r.Get("/auth/callback", a.auth.Callback) |
| + r.Get("/auth/verify", a.auth.Verify) |
| + r.Post("/auth/verify", a.auth.Verify) |
| + r.Post("/auth/forget", a.auth.Forget) |
| + r.Post("/auth/signout", a.auth.Signout) |
| + r.Group(func(r chi.Router) { |
| + r.Use(a.requireMember) |
| + r.Get("/", a.home) |
| + }) |
| + return r, nil |
| +} |
| + |
| +// authorize admits a verified address that belongs to a member, and records |
| +// the member's first sign-in. It runs only after the address has been proved. |
| +func (a *app) authorize(address string) bool { |
| + ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| + defer cancel() |
| + m, ok, err := store.MemberByEmail(ctx, a.db, address) |
| + if err != nil || !ok { |
| + if err != nil { |
| + a.logger.Error("sign-in: member lookup", "err", err) |
| + } |
| + return false |
| + } |
| + if m.JoinedAt == nil { |
| + if err := store.MarkJoined(ctx, a.db, m.ID); err != nil { |
| + a.logger.Error("sign-in: mark joined", "err", err) |
| + return false |
| + } |
| + } |
| + return true |
| +} |
| + |
| +type ctxKey struct{} |
| + |
| +// CurrentMember is the signed-in member behind a request that passed the gate. |
| +func CurrentMember(r *http.Request) (store.Member, bool) { |
| + m, ok := r.Context().Value(ctxKey{}).(store.Member) |
| + return m, ok |
| +} |
| + |
| +// requireMember lets through only a browser session whose address is still a |
| +// member, and puts that member on the request. |
| +func (a *app) requireMember(next http.Handler) http.Handler { |
| + return a.auth.RequireSession(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + id, ok := auth.From(r) |
| + if !ok { |
| + http.Error(w, "forbidden", http.StatusForbidden) |
| + return |
| + } |
| + m, found, err := store.MemberByEmail(r.Context(), a.db, id.Address) |
| + switch { |
| + case err != nil: |
| + a.logger.Error("member gate", "err", err) |
| + http.Error(w, "unavailable", http.StatusServiceUnavailable) |
| + case !found: |
| + http.Error(w, "forbidden", http.StatusForbidden) |
| + default: |
| + next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, m))) |
| + } |
| + })) |
| +} |
| + |
| +// home is a stand-in until Home lands. |
| +func (a *app) home(w http.ResponseWriter, r *http.Request) { |
| + w.Header().Set("Content-Type", "text/plain; charset=utf-8") |
| + _, _ = w.Write([]byte(a.cfg.Name + "\n")) |
| +} |
diff --git a/internal/web/signin.go b/internal/web/signin.go| new file mode 100644 |
| index 0000000..03b1144 |
| --- /dev/null |
| +++ b/internal/web/signin.go |
| @@ -0,0 +1,50 @@ |
| +package web |
| + |
| +import ( |
| + "net/http" |
| + |
| + "amadan.net/rastrillo/rastrillo/auth" |
| +) |
| + |
| +type signinPage struct { |
| + Name string |
| + State auth.SigninState |
| + Refused bool |
| + ProblemText string |
| + Confirm *auth.ConfirmPageData |
| +} |
| + |
| +var problemText = map[auth.SigninProblem]string{ |
| + auth.ProblemRate: "Too many tries. Try again in a few minutes.", |
| + auth.ProblemAddress: "That doesn't look like an email address.", |
| + auth.ProblemExpired: "That link has expired or was already used. Send a new one.", |
| + auth.ProblemKeymail: "Keymail couldn't confirm it's you.", |
| + auth.ProblemGeneric: "Something went wrong. Try again.", |
| + auth.ProblemReauth: "Sign in again to continue.", |
| + auth.ProblemCheck: "Your browser couldn't finish a security check. Try again.", |
| +} |
| + |
| +func (a *app) signin(w http.ResponseWriter, r *http.Request) { |
| + state := a.auth.SigninState(r) |
| + a.auth.PrepareSigninResponse(w, state) |
| + w.Header().Set("Cache-Control", "no-store") |
| + a.render(w, "signin", signinPage{ |
| + Name: a.cfg.Name, State: state, |
| + Refused: r.URL.Query().Get("refused") == "1", |
| + ProblemText: problemText[state.Problem], |
| + }) |
| +} |
| + |
| +// renderConfirm draws the page an emailed link lands on: one button that |
| +// posts the token, so a mail scanner opening the link spends nothing. |
| +func (a *app) renderConfirm(w http.ResponseWriter, _ *http.Request, d auth.ConfirmPageData) { |
| + w.Header().Set("Cache-Control", "no-store") |
| + a.render(w, "confirm", signinPage{Name: a.cfg.Name, Confirm: &d}) |
| +} |
| + |
| +func (a *app) render(w http.ResponseWriter, name string, data any) { |
| + if err := a.pages.Page(w, name, data); err != nil { |
| + a.logger.Error("render", "page", name, "err", err) |
| + http.Error(w, "something went wrong", http.StatusInternalServerError) |
| + } |
| +} |
diff --git a/internal/web/templates/confirm.html b/internal/web/templates/confirm.html| new file mode 100644 |
| index 0000000..8c509d0 |
| --- /dev/null |
| +++ b/internal/web/templates/confirm.html |
| @@ -0,0 +1,11 @@ |
| +{{define "title"}}Sign in to {{.Name}}{{end}} |
| +{{define "main"}}<main class="signin"> |
| +<div class="card glass"> |
| +<div class="wordmark">base</div> |
| +<h2>Sign in to {{.Name}}</h2> |
| +<form method="post" action="{{.Confirm.Action}}"> |
| +<input type="hidden" name="token" value="{{.Confirm.Token}}"> |
| +<button class="btn" type="submit">Sign in</button> |
| +</form> |
| +</div> |
| +</main>{{end}} |
diff --git a/internal/web/templates/signin.html b/internal/web/templates/signin.html| new file mode 100644 |
| index 0000000..7e153af |
| --- /dev/null |
| +++ b/internal/web/templates/signin.html |
| @@ -0,0 +1,23 @@ |
| +{{define "title"}}{{if .State.Unavailable}}Base{{else}}Sign in to {{.Name}}{{end}}{{end}} |
| +{{define "main"}}{{$s := .State}}<main class="signin"> |
| +<div class="card glass"> |
| +<div class="wordmark">base</div> |
| +{{if eq $s.Step "continue"}}<meta http-equiv="refresh" content="0;url={{$s.ContinueURL}}"> |
| +<h2>Taking you to Keymail</h2> |
| +<p>Taking you to Keymail to confirm it's you.</p> |
| +<a class="btn" href="{{$s.ContinueURL}}">Continue to Keymail</a> |
| +{{else if eq $s.Step "sent"}}<h2>Check your email</h2> |
| +<p>{{if $s.SentTo}}We sent a link to <bdi>{{$s.SentTo}}</bdi>.{{else}}We sent a link to your inbox.{{end}} The link works once and expires soon.</p> |
| +<form method="post" action="{{$s.ForgetPath}}">{{with $s.ReturnTo}}<input type="hidden" name="return_to" value="{{.}}">{{end}}<button class="btn ghost" type="submit">Use a different email</button></form> |
| +{{else}}<h2>Sign in to {{.Name}}</h2> |
| +{{if .Refused}}<p role="status">Sign-in isn't available for that address. Ask whoever runs {{.Name}} to invite you, or try another address.</p> |
| +{{else if $s.Problem}}<p role="status">{{.ProblemText}}</p> |
| +{{else}}<p>Use your work email.</p> |
| +{{end}}<form method="post" action="{{$s.BeginPath}}"{{with $s.Proof}} {{.Attrs}}{{end}}>{{with $s.Proof}}{{.Fields}}{{end}} |
| +{{with $s.ReturnTo}}<input type="hidden" name="return_to" value="{{.}}"> |
| +{{end}}{{if or $s.Force (eq $s.Problem "keymail")}}<input type="hidden" name="force" value="1"> |
| +{{end}}<input class="input" type="email" name="address" value="{{$s.Address}}" autocomplete="email" required aria-label="Email address"> |
| +<button class="btn" type="submit">{{if eq $s.Problem "keymail"}}Send me a link instead{{else}}Continue{{end}}</button> |
| +</form> |
| +{{end}}</div> |
| +</main>{{end}} |
diff --git a/internal/webtest/harness_test.go b/internal/webtest/harness_test.go| new file mode 100644 |
| index 0000000..299e5c2 |
| --- /dev/null |
| +++ b/internal/webtest/harness_test.go |
| @@ -0,0 +1,208 @@ |
| +// Package webtest tests Base from the outside: real HTTP requests against |
| +// the real router, wired as cmd/base/main.go wires it. |
| +package webtest |
| + |
| +import ( |
| + "context" |
| + "database/sql" |
| + "html" |
| + "io" |
| + "log/slog" |
| + "net/http" |
| + "net/http/cookiejar" |
| + "net/http/httptest" |
| + "net/url" |
| + "os" |
| + "regexp" |
| + "strings" |
| + "sync" |
| + "testing" |
| + |
| + "amadan.net/rastrillo/rastrillo/budget" |
| + "amadan.net/rastrillo/rastrillo/db" |
| + "amadan.net/rastrillo/rastrillo/dbtest" |
| + |
| + "amadan.net/carlos/base/internal/config" |
| + "amadan.net/carlos/base/internal/store" |
| + "amadan.net/carlos/base/internal/web" |
| +) |
| + |
| +// testOrigin is the origin newApp wires and post presents as its |
| +// same-origin evidence: the pair a browser form submission would be. |
| +const ( |
| + testOrigin = "http://127.0.0.1:8080" |
| + ownerAddress = "owner@acme.test" |
| +) |
| + |
| +// schema is migrated once per test binary and copied for each test. |
| +var schema = dbtest.FromSet(store.BootSchema) |
| + |
| +func TestMain(m *testing.M) { |
| + code := budget.Main(m) |
| + schema.Remove() |
| + os.Exit(code) |
| +} |
| + |
| +// Mail is one captured message. |
| +type Mail struct{ To, Subject, Body string } |
| + |
| +type capturingMailer struct { |
| + mu sync.Mutex |
| + sent []Mail |
| +} |
| + |
| +func (c *capturingMailer) Send(_ context.Context, to, subject, body string) error { |
| + c.mu.Lock() |
| + defer c.mu.Unlock() |
| + c.sent = append(c.sent, Mail{to, subject, body}) |
| + return nil |
| +} |
| + |
| +type noInstaller struct{} |
| + |
| +func (noInstaller) Install(context.Context, string) error { return nil } |
| +func (noInstaller) Uninstall(context.Context, string) error { return nil } |
| + |
| +// Resp is a fully read response. |
| +type Resp struct { |
| + Code int |
| + Header http.Header |
| + Body string |
| +} |
| + |
| +func (r Resp) Location() string { return r.Header.Get("Location") } |
| + |
| +type testApp struct { |
| + t *testing.T |
| + srv *httptest.Server |
| + client *http.Client |
| + mail *capturingMailer |
| + DB *sql.DB |
| +} |
| + |
| +// newApp builds the whole app per test over its own copy of the migrated |
| +// database, exactly as main.go does, with the owner bootstrapped. |
| +func newApp(t *testing.T) *testApp { |
| + t.Helper() |
| + logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| + d, err := db.Open(schema.Path(t), logger) |
| + if err != nil { |
| + t.Fatalf("db.Open: %v", err) |
| + } |
| + t.Cleanup(func() { d.Close() }) |
| + if err := store.Bootstrap(context.Background(), d.Writer(), ownerAddress); err != nil { |
| + t.Fatal(err) |
| + } |
| + cfg := config.Config{Origin: testOrigin, Name: "Acme", Owner: ownerAddress, InstanceKey: "test-instance-key", AllowLoggedMail: true} |
| + mailer := &capturingMailer{} |
| + h, err := web.App(d, cfg, mailer, noInstaller{}, logger) |
| + if err != nil { |
| + t.Fatalf("web.App: %v", err) |
| + } |
| + srv := httptest.NewServer(h) // 127.0.0.1 only |
| + t.Cleanup(srv.Close) |
| + jar, _ := cookiejar.New(nil) |
| + client := &http.Client{Jar: jar, CheckRedirect: func(*http.Request, []*http.Request) error { return http.ErrUseLastResponse }} |
| + return &testApp{t: t, srv: srv, client: client, mail: mailer, DB: d.Writer()} |
| +} |
| + |
| +func (a *testApp) do(req *http.Request) Resp { |
| + a.t.Helper() |
| + res, err := a.client.Do(req) |
| + if err != nil { |
| + a.t.Fatal(err) |
| + } |
| + defer res.Body.Close() |
| + b, _ := io.ReadAll(res.Body) |
| + return Resp{res.StatusCode, res.Header, string(b)} |
| +} |
| + |
| +func (a *testApp) get(target string) Resp { |
| + a.t.Helper() |
| + req, _ := http.NewRequest(http.MethodGet, a.srv.URL+target, nil) |
| + return a.do(req) |
| +} |
| + |
| +// post presents the same-origin evidence csrf.Protect requires: every |
| +// browser sends Origin on a form POST; a test client must too. |
| +func (a *testApp) post(target string, form url.Values) Resp { |
| + a.t.Helper() |
| + req, _ := http.NewRequest(http.MethodPost, a.srv.URL+target, strings.NewReader(form.Encode())) |
| + req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| + req.Header.Set("Origin", testOrigin) |
| + return a.do(req) |
| +} |
| + |
| +func (a *testApp) mailbox() []Mail { |
| + a.mail.mu.Lock() |
| + defer a.mail.mu.Unlock() |
| + return append([]Mail(nil), a.mail.sent...) |
| +} |
| + |
| +var ( |
| + formRE = regexp.MustCompile(`(?s)<form[^>]*action="([^"]*)"[^>]*>(.*?)</form>`) |
| + inputRE = regexp.MustCompile(`<input[^>]*>`) |
| + attrRE = regexp.MustCompile(`(\w[\w-]*)="([^"]*)"`) |
| + linkRE = regexp.MustCompile(`https?://[^\s"<>]+/auth/verify\?[^\s"<>]+`) |
| +) |
| + |
| +// formFields returns the hidden and text inputs of the form posting to action. |
| +func formFields(t *testing.T, body, action string) url.Values { |
| + t.Helper() |
| + for _, m := range formRE.FindAllStringSubmatch(body, -1) { |
| + if html.UnescapeString(m[1]) != action { |
| + continue |
| + } |
| + v := url.Values{} |
| + for _, in := range inputRE.FindAllString(m[2], -1) { |
| + attrs := map[string]string{} |
| + for _, kv := range attrRE.FindAllStringSubmatch(in, -1) { |
| + attrs[kv[1]] = html.UnescapeString(kv[2]) |
| + } |
| + if attrs["name"] != "" { |
| + v.Set(attrs["name"], attrs["value"]) |
| + } |
| + } |
| + return v |
| + } |
| + t.Fatalf("no form posting to %s in:\n%s", action, body) |
| + return nil |
| +} |
| + |
| +// requestLink asks for a sign-in link as a visitor would. ?rec=1 renders the |
| +// recovery form, which is usable at once; the ordinary one makes a person wait |
| +// three seconds before it will be accepted. |
| +func (a *testApp) requestLink(email string) Resp { |
| + a.t.Helper() |
| + page := a.get("/signin?rec=1&force=1") |
| + if page.Code != 200 { |
| + a.t.Fatalf("signin page: %d", page.Code) |
| + } |
| + v := formFields(a.t, page.Body, "/auth/begin") |
| + v.Set("address", email) |
| + return a.post("/auth/begin", v) |
| +} |
| + |
| +// signIn requests a link, follows it from the mailbox and confirms it. It |
| +// returns the response to the confirm POST: a 303 to "/" on success. |
| +func (a *testApp) signIn(email string) Resp { |
| + a.t.Helper() |
| + before := len(a.mailbox()) |
| + if r := a.requestLink(email); r.Code != 303 { |
| + a.t.Fatalf("begin: %d %s", r.Code, r.Body) |
| + } |
| + box := a.mailbox() |
| + if len(box) != before+1 { |
| + a.t.Fatalf("want one new email, mailbox has %d (was %d)", len(box), before) |
| + } |
| + link := linkRE.FindString(html.UnescapeString(box[len(box)-1].Body)) |
| + if link == "" { |
| + a.t.Fatalf("no sign-in link in:\n%s", box[len(box)-1].Body) |
| + } |
| + u, _ := url.Parse(link) |
| + confirm := a.get(u.RequestURI()) |
| + if confirm.Code != 200 { |
| + a.t.Fatalf("confirm page: %d", confirm.Code) |
| + } |
| + return a.post("/auth/verify", formFields(a.t, confirm.Body, "/auth/verify")) |
| +} |
diff --git a/internal/webtest/signin_test.go b/internal/webtest/signin_test.go| new file mode 100644 |
| index 0000000..0436a9b |
| --- /dev/null |
| +++ b/internal/webtest/signin_test.go |
| @@ -0,0 +1,83 @@ |
| +package webtest |
| + |
| +import ( |
| + "context" |
| + "regexp" |
| + "strings" |
| + "testing" |
| + |
| + "amadan.net/carlos/base/internal/store" |
| +) |
| + |
| +func TestOwnerCanSignIn(t *testing.T) { |
| + a := newApp(t) |
| + res := a.signIn(ownerAddress) |
| + if res.Code != 303 || res.Location() != "/" { |
| + t.Fatalf("verify: %d to %q", res.Code, res.Location()) |
| + } |
| + if home := a.get("/"); home.Code != 200 { |
| + t.Fatalf("GET /: %d", home.Code) |
| + } |
| +} |
| + |
| +func TestStrangerRefused(t *testing.T) { |
| + a := newApp(t) |
| + res := a.signIn("stranger@elsewhere.test") |
| + if res.Code != 303 || !strings.HasPrefix(res.Location(), "/signin") { |
| + t.Fatalf("verify: %d to %q", res.Code, res.Location()) |
| + } |
| + page := a.get(res.Location()) |
| + if page.Code != 200 || !strings.Contains(page.Body, "Sign-in isn") { |
| + t.Fatalf("refusal page: %d\n%s", page.Code, page.Body) |
| + } |
| + if home := a.get("/"); home.Code != 303 || !strings.HasPrefix(home.Location(), "/signin") { |
| + t.Fatalf("stranger reached /: %d to %q", home.Code, home.Location()) |
| + } |
| +} |
| + |
| +func TestInvitedMemberJoinsOnFirstSignIn(t *testing.T) { |
| + a := newApp(t) |
| + ctx := context.Background() |
| + if _, _, err := store.Invite(ctx, a.DB, "Ana@Acme.test"); err != nil { |
| + t.Fatal(err) |
| + } |
| + if m, _, _ := store.MemberByEmail(ctx, a.DB, "ana@acme.test"); m.JoinedAt != nil { |
| + t.Fatal("joined before signing in") |
| + } |
| + if res := a.signIn("ana@acme.test"); res.Code != 303 || res.Location() != "/" { |
| + t.Fatalf("verify: %d to %q", res.Code, res.Location()) |
| + } |
| + m, _, err := store.MemberByEmail(ctx, a.DB, "ana@acme.test") |
| + if err != nil || m.JoinedAt == nil { |
| + t.Fatalf("JoinedAt not set: %+v, %v", m, err) |
| + } |
| +} |
| + |
| +func TestSignOut(t *testing.T) { |
| + a := newApp(t) |
| + a.signIn(ownerAddress) |
| + if a.get("/").Code != 200 { |
| + t.Fatal("not signed in") |
| + } |
| + if res := a.post("/auth/signout", nil); res.Code != 303 { |
| + t.Fatalf("signout: %d", res.Code) |
| + } |
| + if home := a.get("/"); home.Code != 303 || !strings.HasPrefix(home.Location(), "/signin") { |
| + t.Fatalf("GET / after signout: %d to %q", home.Code, home.Location()) |
| + } |
| +} |
| + |
| +func TestSigninPageServesItsStylesheet(t *testing.T) { |
| + a := newApp(t) |
| + page := a.get("/signin") |
| + if page.Code != 200 || !strings.Contains(page.Body, "Sign in to Acme") || strings.Contains(page.Body, "passkey") { |
| + t.Fatalf("signin page: %d\n%s", page.Code, page.Body) |
| + } |
| + m := regexp.MustCompile(`href="(/static/app[^"]*\.css)"`).FindStringSubmatch(page.Body) |
| + if m == nil { |
| + t.Fatalf("no stylesheet link in:\n%s", page.Body) |
| + } |
| + if css := a.get(m[1]); css.Code != 200 || !strings.Contains(css.Body, ".signin") { |
| + t.Fatalf("stylesheet: %d", css.Code) |
| + } |
| +} |