package callstest
import (
"io"
"log/slog"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"amadan.net/rastrillo/rastrillo"
"amadan.net/oficina/calls/internal/calls"
)
// TestEmailedLinkOpensTheConfirmDoor walks the magic-link sign-in end to
// end: begin, the mail, GET of the emailed link twice (the confirm door,
// which spends nothing), a cross-site POST that is refused without
// spending it, the door's POST, a session that opens the list, and the
// spent link answering ?err=expired.
//
// GET /auth/verify used to sign in on sight, so a mail-security gateway
// that fetches every link in an inbound message (Safe Links, Proofpoint)
// spent it before the person clicked, and they were told it had expired.
// rastrillo now confirms on GET and redeems on POST; this pins that the
// confirm step is Calls' own door with one Sign in button, not
// rastrillo's plain English fallback, and that the POST is mounted.
func TestEmailedLinkOpensTheConfirmDoor(t *testing.T) {
x := newHarness(t, "paul@example.com")
c := x.browser(t)
if rec := c.post("/signin", url.Values{"address": {"paul@example.com"}}); rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/signin?sent=1" {
t.Fatalf("POST /signin = %d %q, want 303 /signin?sent=1", rec.Code, rec.Header().Get("Location"))
}
_, link := x.mail.last()
u, err := url.Parse(link)
if err != nil || link == "" {
t.Fatalf("emailed link %q: %v", link, err)
}
// Opened twice, as a scanner and then the person would. Each is a
// fresh browser, so a cookie one GET set could not help the next.
for _, who := range []string{"scanner", "person"} {
rec := x.browser(t).get(u.RequestURI())
if rec.Code != http.StatusOK || len(rec.Result().Cookies()) != 0 {
t.Fatalf("%s's GET = %d with %d cookies, want 200 and nothing minted", who, rec.Code, len(rec.Result().Cookies()))
}
body := rec.Body.String()
for _, want := range []string{"estilo-door", "estilo-signin-form", "Calls", "Select Sign in to finish signing in.", `name="token" value="` + u.Query().Get("token") + `"`, `action="/auth/verify"`} {
if !strings.Contains(body, want) {
t.Errorf("%s: confirm door lacks %q:\n%s", who, want, body)
}
}
if n := strings.Count(body, "`) {
t.Errorf("%s: confirm door has %d buttons, want exactly one Sign in:\n%s", who, n, body)
}
if strings.Contains(body, `name="address"`) {
t.Errorf("%s: confirm door asks for an address again", who)
}
// auth sets these before RenderConfirm; render must not undo them.
for header, want := range map[string]string{
"Cache-Control": "no-store",
"Referrer-Policy": "strict-origin",
"X-Frame-Options": "DENY",
} {
if got := rec.Header().Get(header); got != want {
t.Errorf("%s: %s = %q, want %q", who, header, got, want)
}
}
}
if n := x.authLinks(t); n != 1 {
t.Fatalf("auth_links after two GETs: %d, want the one link still unspent", n)
}
// A post without a browser's same-origin evidence is refused and
// spends nothing.
action, token := c.open(link)
cross := httptest.NewRequest(http.MethodPost, action, strings.NewReader(url.Values{"token": {token}}.Encode()))
cross.Header.Set("Content-Type", "application/x-www-form-urlencoded")
cross.Header.Set("Sec-Fetch-Site", "cross-site")
if rec := c.do(cross); rec.Code != http.StatusForbidden || len(rec.Result().Cookies()) != 0 {
t.Fatalf("cross-site POST = %d with %d cookies, want 403 and nothing minted", rec.Code, len(rec.Result().Cookies()))
}
if n := x.authLinks(t); n != 1 {
t.Fatalf("auth_links after a refused cross-site POST: %d, want the link still unspent", n)
}
// Sign in: the POST spends the link and mints the session.
signed := c.press(action, token)
if signed.Code != http.StatusSeeOther || signed.Header().Get("Location") != "/continue" {
t.Fatalf("POST %s = %d %q, want 303 /continue", action, signed.Code, signed.Header().Get("Location"))
}
if rec := c.get("/continue"); rec.Code != http.StatusSeeOther || rec.Header().Get("Location") != "/" {
t.Fatalf("GET /continue = %d %q, want 303 /", rec.Code, rec.Header().Get("Location"))
}
if rec := c.get("/"); rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), "Meetings") {
t.Fatalf("GET / with the new session = %d", rec.Code)
}
// Spent: the door still opens (it looks nothing up), but its button
// now says the link expired, and mints nothing.
again := x.browser(t)
replay := again.press(again.open(link))
if len(replay.Result().Cookies()) != 0 || replay.Header().Get("Location") != "/signin?err=expired" {
t.Fatalf("second POST = %d %q, want /signin?err=expired and no session", replay.Code, replay.Header().Get("Location"))
}
}
// productionHandler is the app behind rastrillo's serving stack, built
// from the same calls.ServeOptions main hands to rastrillo.Serve:
// security headers, CSP and all. The bare mux carries no CSP, so a test
// that serves only the mux cannot see what a browser is told.
func productionHandler(t *testing.T, x *harness) http.Handler {
t.Helper()
h, closeFn, err := rastrillo.Handler(calls.ServeOptions(rastrillo.Options{Logger: slog.New(slog.NewTextHandler(io.Discard, nil))}, x.h.(*http.ServeMux), x.ctl.Runtime()))
if err != nil {
t.Fatalf("rastrillo.Handler: %v", err)
}
t.Cleanup(func() { _ = closeFn() })
return h
}
// frameworkDefaultCSP is rastrillo's own policy, read off a handler
// built with no CSP and no app.
func frameworkDefaultCSP(t *testing.T) string {
t.Helper()
bare, closeFn, err := rastrillo.Handler(rastrillo.Options{Mux: http.NewServeMux(), Logger: slog.New(slog.NewTextHandler(io.Discard, nil))})
if err != nil {
t.Fatal(err)
}
defer closeFn()
rec := httptest.NewRecorder()
bare.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, "/healthz", nil))
policy := rec.Header().Get("Content-Security-Policy")
if policy == "" {
t.Fatal("rastrillo set no default CSP")
}
return policy
}
// TestProductionServesRastrillosDefaultCSP: standalone, every page Calls
// serves through the production stack carries exactly rastrillo's
// default policy, the one that refuses inline styles (serving.go says
// why Calls needs nothing looser). A bump that changes the default is
// followed, not overridden; a change here that widened style-src would
// fail.
func TestProductionServesRastrillosDefaultCSP(t *testing.T) {
want := frameworkDefaultCSP(t)
if strings.Contains(want, "'unsafe-inline'") {
t.Fatalf("rastrillo's default allows inline again (%q): revisit serving.go", want)
}
x, sqid, _ := memberWithMeeting(t)
h := productionHandler(t, x)
member := x.browser(t)
member.signIn("paul@example.com")
for _, path := range []string{"/signin", "/", "/m/" + sqid + "/join", "/m/" + sqid, "/settings", "/help/open-source"} {
req := httptest.NewRequest(http.MethodGet, path, nil)
if path != "/signin" {
for _, ck := range member.cookies {
req.AddCookie(ck)
}
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, req)
if rec.Code != http.StatusOK {
t.Fatalf("GET %s through the production stack = %d", path, rec.Code)
}
if got := rec.Header().Values("Content-Security-Policy"); len(got) != 1 || got[0] != want {
t.Errorf("GET %s: CSP = %q, want exactly rastrillo's default %q", path, got, want)
}
if strings.Contains(rec.Body.String(), " style=\"") {
t.Errorf("GET %s: the page carries a style attribute, which this policy refuses", path)
}
}
}
// TestTheConfirmDoorKeepsEveryPolicy: the confirm door through the
// production stack carries rastrillo's policy and auth's added
// frame-ancestors 'none' (browsers enforce every CSP header, so the
// second only narrows), and auth's no-store, strict-origin referrer and
// frame denial survive the render.
func TestTheConfirmDoorKeepsEveryPolicy(t *testing.T) {
x := newHarness(t, "paul@example.com")
h := productionHandler(t, x)
x.browser(t).post("/signin", url.Values{"address": {"paul@example.com"}})
_, link := x.mail.last()
u, err := url.Parse(link)
if err != nil {
t.Fatal(err)
}
rec := httptest.NewRecorder()
h.ServeHTTP(rec, httptest.NewRequest(http.MethodGet, u.RequestURI(), nil))
if rec.Code != http.StatusOK || !confirmForm.MatchString(rec.Body.String()) {
t.Fatalf("confirm door through the production stack = %d, or no confirm form", rec.Code)
}
got := rec.Header().Values("Content-Security-Policy")
if want := frameworkDefaultCSP(t); len(got) != 2 || got[0] != want || got[1] != "frame-ancestors 'none'" {
t.Fatalf("confirm door CSP = %q, want rastrillo's default then frame-ancestors 'none'", got)
}
for header, want := range map[string]string{"X-Frame-Options": "DENY", "Referrer-Policy": "strict-origin", "Cache-Control": "no-store"} {
if v := rec.Header().Get(header); v != want {
t.Errorf("%s = %q, want %q", header, v, want)
}
}
}