package fichastest // The Keymail continuation, driven from the outside: an owner whose // address Keymail claims posts to Begin, which keeps the sign-in on the // door (/signin?continue=) instead of a 303 off-site that the CSP's // form-action 'self' would refuse. These replace auth_navigation_test.go, // whose wrapper rastrillo's screen made unnecessary. // // Nothing here leaves the machine: the classifier's DNS lookup goes to a // resolver on loopback that answers "no such name" (so the domain is its // own Keymail server, as keymail's protocol says), and its HTTPS probes go // to a transport that answers for kmail.test. Both are process globals, // swapped for the test and put back. import ( "context" "io" "log/slog" "net" "net/http" "net/url" "path/filepath" "regexp" "strings" "sync/atomic" "testing" fichas "amadan.net/oficina/fichas/internal/fichas" "amadan.net/rastrillo/rastrillo" "amadan.net/rastrillo/rastrillo/db" ) const ( keymailOwner = "km@kmail.test" // Keymail claims it plainOwner = "pl@plain.test" // a domain that is not Keymail keymailHost = "kmail.test" // its own server: no _keymail delegation ) // fakeKeymail answers the classifier's probes: kmail.test is a Keymail // server that claims every address; any other host has no well-known. type fakeKeymail struct{ probes atomic.Int32 } func (f *fakeKeymail) RoundTrip(r *http.Request) (*http.Response, error) { f.probes.Add(1) status, body := http.StatusNotFound, "{}" if r.URL.Host == keymailHost { switch r.URL.Path { case "/.well-known/keymail": status, body = http.StatusOK, `{"version":"1"}` case "/api/federation/lookup": status = http.StatusOK } } return &http.Response{StatusCode: status, Body: io.NopCloser(strings.NewReader(body)), Header: http.Header{"Content-Type": {"application/json"}}, Request: r}, nil } // withFakeKeymail swaps the resolver and the default transport for the // test's length. func withFakeKeymail(t *testing.T) *fakeKeymail { t.Helper() pc, err := net.ListenPacket("udp", "127.0.0.1:0") if err != nil { t.Fatal(err) } t.Cleanup(func() { pc.Close() }) go func() { buf := make([]byte, 1500) for { n, from, err := pc.ReadFrom(buf) if err != nil { return } if n < 12 { continue } // The query back as the answer: a response (QR), recursion // available, NXDOMAIN, nothing answered. resp := append([]byte(nil), buf[:n]...) resp[2] = 0x80 | (resp[2] & 0x01) resp[3] = 0x80 | 0x03 pc.WriteTo(resp, from) } }() resolver, transport := net.DefaultResolver, http.DefaultTransport net.DefaultResolver = &net.Resolver{PreferGo: true, Dial: func(ctx context.Context, _, _ string) (net.Conn, error) { var d net.Dialer return d.DialContext(ctx, "udp", pc.LocalAddr().String()) }} fake := &fakeKeymail{} http.DefaultTransport = fake t.Cleanup(func() { net.DefaultResolver, http.DefaultTransport = resolver, transport }) return fake } // keymailApp is the app as main.go wires it, owned by keymailOwner and // plainOwner. func keymailApp(t *testing.T) (*http.ServeMux, *capturingMailer) { t.Helper() logger := slog.New(slog.NewTextHandler(io.Discard, nil)) d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger) if err != nil { t.Fatalf("db.Open: %v", err) } t.Cleanup(func() { d.Close() }) cfg := testConfig(t) cfg.Owners = []string{keymailOwner, plainOwner} mux, app, err := fichas.App(d, cfg, logger) if err != nil { t.Fatalf("App: %v", err) } m := &capturingMailer{} // The fake's two hosts, listed: rastrillo's default (nil, any server) // dials only public addresses, on a transport of its own, so it never // reaches the fake (rastrillo v0.45.0). au, err := fichas.NewAuth(d.Writer(), fichas.AuthEnv{Origin: cfg.Origin, InstanceKey: cfg.InstanceKey, Mailer: m, KeymailServers: []string{keymailHost, "plain.test"}}, logger, app) if err != nil { t.Fatalf("NewAuth: %v", err) } app.UseAuth(au) return mux, m } var metaRefresh = regexp.MustCompile(``) // A Keymail address: Begin keeps the sign-in on the door, and the // Continue step navigates on by itself (a meta refresh, no script) and by // its link, to exactly the authorize URL for this origin, on the one-way // door (its link a pill), with no-referrer and no-store, under the CSP // the app is served with, whose form-action stays 'self'. func TestAKeymailAddressContinuesOnTheDoor(t *testing.T) { fake := withFakeKeymail(t) mux, m := keymailApp(t) served, closeDB, err := rastrillo.Handler(rastrillo.Options{Mux: mux, ErrorPage: fichas.ErrorPage}) if err != nil { t.Fatalf("rastrillo.Handler: %v", err) } t.Cleanup(func() { closeDB() }) b := newBrowser() begin := b.post(t, served, "/auth/begin", url.Values{"address": {keymailOwner}}) loc := begin.Header().Get("Location") if begin.Code != http.StatusSeeOther || !strings.HasPrefix(loc, "/signin?continue=") { t.Fatalf("Begin for a Keymail address: %d to %q, want the door's continuation (probes: %d)", begin.Code, loc, fake.probes.Load()) } if len(m.sent) != 0 { t.Error("a Keymail address was mailed a link") } page := b.get(t, served, loc) if page.Code != http.StatusOK { t.Fatalf("GET %s: %d", loc, page.Code) } body := page.Body.String() // rastrillo's own words since v0.45.0, which never name Keymail. if got := titleOf(body); got != "Signing in to Fichas" { t.Errorf("title %q", got) } if !strings.Contains(body, `
`) { t.Errorf("the Continue step is not on the one-way door, so its link is no pill:\n%s", body) } refresh := metaRefresh.FindStringSubmatch(body) if refresh == nil { t.Fatalf("no meta refresh on the Continue step:\n%s", body) } dest, err := url.Parse(strings.ReplaceAll(refresh[1], "&", "&")) if err != nil { t.Fatal(err) } q := dest.Query() if dest.Scheme != "https" || dest.Host != keymailHost || dest.Path != "/oauth/authorize" || q.Get("client_id") != testOrigin || q.Get("redirect_uri") != testOrigin+"/auth/callback" || q.Get("code_challenge_method") != "S256" || q.Get("state") == "" || q.Get("code_challenge") == "" { t.Errorf("the continuation goes to %s, not this origin's Keymail authorize URL", dest) } if !strings.Contains(body, `Continue`) { t.Errorf("no Continue link to the same URL:\n%s", body) } if page.Header().Get("Referrer-Policy") != "no-referrer" || page.Header().Get("Cache-Control") != "no-store" { t.Errorf("Referrer-Policy %q, Cache-Control %q", page.Header().Get("Referrer-Policy"), page.Header().Get("Cache-Control")) } csp := page.Header().Get("Content-Security-Policy") if !strings.Contains(csp, "form-action 'self'") || strings.Contains(csp, keymailHost) { t.Errorf("the served CSP %q was widened for Keymail", csp) } if strings.Contains(body, "