| 1 | package fichastest |
| 2 | |
| 3 | // The Keymail continuation, driven from the outside: an owner whose |
| 4 | // address Keymail claims posts to Begin, which keeps the sign-in on the |
| 5 | // door (/signin?continue=<id>) instead of a 303 off-site that the CSP's |
| 6 | // form-action 'self' would refuse. These replace auth_navigation_test.go, |
| 7 | // whose wrapper rastrillo's screen made unnecessary. |
| 8 | // |
| 9 | // Nothing here leaves the machine: the classifier's DNS lookup goes to a |
| 10 | // resolver on loopback that answers "no such name" (so the domain is its |
| 11 | // own Keymail server, as keymail's protocol says), and its HTTPS probes go |
| 12 | // to a transport that answers for kmail.test. Both are process globals, |
| 13 | // swapped for the test and put back. |
| 14 | |
| 15 | import ( |
| 16 | "context" |
| 17 | "io" |
| 18 | "log/slog" |
| 19 | "net" |
| 20 | "net/http" |
| 21 | "net/url" |
| 22 | "path/filepath" |
| 23 | "regexp" |
| 24 | "strings" |
| 25 | "sync/atomic" |
| 26 | "testing" |
| 27 | |
| 28 | fichas "amadan.net/oficina/fichas/internal/fichas" |
| 29 | "amadan.net/rastrillo/rastrillo" |
| 30 | "amadan.net/rastrillo/rastrillo/db" |
| 31 | ) |
| 32 | |
| 33 | const ( |
| 34 | keymailOwner = "km@kmail.test" // Keymail claims it |
| 35 | plainOwner = "pl@plain.test" // a domain that is not Keymail |
| 36 | keymailHost = "kmail.test" // its own server: no _keymail delegation |
| 37 | ) |
| 38 | |
| 39 | // fakeKeymail answers the classifier's probes: kmail.test is a Keymail |
| 40 | // server that claims every address; any other host has no well-known. |
| 41 | type fakeKeymail struct{ probes atomic.Int32 } |
| 42 | |
| 43 | func (f *fakeKeymail) RoundTrip(r *http.Request) (*http.Response, error) { |
| 44 | f.probes.Add(1) |
| 45 | status, body := http.StatusNotFound, "{}" |
| 46 | if r.URL.Host == keymailHost { |
| 47 | switch r.URL.Path { |
| 48 | case "/.well-known/keymail": |
| 49 | status, body = http.StatusOK, `{"version":"1"}` |
| 50 | case "/api/federation/lookup": |
| 51 | status = http.StatusOK |
| 52 | } |
| 53 | } |
| 54 | return &http.Response{StatusCode: status, Body: io.NopCloser(strings.NewReader(body)), Header: http.Header{"Content-Type": {"application/json"}}, Request: r}, nil |
| 55 | } |
| 56 | |
| 57 | // withFakeKeymail swaps the resolver and the default transport for the |
| 58 | // test's length. |
| 59 | func withFakeKeymail(t *testing.T) *fakeKeymail { |
| 60 | t.Helper() |
| 61 | pc, err := net.ListenPacket("udp", "127.0.0.1:0") |
| 62 | if err != nil { |
| 63 | t.Fatal(err) |
| 64 | } |
| 65 | t.Cleanup(func() { pc.Close() }) |
| 66 | go func() { |
| 67 | buf := make([]byte, 1500) |
| 68 | for { |
| 69 | n, from, err := pc.ReadFrom(buf) |
| 70 | if err != nil { |
| 71 | return |
| 72 | } |
| 73 | if n < 12 { |
| 74 | continue |
| 75 | } |
| 76 | // The query back as the answer: a response (QR), recursion |
| 77 | // available, NXDOMAIN, nothing answered. |
| 78 | resp := append([]byte(nil), buf[:n]...) |
| 79 | resp[2] = 0x80 | (resp[2] & 0x01) |
| 80 | resp[3] = 0x80 | 0x03 |
| 81 | pc.WriteTo(resp, from) |
| 82 | } |
| 83 | }() |
| 84 | resolver, transport := net.DefaultResolver, http.DefaultTransport |
| 85 | net.DefaultResolver = &net.Resolver{PreferGo: true, Dial: func(ctx context.Context, _, _ string) (net.Conn, error) { |
| 86 | var d net.Dialer |
| 87 | return d.DialContext(ctx, "udp", pc.LocalAddr().String()) |
| 88 | }} |
| 89 | fake := &fakeKeymail{} |
| 90 | http.DefaultTransport = fake |
| 91 | t.Cleanup(func() { net.DefaultResolver, http.DefaultTransport = resolver, transport }) |
| 92 | return fake |
| 93 | } |
| 94 | |
| 95 | // keymailApp is the app as main.go wires it, owned by keymailOwner and |
| 96 | // plainOwner. |
| 97 | func keymailApp(t *testing.T) (*http.ServeMux, *capturingMailer) { |
| 98 | t.Helper() |
| 99 | logger := slog.New(slog.NewTextHandler(io.Discard, nil)) |
| 100 | d, err := db.Open(filepath.Join(t.TempDir(), "app.db"), logger) |
| 101 | if err != nil { |
| 102 | t.Fatalf("db.Open: %v", err) |
| 103 | } |
| 104 | t.Cleanup(func() { d.Close() }) |
| 105 | cfg := testConfig(t) |
| 106 | cfg.Owners = []string{keymailOwner, plainOwner} |
| 107 | mux, app, err := fichas.App(d, cfg, logger) |
| 108 | if err != nil { |
| 109 | t.Fatalf("App: %v", err) |
| 110 | } |
| 111 | m := &capturingMailer{} |
| 112 | // The fake's two hosts, listed: rastrillo's default (nil, any server) |
| 113 | // dials only public addresses, on a transport of its own, so it never |
| 114 | // reaches the fake (rastrillo v0.45.0). |
| 115 | au, err := fichas.NewAuth(d.Writer(), fichas.AuthEnv{Origin: cfg.Origin, InstanceKey: cfg.InstanceKey, Mailer: m, |
| 116 | KeymailServers: []string{keymailHost, "plain.test"}}, logger, app) |
| 117 | if err != nil { |
| 118 | t.Fatalf("NewAuth: %v", err) |
| 119 | } |
| 120 | app.UseAuth(au) |
| 121 | return mux, m |
| 122 | } |
| 123 | |
| 124 | var metaRefresh = regexp.MustCompile(`<meta http-equiv="refresh" content="0;url=([^"]+)">`) |
| 125 | |
| 126 | // A Keymail address: Begin keeps the sign-in on the door, and the |
| 127 | // Continue step navigates on by itself (a meta refresh, no script) and by |
| 128 | // its link, to exactly the authorize URL for this origin, on the one-way |
| 129 | // door (its link a pill), with no-referrer and no-store, under the CSP |
| 130 | // the app is served with, whose form-action stays 'self'. |
| 131 | func TestAKeymailAddressContinuesOnTheDoor(t *testing.T) { |
| 132 | fake := withFakeKeymail(t) |
| 133 | mux, m := keymailApp(t) |
| 134 | served, closeDB, err := rastrillo.Handler(rastrillo.Options{Mux: mux, ErrorPage: fichas.ErrorPage}) |
| 135 | if err != nil { |
| 136 | t.Fatalf("rastrillo.Handler: %v", err) |
| 137 | } |
| 138 | t.Cleanup(func() { closeDB() }) |
| 139 | |
| 140 | b := newBrowser() |
| 141 | begin := b.post(t, served, "/auth/begin", url.Values{"address": {keymailOwner}}) |
| 142 | loc := begin.Header().Get("Location") |
| 143 | if begin.Code != http.StatusSeeOther || !strings.HasPrefix(loc, "/signin?continue=") { |
| 144 | t.Fatalf("Begin for a Keymail address: %d to %q, want the door's continuation (probes: %d)", begin.Code, loc, fake.probes.Load()) |
| 145 | } |
| 146 | if len(m.sent) != 0 { |
| 147 | t.Error("a Keymail address was mailed a link") |
| 148 | } |
| 149 | |
| 150 | page := b.get(t, served, loc) |
| 151 | if page.Code != http.StatusOK { |
| 152 | t.Fatalf("GET %s: %d", loc, page.Code) |
| 153 | } |
| 154 | body := page.Body.String() |
| 155 | // rastrillo's own words since v0.45.0, which never name Keymail. |
| 156 | if got := titleOf(body); got != "Signing in to Fichas" { |
| 157 | t.Errorf("title %q", got) |
| 158 | } |
| 159 | if !strings.Contains(body, `<div rst-signin-door="one-way">`) { |
| 160 | t.Errorf("the Continue step is not on the one-way door, so its link is no pill:\n%s", body) |
| 161 | } |
| 162 | refresh := metaRefresh.FindStringSubmatch(body) |
| 163 | if refresh == nil { |
| 164 | t.Fatalf("no meta refresh on the Continue step:\n%s", body) |
| 165 | } |
| 166 | dest, err := url.Parse(strings.ReplaceAll(refresh[1], "&", "&")) |
| 167 | if err != nil { |
| 168 | t.Fatal(err) |
| 169 | } |
| 170 | q := dest.Query() |
| 171 | if dest.Scheme != "https" || dest.Host != keymailHost || dest.Path != "/oauth/authorize" || |
| 172 | q.Get("client_id") != testOrigin || q.Get("redirect_uri") != testOrigin+"/auth/callback" || |
| 173 | q.Get("code_challenge_method") != "S256" || q.Get("state") == "" || q.Get("code_challenge") == "" { |
| 174 | t.Errorf("the continuation goes to %s, not this origin's Keymail authorize URL", dest) |
| 175 | } |
| 176 | if !strings.Contains(body, `<a rst-btn="primary block" href="`+refresh[1]+`">Continue</a>`) { |
| 177 | t.Errorf("no Continue link to the same URL:\n%s", body) |
| 178 | } |
| 179 | if page.Header().Get("Referrer-Policy") != "no-referrer" || page.Header().Get("Cache-Control") != "no-store" { |
| 180 | t.Errorf("Referrer-Policy %q, Cache-Control %q", page.Header().Get("Referrer-Policy"), page.Header().Get("Cache-Control")) |
| 181 | } |
| 182 | csp := page.Header().Get("Content-Security-Policy") |
| 183 | if !strings.Contains(csp, "form-action 'self'") || strings.Contains(csp, keymailHost) { |
| 184 | t.Errorf("the served CSP %q was widened for Keymail", csp) |
| 185 | } |
| 186 | if strings.Contains(body, "<script>") { |
| 187 | t.Error("the Continue step needs an inline script") |
| 188 | } |
| 189 | } |
| 190 | |
| 191 | // The continuation is only ever the one this browser's sealed cookie |
| 192 | // holds: an id without the cookie, a cookie another browser holds, or a |
| 193 | // URL in its place draws the door with "That link has expired", never a |
| 194 | // link anywhere. (The field keeps the address this browser typed: that is |
| 195 | // its own attempt, not the continuation.) |
| 196 | func TestTheContinuationGoesNowhereItWasNotSent(t *testing.T) { |
| 197 | withFakeKeymail(t) |
| 198 | h, _ := keymailApp(t) |
| 199 | b := newBrowser() |
| 200 | loc := b.post(t, h, "/auth/begin", url.Values{"address": {keymailOwner}}).Header().Get("Location") |
| 201 | if !strings.HasPrefix(loc, "/signin?continue=") { |
| 202 | t.Fatalf("Begin answered %q", loc) |
| 203 | } |
| 204 | for name, target := range map[string]string{ |
| 205 | "no cookie": loc, |
| 206 | "a URL for id": "/signin?continue=" + url.QueryEscape("https://evil.example/oauth/authorize"), |
| 207 | "another id": "/signin?continue=AAAAAAAAAAAAAAAAAAAAAA", |
| 208 | } { |
| 209 | jar := newBrowser() |
| 210 | if name != "no cookie" { |
| 211 | jar = b |
| 212 | } |
| 213 | body := jar.get(t, h, target).Body.String() |
| 214 | if strings.Contains(body, "http-equiv=\"refresh\"") || strings.Contains(body, "evil.example") || strings.Contains(body, "/oauth/authorize") || strings.Contains(body, ">Continue</a>") { |
| 215 | t.Errorf("%s: the door links somewhere:\n%s", name, body) |
| 216 | } |
| 217 | if !strings.Contains(body, "That link has expired or was already used. Send a new one.") { |
| 218 | t.Errorf("%s: the door does not say the continuation is gone", name) |
| 219 | } |
| 220 | } |
| 221 | } |
| 222 | |
| 223 | // An address Keymail does not claim passes straight through: Begin mails |
| 224 | // a link and answers Sent on the door, with no continuation. |
| 225 | func TestANonKeymailAddressIsSentALink(t *testing.T) { |
| 226 | fake := withFakeKeymail(t) |
| 227 | h, m := keymailApp(t) |
| 228 | rec := post(t, h, "/auth/begin", url.Values{"address": {plainOwner}}) |
| 229 | if loc := rec.Header().Get("Location"); rec.Code != http.StatusSeeOther || !strings.HasPrefix(loc, "/signin?sent=1&attempt=") { |
| 230 | t.Errorf("Begin for a plain address: %d to %q, want Sent", rec.Code, loc) |
| 231 | } |
| 232 | if fake.probes.Load() == 0 { |
| 233 | t.Error("the classifier was never asked: this test proves nothing") |
| 234 | } |
| 235 | if mail := m.last(t); !strings.HasPrefix(mail, plainOwner+"\n") || !linkToken.MatchString(mail) { |
| 236 | t.Errorf("no link mailed:\n%s", mail) |
| 237 | } |
| 238 | } |
| 239 | |