| 1 | package relay |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "crypto/rand" |
| 6 | "crypto/sha256" |
| 7 | "encoding/base64" |
| 8 | "encoding/json" |
| 9 | "fmt" |
| 10 | "io" |
| 11 | "net/http" |
| 12 | "net/http/httptest" |
| 13 | "strings" |
| 14 | "testing" |
| 15 | "time" |
| 16 | |
| 17 | "github.com/gorilla/websocket" |
| 18 | ) |
| 19 | |
| 20 | const testAdmin = "relay-test-admin-token-not-a-real-credential" |
| 21 | |
| 22 | func testServer(t *testing.T, config Config) (*Server, *httptest.Server) { |
| 23 | t.Helper() |
| 24 | config.AdminToken = testAdmin |
| 25 | s, err := New(config) |
| 26 | if err != nil { |
| 27 | t.Fatal(err) |
| 28 | } |
| 29 | httpServer := httptest.NewServer(s) |
| 30 | t.Cleanup(func() { _ = s.Close(); httpServer.Close() }) |
| 31 | return s, httpServer |
| 32 | } |
| 33 | |
| 34 | func createRoom(t *testing.T, serverURL, token string, expectedStatus int) Invitation { |
| 35 | t.Helper() |
| 36 | r, err := http.NewRequest(http.MethodPost, serverURL+"/v1/rooms", nil) |
| 37 | if err != nil { |
| 38 | t.Fatal(err) |
| 39 | } |
| 40 | r.Header.Set("Authorization", "Bearer "+token) |
| 41 | response, err := http.DefaultClient.Do(r) |
| 42 | if err != nil { |
| 43 | t.Fatal(err) |
| 44 | } |
| 45 | defer response.Body.Close() |
| 46 | if response.StatusCode != expectedStatus { |
| 47 | t.Fatalf("create status = %d, want %d", response.StatusCode, expectedStatus) |
| 48 | } |
| 49 | var invitation Invitation |
| 50 | if expectedStatus == http.StatusCreated { |
| 51 | if err := json.NewDecoder(response.Body).Decode(&invitation); err != nil { |
| 52 | t.Fatal(err) |
| 53 | } |
| 54 | } |
| 55 | return invitation |
| 56 | } |
| 57 | |
| 58 | func dial(t *testing.T, serverURL string, invitation Invitation, role, token string, expectedStatus int) *websocket.Conn { |
| 59 | t.Helper() |
| 60 | url := "ws" + strings.TrimPrefix(serverURL, "http") + "/v1/rooms/" + invitation.ID + "/" + role |
| 61 | connection, response, err := websocket.DefaultDialer.Dial(url, http.Header{"Authorization": {"Bearer " + token}}) |
| 62 | if expectedStatus == http.StatusSwitchingProtocols { |
| 63 | if err != nil { |
| 64 | t.Fatalf("connect: %v", err) |
| 65 | } |
| 66 | t.Cleanup(func() { _ = connection.Close() }) |
| 67 | return connection |
| 68 | } |
| 69 | if connection != nil { |
| 70 | _ = connection.Close() |
| 71 | t.Fatal("unexpected accepted connection") |
| 72 | } |
| 73 | if err == nil || response == nil || response.StatusCode != expectedStatus { |
| 74 | t.Fatalf("rejected connect: response=%v, err=%v, want status %d", response, err, expectedStatus) |
| 75 | } |
| 76 | _ = response.Body.Close() |
| 77 | return nil |
| 78 | } |
| 79 | |
| 80 | func read(t *testing.T, connection *websocket.Conn, expected []byte) { |
| 81 | t.Helper() |
| 82 | _ = connection.SetReadDeadline(time.Now().Add(2 * time.Second)) |
| 83 | kind, actual, err := connection.ReadMessage() |
| 84 | if err != nil || kind != websocket.BinaryMessage || !bytes.Equal(actual, expected) { |
| 85 | t.Fatalf("roundtrip kind=%d payload length=%d err=%v", kind, len(actual), err) |
| 86 | } |
| 87 | } |
| 88 | |
| 89 | func waitClosed(t *testing.T, connection *websocket.Conn) { |
| 90 | t.Helper() |
| 91 | _ = connection.SetReadDeadline(time.Now().Add(2 * time.Second)) |
| 92 | if _, _, err := connection.ReadMessage(); err == nil { |
| 93 | t.Fatal("connection remained readable") |
| 94 | } else if timeout, ok := err.(interface{ Timeout() bool }); ok && timeout.Timeout() { |
| 95 | t.Fatal("server did not actively close connection") |
| 96 | } |
| 97 | } |
| 98 | |
| 99 | func TestAuthenticatedSingleUsePair(t *testing.T) { |
| 100 | _, server := testServer(t, Config{MaxRooms: 1}) |
| 101 | createRoom(t, server.URL, "wrong-admin", http.StatusUnauthorized) |
| 102 | i := createRoom(t, server.URL, testAdmin, http.StatusCreated) |
| 103 | createRoom(t, server.URL, testAdmin, http.StatusTooManyRequests) |
| 104 | dial(t, server.URL, i, "host", i.ClientToken, http.StatusUnauthorized) |
| 105 | host := dial(t, server.URL, i, "host", i.HostToken, http.StatusSwitchingProtocols) |
| 106 | dial(t, server.URL, i, "host", i.HostToken, http.StatusConflict) |
| 107 | client := dial(t, server.URL, i, "client", i.ClientToken, http.StatusSwitchingProtocols) |
| 108 | for _, pair := range [][2]*websocket.Conn{{host, client}, {client, host}} { |
| 109 | payload := bytes.Repeat([]byte{0, 9, 255, 42}, 8192) |
| 110 | if err := pair[0].WriteMessage(websocket.BinaryMessage, payload); err != nil { |
| 111 | t.Fatal(err) |
| 112 | } |
| 113 | read(t, pair[1], payload) |
| 114 | } |
| 115 | _ = client.Close() |
| 116 | waitClosed(t, host) |
| 117 | dial(t, server.URL, i, "client", i.ClientToken, http.StatusNotFound) |
| 118 | createRoom(t, server.URL, testAdmin, http.StatusCreated) |
| 119 | } |
| 120 | |
| 121 | func TestRoomExpiryAndShutdownCloseWaitingSockets(t *testing.T) { |
| 122 | for _, shutdown := range []bool{false, true} { |
| 123 | t.Run(map[bool]string{false: "expires", true: "shutdown"}[shutdown], func(t *testing.T) { |
| 124 | service, server := testServer(t, Config{PairTimeout: 200 * time.Millisecond, MaxRooms: 1}) |
| 125 | i := createRoom(t, server.URL, testAdmin, http.StatusCreated) |
| 126 | host := dial(t, server.URL, i, "host", i.HostToken, http.StatusSwitchingProtocols) |
| 127 | if shutdown { |
| 128 | _ = service.Close() |
| 129 | } |
| 130 | waitClosed(t, host) |
| 131 | if shutdown { |
| 132 | createRoom(t, server.URL, testAdmin, http.StatusServiceUnavailable) |
| 133 | } else { |
| 134 | createRoom(t, server.URL, testAdmin, http.StatusCreated) |
| 135 | } |
| 136 | }) |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | func TestDisconnectedWaitingHostReleasesRoom(t *testing.T) { |
| 141 | service, server := testServer(t, Config{MaxRooms: 1, PairTimeout: time.Minute}) |
| 142 | invite := createRoom(t, server.URL, testAdmin, http.StatusCreated) |
| 143 | host := dial(t, server.URL, invite, "host", invite.HostToken, http.StatusSwitchingProtocols) |
| 144 | _ = host.Close() |
| 145 | deadline := time.Now().Add(2 * time.Second) |
| 146 | for { |
| 147 | service.mu.Lock() |
| 148 | _, stale := service.rooms[invite.ID] |
| 149 | service.mu.Unlock() |
| 150 | if !stale { |
| 151 | break |
| 152 | } |
| 153 | if time.Now().After(deadline) { |
| 154 | t.Fatal("disconnected waiting host still occupies its room") |
| 155 | } |
| 156 | time.Sleep(10 * time.Millisecond) |
| 157 | } |
| 158 | createRoom(t, server.URL, testAdmin, http.StatusCreated) |
| 159 | } |
| 160 | |
| 161 | func TestInvalidStreamClosesBothDirections(t *testing.T) { |
| 162 | for _, tc := range []struct { |
| 163 | name string |
| 164 | kind int |
| 165 | size int |
| 166 | }{{"text", websocket.TextMessage, 10}, {"oversize", websocket.BinaryMessage, MaxFrameSize + 1}} { |
| 167 | t.Run(tc.name, func(t *testing.T) { |
| 168 | _, server := testServer(t, Config{}) |
| 169 | i := createRoom(t, server.URL, testAdmin, http.StatusCreated) |
| 170 | host := dial(t, server.URL, i, "host", i.HostToken, http.StatusSwitchingProtocols) |
| 171 | client := dial(t, server.URL, i, "client", i.ClientToken, http.StatusSwitchingProtocols) |
| 172 | _ = client.WriteMessage(tc.kind, make([]byte, tc.size)) |
| 173 | waitClosed(t, host) |
| 174 | waitClosed(t, client) |
| 175 | }) |
| 176 | } |
| 177 | } |
| 178 | |
| 179 | func TestActiveIdleTimeoutAndServerClose(t *testing.T) { |
| 180 | for _, shutdown := range []bool{false, true} { |
| 181 | t.Run(map[bool]string{false: "idle", true: "shutdown"}[shutdown], func(t *testing.T) { |
| 182 | service, server := testServer(t, Config{IdleTimeout: 100 * time.Millisecond}) |
| 183 | i := createRoom(t, server.URL, testAdmin, http.StatusCreated) |
| 184 | host := dial(t, server.URL, i, "host", i.HostToken, http.StatusSwitchingProtocols) |
| 185 | client := dial(t, server.URL, i, "client", i.ClientToken, http.StatusSwitchingProtocols) |
| 186 | if shutdown { |
| 187 | _ = service.Close() |
| 188 | } |
| 189 | waitClosed(t, host) |
| 190 | waitClosed(t, client) |
| 191 | }) |
| 192 | } |
| 193 | } |
| 194 | |
| 195 | func TestOneWayOutputKeepsRoomAlive(t *testing.T) { |
| 196 | _, server := testServer(t, Config{IdleTimeout: 200 * time.Millisecond}) |
| 197 | i := createRoom(t, server.URL, testAdmin, http.StatusCreated) |
| 198 | host := dial(t, server.URL, i, "host", i.HostToken, http.StatusSwitchingProtocols) |
| 199 | client := dial(t, server.URL, i, "client", i.ClientToken, http.StatusSwitchingProtocols) |
| 200 | ticker := time.NewTicker(30 * time.Millisecond) |
| 201 | defer ticker.Stop() |
| 202 | for n := 0; n < 15; n++ { |
| 203 | <-ticker.C |
| 204 | payload := []byte{byte(n)} |
| 205 | if err := host.WriteMessage(websocket.BinaryMessage, payload); err != nil { |
| 206 | t.Fatal(err) |
| 207 | } |
| 208 | read(t, client, payload) |
| 209 | } |
| 210 | |
| 211 | waitClosed(t, host) |
| 212 | waitClosed(t, client) |
| 213 | } |
| 214 | |
| 215 | func TestNoURLCredentialsOrBrowserOrigins(t *testing.T) { |
| 216 | _, server := testServer(t, Config{}) |
| 217 | for _, tc := range []struct{ path, origin string }{{"/v1/rooms?token=not-secret", ""}, {"/v1/rooms", "https://untrusted.example"}} { |
| 218 | r, _ := http.NewRequest(http.MethodPost, server.URL+tc.path, nil) |
| 219 | r.Header.Set("Authorization", "Bearer "+testAdmin) |
| 220 | r.Header.Set("Origin", tc.origin) |
| 221 | response, err := http.DefaultClient.Do(r) |
| 222 | if err != nil { |
| 223 | t.Fatal(err) |
| 224 | } |
| 225 | body, _ := io.ReadAll(response.Body) |
| 226 | _ = response.Body.Close() |
| 227 | if response.StatusCode != http.StatusBadRequest || strings.Contains(string(body), testAdmin) { |
| 228 | t.Fatalf("unexpected rejection: %d %q", response.StatusCode, body) |
| 229 | } |
| 230 | } |
| 231 | } |
| 232 | |
| 233 | func TestSavedDeviceReceivesNewInvitationAfterDisconnect(t *testing.T) { |
| 234 | _, server := testServer(t, Config{}) |
| 235 | key := make([]byte, 32) |
| 236 | if _, err := rand.Read(key); err != nil { |
| 237 | t.Fatal(err) |
| 238 | } |
| 239 | secret := base64.RawURLEncoding.EncodeToString(key) |
| 240 | digest := sha256.Sum256(key) |
| 241 | body := fmt.Sprintf(`{"lookup_hash":"%x"}`, digest) |
| 242 | create := func(status int) Invitation { |
| 243 | t.Helper() |
| 244 | req, _ := http.NewRequest("POST", server.URL+"/v1/rooms", strings.NewReader(body)) |
| 245 | req.Header.Set("Authorization", "Bearer "+testAdmin) |
| 246 | res, err := http.DefaultClient.Do(req) |
| 247 | if err != nil { |
| 248 | t.Fatal(err) |
| 249 | } |
| 250 | defer res.Body.Close() |
| 251 | if res.StatusCode != status { |
| 252 | t.Fatalf("room: %d, want %d", res.StatusCode, status) |
| 253 | } |
| 254 | var i Invitation |
| 255 | if status == 201 { |
| 256 | if err = json.NewDecoder(res.Body).Decode(&i); err != nil { |
| 257 | t.Fatal(err) |
| 258 | } |
| 259 | } |
| 260 | return i |
| 261 | } |
| 262 | lookup := func(token string) (int, Invitation) { |
| 263 | t.Helper() |
| 264 | req, _ := http.NewRequest("GET", server.URL+"/v1/invitation", nil) |
| 265 | req.Header.Set("Authorization", "Bearer "+token) |
| 266 | res, err := http.DefaultClient.Do(req) |
| 267 | if err != nil { |
| 268 | t.Fatal(err) |
| 269 | } |
| 270 | defer res.Body.Close() |
| 271 | var i Invitation |
| 272 | if res.StatusCode == 200 { |
| 273 | if err = json.NewDecoder(res.Body).Decode(&i); err != nil { |
| 274 | t.Fatal(err) |
| 275 | } |
| 276 | if i.HostToken != "" || res.Header.Get("Cache-Control") != "no-store" { |
| 277 | t.Fatal("lookup exposed a host credential or a cacheable ticket") |
| 278 | } |
| 279 | } |
| 280 | return res.StatusCode, i |
| 281 | } |
| 282 | first := create(201) |
| 283 | if status, _ := lookup(secret); status != 404 { |
| 284 | t.Fatal("advertised a room before host joined") |
| 285 | } |
| 286 | host := dial(t, server.URL, first, "host", first.HostToken, 101) |
| 287 | create(409) |
| 288 | if status, _ := lookup(base64.RawURLEncoding.EncodeToString(make([]byte, 32))); status != 404 { |
| 289 | t.Fatal("unknown device looked up a room") |
| 290 | } |
| 291 | wait := func(i Invitation) { |
| 292 | t.Helper() |
| 293 | deadline := time.Now().Add(time.Second) |
| 294 | for time.Now().Before(deadline) { |
| 295 | status, found := lookup(secret) |
| 296 | if status == 200 { |
| 297 | if found.ID != i.ID || found.ClientToken != i.ClientToken { |
| 298 | t.Fatal("looked up another device or stale ticket") |
| 299 | } |
| 300 | return |
| 301 | } |
| 302 | time.Sleep(5 * time.Millisecond) |
| 303 | } |
| 304 | t.Fatal("room did not become discoverable") |
| 305 | } |
| 306 | wait(first) |
| 307 | client := dial(t, server.URL, first, "client", first.ClientToken, 101) |
| 308 | if status, _ := lookup(secret); status != 404 { |
| 309 | t.Fatal("claimed client ticket could be fetched") |
| 310 | } |
| 311 | client.Close() |
| 312 | waitClosed(t, host) |
| 313 | if status, _ := lookup(secret); status != 404 { |
| 314 | t.Fatal("closed room still discoverable") |
| 315 | } |
| 316 | second := create(201) |
| 317 | dial(t, server.URL, second, "host", second.HostToken, 101) |
| 318 | if first.ID == second.ID || first.ClientToken == second.ClientToken { |
| 319 | t.Fatal("reused a one-time transport credential") |
| 320 | } |
| 321 | wait(second) |
| 322 | } |
| 323 | |
| 324 | func TestPublicRoomCreationKeepsRoleAuthentication(t *testing.T) { |
| 325 | for _, public := range []bool{false, true} { |
| 326 | _, server := testServer(t, Config{PublicRooms: public}) |
| 327 | response, err := http.Post(server.URL+"/v1/rooms", "application/json", nil) |
| 328 | if err != nil { |
| 329 | t.Fatal(err) |
| 330 | } |
| 331 | defer response.Body.Close() |
| 332 | if !public { |
| 333 | if response.StatusCode != http.StatusUnauthorized { |
| 334 | t.Fatal("private relay allowed anonymous room creation") |
| 335 | } |
| 336 | continue |
| 337 | } |
| 338 | var room Invitation |
| 339 | if response.StatusCode != http.StatusCreated || json.NewDecoder(response.Body).Decode(&room) != nil { |
| 340 | t.Fatal("public relay did not create a room") |
| 341 | } |
| 342 | dial(t, server.URL, room, "client", room.HostToken, http.StatusUnauthorized) |
| 343 | dial(t, server.URL, room, "host", room.HostToken, http.StatusSwitchingProtocols) |
| 344 | } |
| 345 | } |