| 1 | package docs |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "crypto/sha256" |
| 6 | "encoding/base64" |
| 7 | "encoding/json" |
| 8 | "fmt" |
| 9 | "html" |
| 10 | "io" |
| 11 | "net" |
| 12 | "net/http" |
| 13 | "net/http/cookiejar" |
| 14 | "net/http/httptest" |
| 15 | "net/url" |
| 16 | "os" |
| 17 | "os/exec" |
| 18 | "regexp" |
| 19 | "strings" |
| 20 | "sync" |
| 21 | "testing" |
| 22 | "time" |
| 23 | ) |
| 24 | |
| 25 | // Process isolation keeps the resolver and default transport overrides out of |
| 26 | // concurrent tests. Every DNS packet and HTTPS request stays in this fixture. |
| 27 | func TestKeymailOAuthActualIntegration(t *testing.T) { |
| 28 | if os.Getenv("DOCS_KEYMAIL_TEST_CHILD") == "1" { |
| 29 | keymailOAuthChild(t) |
| 30 | return |
| 31 | } |
| 32 | ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second) |
| 33 | defer cancel() |
| 34 | cmd := exec.CommandContext(ctx, os.Args[0], "-test.run=^TestKeymailOAuthActualIntegration$", "-test.count=1", "-test.v") |
| 35 | cmd.Dir = t.TempDir() |
| 36 | for _, e := range os.Environ() { |
| 37 | if strings.HasPrefix(e, "DOCS_") || strings.HasPrefix(e, "HOME_") || strings.HasPrefix(e, "CARLOS_") || strings.HasPrefix(e, "AWS_") { |
| 38 | continue |
| 39 | } |
| 40 | cmd.Env = append(cmd.Env, e) |
| 41 | } |
| 42 | cmd.Env = append(cmd.Env, "DOCS_KEYMAIL_TEST_CHILD=1") |
| 43 | out, err := cmd.CombinedOutput() |
| 44 | if err != nil { |
| 45 | t.Fatalf("isolated OAuth test: %v\n%s", err, out) |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | type keymailTestTransport func(*http.Request) (*http.Response, error) |
| 50 | |
| 51 | func (f keymailTestTransport) RoundTrip(r *http.Request) (*http.Response, error) { return f(r) } |
| 52 | |
| 53 | func keymailOAuthChild(t *testing.T) { |
| 54 | dns, err := net.ListenPacket("udp", "127.0.0.1:0") |
| 55 | if err != nil { |
| 56 | t.Fatal(err) |
| 57 | } |
| 58 | defer dns.Close() |
| 59 | go func() { |
| 60 | b := make([]byte, 4096) |
| 61 | for { |
| 62 | n, a, e := dns.ReadFrom(b) |
| 63 | if e != nil { |
| 64 | return |
| 65 | } |
| 66 | if n < 12 { |
| 67 | continue |
| 68 | } |
| 69 | reply := append([]byte(nil), b[:n]...) |
| 70 | reply[2] = 0x81 |
| 71 | reply[3] = 0x83 |
| 72 | for i := 6; i < 12; i++ { |
| 73 | reply[i] = 0 |
| 74 | } |
| 75 | _, _ = dns.WriteTo(reply, a) |
| 76 | } |
| 77 | }() |
| 78 | net.DefaultResolver = &net.Resolver{PreferGo: true, Dial: func(ctx context.Context, _, _ string) (net.Conn, error) { |
| 79 | return (&net.Dialer{}).DialContext(ctx, "udp", dns.LocalAddr().String()) |
| 80 | }} |
| 81 | const origin = "https://docs.oauth.test" |
| 82 | const provider = "mail.oauth.test" |
| 83 | // auth reaches only listed servers through its guard, so the |
| 84 | // fixture's own unexpected-host check below is a second line: a |
| 85 | // request to any other host is refused before it gets here. |
| 86 | keymailTestServers = []string{provider} |
| 87 | for _, tc := range []struct { |
| 88 | name, address, returned string |
| 89 | admitted, detected, badState, badPKCE bool |
| 90 | }{ |
| 91 | {name: "allowed OAuth", address: "member@mail.oauth.test", admitted: true, detected: true}, |
| 92 | {name: "denied OAuth", address: "outsider@mail.oauth.test", detected: true}, |
| 93 | {name: "wrong address", address: "member@mail.oauth.test", returned: "outsider@mail.oauth.test", admitted: true, detected: true}, |
| 94 | {name: "wrong state", address: "member@mail.oauth.test", admitted: true, detected: true, badState: true}, |
| 95 | {name: "wrong PKCE", address: "member@mail.oauth.test", admitted: true, detected: true, badPKCE: true}, |
| 96 | {name: "ordinary mail", address: "member@mail.oauth.test", admitted: true}, |
| 97 | {name: "denied ordinary mail", address: "outsider@mail.oauth.test"}, |
| 98 | } { |
| 99 | t.Run(tc.name, func(t *testing.T) { |
| 100 | var mu sync.Mutex |
| 101 | calls := map[string]int{} |
| 102 | challenge := "" |
| 103 | exchanges := 0 |
| 104 | http.DefaultTransport = keymailTestTransport(func(r *http.Request) (*http.Response, error) { |
| 105 | mu.Lock() |
| 106 | defer mu.Unlock() |
| 107 | if r.URL.Scheme != "https" || r.URL.Host != provider { |
| 108 | t.Errorf("unexpected outbound request %s", r.URL) |
| 109 | return nil, fmt.Errorf("fixture refuses outbound request") |
| 110 | } |
| 111 | calls[r.URL.Path]++ |
| 112 | status := http.StatusOK |
| 113 | var body any |
| 114 | switch r.URL.Path { |
| 115 | case "/.well-known/keymail": |
| 116 | body = map[string]any{"version": "1", "reauth": true} |
| 117 | case "/api/federation/lookup": |
| 118 | if r.URL.Query().Get("addr") != tc.address { |
| 119 | t.Errorf("wrong lookup address") |
| 120 | } |
| 121 | if !tc.detected { |
| 122 | status = http.StatusNotFound |
| 123 | } |
| 124 | body = map[string]bool{"ok": tc.detected} |
| 125 | case "/api/oauth/token": |
| 126 | exchanges++ |
| 127 | var in map[string]string |
| 128 | if r.Method != "POST" || json.NewDecoder(io.LimitReader(r.Body, 8192)).Decode(&in) != nil { |
| 129 | t.Error("invalid token request") |
| 130 | } |
| 131 | sum := sha256.Sum256([]byte(in["code_verifier"])) |
| 132 | if in["client_id"] != origin || in["redirect_uri"] != origin+"/auth/callback" || in["code"] != "one-code" || base64.RawURLEncoding.EncodeToString(sum[:]) != challenge || exchanges != 1 { |
| 133 | status = http.StatusBadRequest |
| 134 | body = map[string]string{"error": "invalid grant"} |
| 135 | } else { |
| 136 | address := tc.address |
| 137 | if tc.returned != "" { |
| 138 | address = tc.returned |
| 139 | } |
| 140 | body = map[string]any{"access_token": "synthetic-token", "token_type": "bearer", "address": address, "auth_time": time.Now().Unix()} |
| 141 | } |
| 142 | default: |
| 143 | t.Errorf("unexpected endpoint %s", r.URL.Path) |
| 144 | status = http.StatusNotFound |
| 145 | } |
| 146 | raw, _ := json.Marshal(body) |
| 147 | return &http.Response{StatusCode: status, Header: make(http.Header), Body: io.NopCloser(strings.NewReader(string(raw))), Request: r}, nil |
| 148 | }) |
| 149 | app, e := NewForTestWith(t, Config{Origin: origin, AllowedAddresses: "member@mail.oauth.test"}) |
| 150 | if e != nil { |
| 151 | t.Fatal(e) |
| 152 | } |
| 153 | jar, _ := cookiejar.New(nil) |
| 154 | request := func(method, path, body string) *httptest.ResponseRecorder { |
| 155 | u, _ := url.Parse(origin + path) |
| 156 | req := httptest.NewRequest(method, u.String(), strings.NewReader(body)) |
| 157 | req.Header.Set("Origin", origin) |
| 158 | req.Header.Set("Sec-Fetch-Site", "same-origin") |
| 159 | req.Header.Set("Content-Type", "application/x-www-form-urlencoded") |
| 160 | for _, c := range jar.Cookies(u) { |
| 161 | req.AddCookie(c) |
| 162 | } |
| 163 | rec := httptest.NewRecorder() |
| 164 | app.Handler().ServeHTTP(rec, req) |
| 165 | jar.SetCookies(u, rec.Result().Cookies()) |
| 166 | return rec |
| 167 | } |
| 168 | rec := request("POST", "/signin", url.Values{"address": {tc.address}}.Encode()) |
| 169 | mu.Lock() |
| 170 | lookups := calls["/api/federation/lookup"] |
| 171 | mu.Unlock() |
| 172 | if lookups != 1 { |
| 173 | t.Fatalf("actual classifier lookup count=%d, status=%d", lookups, rec.Code) |
| 174 | } |
| 175 | if !tc.detected { |
| 176 | if rec.Code != 303 || !regexp.MustCompile(`^/signin\?sent=1&attempt=[A-Za-z0-9_-]+$`).MatchString(rec.Header().Get("Location")) { |
| 177 | t.Fatalf("mail start: %d %s", rec.Code, rec.Header().Get("Location")) |
| 178 | } |
| 179 | app.signinMail.wait() |
| 180 | app.mailRecorder.mu.Lock() |
| 181 | sent := app.mailRecorder.sends |
| 182 | app.mailRecorder.mu.Unlock() |
| 183 | want := 0 |
| 184 | if tc.admitted { |
| 185 | want = 1 |
| 186 | } |
| 187 | if sent != want { |
| 188 | t.Fatalf("mail deliveries=%d want%d", sent, want) |
| 189 | } |
| 190 | return |
| 191 | } |
| 192 | // The sign-in screen keeps a Keymail start on the door, so |
| 193 | // form-action stays 'self': Begin answers with the door's |
| 194 | // continuation (?continue=), whose page leaves for Keymail by |
| 195 | // a meta refresh and a link, and discloses no referrer. |
| 196 | continuation := rec.Header().Get("Location") |
| 197 | if rec.Code != 303 || !strings.HasPrefix(continuation, "/signin?continue=") { |
| 198 | t.Fatalf("OAuth start: %d %q, want the door's continuation", rec.Code, continuation) |
| 199 | } |
| 200 | rec = request("GET", continuation, "") |
| 201 | if rec.Code != 200 || rec.Header().Get("Location") != "" || rec.Header().Get("Referrer-Policy") != "no-referrer" || rec.Header().Get("Cache-Control") != "no-store" { |
| 202 | t.Fatalf("OAuth continuation: %d %q %q", rec.Code, rec.Header().Get("Referrer-Policy"), rec.Header().Get("Cache-Control")) |
| 203 | } |
| 204 | if !strings.Contains(rec.Body.String(), `http-equiv="refresh"`) || !strings.Contains(rec.Body.String(), "estilo-door") { |
| 205 | t.Fatal("the continuation is not the door, leaving for Keymail") |
| 206 | } |
| 207 | var target *url.URL |
| 208 | for _, m := range regexp.MustCompile(`href="([^"]+)"`).FindAllStringSubmatch(rec.Body.String(), -1) { |
| 209 | u, e := url.Parse(html.UnescapeString(m[1])) |
| 210 | if e == nil && u.Host == provider && u.Path == "/oauth/authorize" { |
| 211 | target = u |
| 212 | } |
| 213 | } |
| 214 | if target == nil { |
| 215 | t.Fatal("no generated OAuth authorize link") |
| 216 | } |
| 217 | q := target.Query() |
| 218 | if q.Get("client_id") != origin || q.Get("redirect_uri") != origin+"/auth/callback" || q.Get("code_challenge_method") != "S256" || q.Get("prompt") != "login" || q.Get("state") == "" { |
| 219 | t.Fatal("OAuth bindings missing") |
| 220 | } |
| 221 | mu.Lock() |
| 222 | challenge = q.Get("code_challenge") |
| 223 | if tc.badPKCE { |
| 224 | challenge = "wrong" |
| 225 | } |
| 226 | mu.Unlock() |
| 227 | state := q.Get("state") |
| 228 | if tc.badState { |
| 229 | state = "wrong" |
| 230 | } |
| 231 | callback := request("GET", "/auth/callback?"+url.Values{"state": {state}, "code": {"one-code"}}.Encode(), "") |
| 232 | allowed := tc.admitted && tc.returned == "" && !tc.badState && !tc.badPKCE |
| 233 | if !tc.admitted && tc.returned == "" && !tc.badState && !tc.badPKCE { |
| 234 | // A verified address the allowlist refuses gets the door, |
| 235 | // rendered in the refusal's own 403 — not rastrillo's bare |
| 236 | // text, and not a query anybody could type. |
| 237 | body := callback.Body.String() |
| 238 | if callback.Code != http.StatusForbidden || !strings.Contains(body, `name="address"`) || !strings.Contains(body, "docs.signin.error.refused") && !strings.Contains(body, "can’t sign in to Docs") { |
| 239 | t.Fatalf("refused OAuth: %d, want the door with the refusal in a 403:\n%s", callback.Code, body) |
| 240 | } |
| 241 | spoof := request("GET", "/signin?err=refused", "") |
| 242 | if strings.Contains(spoof.Body.String(), "can’t sign in to Docs") { |
| 243 | t.Fatal("anybody can show the refusal by visiting /signin?err=refused") |
| 244 | } |
| 245 | } |
| 246 | home := request("GET", "/", "") |
| 247 | if allowed { |
| 248 | if callback.Code != 303 || home.Code != 200 { |
| 249 | t.Fatalf("authorized callback=%d home=%d", callback.Code, home.Code) |
| 250 | } |
| 251 | } else if home.Code == 200 { |
| 252 | t.Fatal("refused OAuth created admitted session") |
| 253 | } |
| 254 | if !allowed { |
| 255 | u, _ := url.Parse(origin) |
| 256 | for _, c := range jar.Cookies(u) { |
| 257 | if strings.Contains(c.Name, "session") { |
| 258 | t.Fatal("refused OAuth minted session") |
| 259 | } |
| 260 | } |
| 261 | } |
| 262 | app.signinMail.wait() |
| 263 | app.mailRecorder.mu.Lock() |
| 264 | sent := app.mailRecorder.sends |
| 265 | app.mailRecorder.mu.Unlock() |
| 266 | if sent != 0 { |
| 267 | t.Fatalf("OAuth sent %d emails", sent) |
| 268 | } |
| 269 | mu.Lock() |
| 270 | got := exchanges |
| 271 | mu.Unlock() |
| 272 | want := 1 |
| 273 | if tc.badState { |
| 274 | want = 0 |
| 275 | } |
| 276 | if got != want { |
| 277 | t.Fatalf("token exchanges=%d want%d", got, want) |
| 278 | } |
| 279 | // A callback with another attempt's state is answered Expired and |
| 280 | // leaves this browser's attempt alone (rastrillo's sign-in screen: |
| 281 | // a late callback from another tab must not throw away a newer |
| 282 | // attempt), so this attempt's own callback still completes it, once. |
| 283 | if tc.badState { |
| 284 | request("GET", "/auth/callback?"+url.Values{"state": {q.Get("state")}, "code": {"one-code"}}.Encode(), "") |
| 285 | mu.Lock() |
| 286 | got = exchanges |
| 287 | mu.Unlock() |
| 288 | if want = 1; got != want { |
| 289 | t.Fatalf("the attempt's own callback after a stray one: token exchanges=%d want%d", got, want) |
| 290 | } |
| 291 | } |
| 292 | // Pending state is cleared after callback: replay cannot reach exchange. |
| 293 | request("GET", "/auth/callback?"+url.Values{"state": {q.Get("state")}, "code": {"one-code"}}.Encode(), "") |
| 294 | mu.Lock() |
| 295 | defer mu.Unlock() |
| 296 | if exchanges != want { |
| 297 | t.Fatal("callback replay reached token endpoint") |
| 298 | } |
| 299 | }) |
| 300 | } |
| 301 | } |
| 302 | |