| 1 | package mobilelink_test |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "context" |
| 6 | "crypto/ecdsa" |
| 7 | "crypto/elliptic" |
| 8 | "crypto/rand" |
| 9 | "crypto/x509" |
| 10 | "encoding/json" |
| 11 | "fmt" |
| 12 | "io" |
| 13 | "net" |
| 14 | "net/http" |
| 15 | "net/http/httptest" |
| 16 | "net/url" |
| 17 | "os" |
| 18 | "path/filepath" |
| 19 | "strings" |
| 20 | "sync/atomic" |
| 21 | "testing" |
| 22 | "time" |
| 23 | |
| 24 | "github.com/gorilla/websocket" |
| 25 | "github.com/sylvinus/agent-vm/internal/mobilelink" |
| 26 | "github.com/sylvinus/agent-vm/internal/mobilelink/nativeclient" |
| 27 | "github.com/sylvinus/agent-vm/internal/relay" |
| 28 | "github.com/sylvinus/agent-vm/internal/remotelink" |
| 29 | "golang.org/x/net/http2" |
| 30 | ) |
| 31 | |
| 32 | type device struct{ key *ecdsa.PrivateKey } |
| 33 | |
| 34 | func (d device) PublicKeyDER() ([]byte, error) { return x509.MarshalPKIXPublicKey(&d.key.PublicKey) } |
| 35 | func (d device) SignSHA256(hash []byte) ([]byte, error) { |
| 36 | return ecdsa.SignASN1(rand.Reader, d.key, hash) |
| 37 | } |
| 38 | |
| 39 | const session = "/api/mobile/cli/sessions/12345678-1234-4321-aaaa-123456789abc" |
| 40 | |
| 41 | type fixture struct { |
| 42 | base string |
| 43 | backend *mobilelink.Workbench |
| 44 | identity *remotelink.Identity |
| 45 | locked atomic.Bool |
| 46 | upstream atomic.Int32 |
| 47 | activeGet chan struct{} |
| 48 | finishGet chan struct{} |
| 49 | } |
| 50 | |
| 51 | func newFixture(t *testing.T) *fixture { |
| 52 | t.Helper() |
| 53 | f := &fixture{activeGet: make(chan struct{}, 1), finishGet: make(chan struct{})} |
| 54 | id, err := remotelink.NewIdentity() |
| 55 | if err != nil { |
| 56 | t.Fatal(err) |
| 57 | } |
| 58 | f.identity = id |
| 59 | ticket := strings.Repeat("test-ticket-", 5) |
| 60 | const cookie = "local-cookie-must-stay-on-host" |
| 61 | control := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| 62 | if r.Header.Get("Origin") != "http://"+r.Host { |
| 63 | http.Error(w, "origin refused", 403) |
| 64 | return |
| 65 | } |
| 66 | _, port, _ := net.SplitHostPort(r.Host) |
| 67 | name := "cage_session_" + port |
| 68 | if r.URL.Path == "/api/session" { |
| 69 | var in struct{ Token string } |
| 70 | if r.Method != http.MethodPost || json.NewDecoder(r.Body).Decode(&in) != nil || in.Token != ticket { |
| 71 | http.Error(w, "ticket refused", 401) |
| 72 | return |
| 73 | } |
| 74 | http.SetCookie(w, &http.Cookie{Name: name, Value: cookie, Path: "/", HttpOnly: true}) |
| 75 | return |
| 76 | } |
| 77 | c, err := r.Cookie(name) |
| 78 | if err != nil || c.Value != cookie || len(r.Cookies()) != 1 || r.Header.Get("Authorization") != "" { |
| 79 | http.Error(w, "session refused", 401) |
| 80 | return |
| 81 | } |
| 82 | f.upstream.Add(1) |
| 83 | if f.locked.Load() { |
| 84 | http.Error(w, "locked", 423) |
| 85 | return |
| 86 | } |
| 87 | w.Header().Set("Content-Type", "application/json") |
| 88 | switch { |
| 89 | case r.URL.Path == "/api/mobile/cli/projects": |
| 90 | _, _ = io.WriteString(w, `{"projects":["B"]}`) |
| 91 | case r.URL.Path == session && r.URL.RawQuery == "after=2": |
| 92 | f.activeGet <- struct{}{} |
| 93 | select { |
| 94 | case <-f.finishGet: |
| 95 | w.WriteHeader(204) |
| 96 | case <-r.Context().Done(): |
| 97 | } |
| 98 | case (r.URL.Path == session+"/messages" || r.URL.Path == session+"/approval") && r.Method == http.MethodPost: |
| 99 | data, _ := io.ReadAll(r.Body) |
| 100 | w.WriteHeader(201) |
| 101 | _, _ = w.Write(data) |
| 102 | case r.URL.Path == "/api/mobile/cli/sessions": |
| 103 | http.Redirect(w, r, "/api/account", 307) |
| 104 | default: |
| 105 | t.Errorf("unexpected local upstream operation: %s", r.URL.Path) |
| 106 | http.NotFound(w, r) |
| 107 | } |
| 108 | })) |
| 109 | t.Cleanup(control.Close) |
| 110 | f.backend, err = mobilelink.OpenWorkbench(context.Background(), control.URL, ticket) |
| 111 | if err != nil { |
| 112 | t.Fatal(err) |
| 113 | } |
| 114 | t.Cleanup(f.backend.Close) |
| 115 | r, err := relay.New(relay.Config{AdminToken: strings.Repeat("t", 64)}) |
| 116 | if err != nil { |
| 117 | t.Fatal(err) |
| 118 | } |
| 119 | rs := httptest.NewServer(r) |
| 120 | t.Cleanup(rs.Close) |
| 121 | t.Cleanup(func() { _ = r.Close() }) |
| 122 | f.base = rs.URL |
| 123 | return f |
| 124 | } |
| 125 | |
| 126 | func (f *fixture) startHost(t *testing.T, pin string) relay.Invitation { |
| 127 | t.Helper() |
| 128 | ctx, cancel := context.WithCancel(context.Background()) |
| 129 | room, err := mobilelink.CreateRoom(ctx, f.base, strings.Repeat("t", 64)) |
| 130 | if err != nil { |
| 131 | t.Fatal(err) |
| 132 | } |
| 133 | done := make(chan error, 1) |
| 134 | go func() { done <- mobilelink.ServeHost(ctx, f.base, room.ID, room.HostToken, f.identity, pin, f.backend) }() |
| 135 | t.Cleanup(func() { |
| 136 | cancel() |
| 137 | select { |
| 138 | case <-done: |
| 139 | case <-time.After(3 * time.Second): |
| 140 | t.Error("host bridge did not stop") |
| 141 | } |
| 142 | }) |
| 143 | return room |
| 144 | } |
| 145 | |
| 146 | func TestNativeRequestsAcrossRealRelay(t *testing.T) { |
| 147 | f := newFixture(t) |
| 148 | key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| 149 | if err != nil { |
| 150 | t.Fatal(err) |
| 151 | } |
| 152 | d := device{key} |
| 153 | pin, err := nativeclient.Fingerprint(d) |
| 154 | if err != nil { |
| 155 | t.Fatal(err) |
| 156 | } |
| 157 | room := f.startHost(t, pin) |
| 158 | c, err := nativeclient.Open(f.base, room.ID, room.ClientToken, f.identity.Pin, d) |
| 159 | if err != nil { |
| 160 | t.Fatal(err) |
| 161 | } |
| 162 | t.Cleanup(func() { _ = c.Close() }) |
| 163 | p, err := c.Request("GET", "/api/mobile/cli/projects", nil) |
| 164 | if err != nil || p.Status != 200 || p.ContentType != "application/json" || !bytes.Contains(p.Body, []byte("B")) { |
| 165 | t.Fatalf("project read failed: %v", err) |
| 166 | } |
| 167 | done := make(chan error, 1) |
| 168 | go func() { |
| 169 | _, err := c.Request("GET", session+"?after=2", nil) |
| 170 | done <- err |
| 171 | }() |
| 172 | select { |
| 173 | case <-f.activeGet: |
| 174 | case <-time.After(3 * time.Second): |
| 175 | t.Fatal("revision read did not reach host") |
| 176 | } |
| 177 | message := []byte(`{"text":"在项目 B 运行测试"}`) |
| 178 | p, err = c.Request("POST", session+"/messages", message) |
| 179 | close(f.finishGet) |
| 180 | if err != nil || p.Status != 201 || !bytes.Equal(p.Body, message) { |
| 181 | t.Fatalf("concurrent message submission failed: %v", err) |
| 182 | } |
| 183 | if err := <-done; err != nil { |
| 184 | t.Fatal(err) |
| 185 | } |
| 186 | decision := []byte(`{"request_id":"12345678-1234-4321-aaaa-123456789abc","approval_id":"12345678-1234-4321-aaaa-123456789abd","allow":false}`) |
| 187 | p, err = c.Request("POST", session+"/approval", decision) |
| 188 | if err != nil || p.Status != 201 || !bytes.Equal(p.Body, decision) { |
| 189 | t.Fatalf("approval reply failed: %v", err) |
| 190 | } |
| 191 | before := f.upstream.Load() |
| 192 | for _, path := range []string{"/api/account", "/api/launch", "/api/mobile/cli/sessions/../projects", session + "/%73top", session + "?after=1&after=2", session + "?after=-1", "http://localhost/api/mobile/cli/projects", "//localhost/api/mobile/cli/projects"} { |
| 193 | if _, err := c.Request("GET", path, nil); err == nil { |
| 194 | t.Errorf("unsafe operation accepted: %s", path) |
| 195 | } |
| 196 | } |
| 197 | if f.upstream.Load() != before { |
| 198 | t.Fatal("refused operation reached host") |
| 199 | } |
| 200 | p, err = c.Request("GET", "/api/mobile/cli/sessions", nil) |
| 201 | if err != nil || p.Status != 502 || f.upstream.Load() != before+1 { |
| 202 | t.Fatal("host redirect was followed or exposed") |
| 203 | } |
| 204 | f.locked.Store(true) |
| 205 | p, err = c.Request("GET", "/api/mobile/cli/projects", nil) |
| 206 | if err != nil || p.Status != 423 { |
| 207 | t.Fatalf("account lock lost at bridge: %v", err) |
| 208 | } |
| 209 | assets := t.TempDir() |
| 210 | if err := os.WriteFile(filepath.Join(assets, "mobile.html"), []byte("mobile"), 0600); err != nil { |
| 211 | t.Fatal(err) |
| 212 | } |
| 213 | entry, err := c.StartUI(assets) |
| 214 | if err != nil { |
| 215 | t.Fatal(err) |
| 216 | } |
| 217 | u, err := url.Parse(entry) |
| 218 | if err != nil || u.Hostname() != "127.0.0.1" || u.Path != "/link-bootstrap" || u.Fragment == "" { |
| 219 | t.Fatal("invalid native UI entry") |
| 220 | } |
| 221 | browser := &http.Client{Transport: &http.Transport{Proxy: nil}, Timeout: 2 * time.Second} |
| 222 | defer browser.CloseIdleConnections() |
| 223 | res, err := browser.Get(u.Scheme + "://" + u.Host + u.Path) |
| 224 | if err != nil { |
| 225 | t.Fatal("cannot open native UI bootstrap") |
| 226 | } |
| 227 | res.Body.Close() |
| 228 | if res.StatusCode != 200 { |
| 229 | t.Fatal("native UI bootstrap unavailable") |
| 230 | } |
| 231 | if _, err := c.StartUI(assets); err == nil { |
| 232 | t.Fatal("native UI opened twice") |
| 233 | } |
| 234 | if err := c.Close(); err != nil { |
| 235 | t.Fatal(err) |
| 236 | } |
| 237 | if res, err := browser.Get(u.Scheme + "://" + u.Host + u.Path); err == nil { |
| 238 | res.Body.Close() |
| 239 | t.Fatal("discarded native UI remained reachable") |
| 240 | } |
| 241 | } |
| 242 | |
| 243 | |
| 244 | |
| 245 | func TestPairedPeerCannotBypassHostFilter(t *testing.T) { |
| 246 | f := newFixture(t) |
| 247 | key, err := remotelink.NewIdentity() |
| 248 | if err != nil { |
| 249 | t.Fatal(err) |
| 250 | } |
| 251 | room := f.startHost(t, key.Pin) |
| 252 | dial := websocket.Dialer{HandshakeTimeout: 2 * time.Second} |
| 253 | ws, _, err := dial.Dial("ws"+strings.TrimPrefix(f.base, "http")+"/v1/rooms/"+room.ID+"/client", http.Header{"Authorization": {"Bearer " + room.ClientToken}}) |
| 254 | if err != nil { |
| 255 | t.Fatal("test client did not reach relay") |
| 256 | } |
| 257 | conn, err := remotelink.Client(context.Background(), ws, key, f.identity.Pin) |
| 258 | if err != nil { |
| 259 | t.Fatal(err) |
| 260 | } |
| 261 | defer conn.NetConn().Close() |
| 262 | cc, err := (&http2.Transport{}).NewClientConn(conn) |
| 263 | if err != nil { |
| 264 | t.Fatal(err) |
| 265 | } |
| 266 | defer cc.Close() |
| 267 | for _, tc := range []struct { |
| 268 | method, path, host, body string |
| 269 | want int |
| 270 | }{ |
| 271 | {"POST", "/api/launch", "cage-mobile.invalid", "{}", 404}, |
| 272 | {"GET", "/api/mobile/cli/sessions/../projects", "cage-mobile.invalid", "", 404}, |
| 273 | {"GET", session + "?after=1&after=2", "cage-mobile.invalid", "", 404}, |
| 274 | {"GET", "/api/mobile/cli/projects", "other-host.invalid", "", 403}, |
| 275 | {"POST", session + "/messages", "cage-mobile.invalid", strings.Repeat("x", (72<<10)+1), 413}, |
| 276 | {"GET", "/api/mobile/cli/projects", "cage-mobile.invalid", "", 200}, |
| 277 | } { |
| 278 | req, err := http.NewRequest(tc.method, "https://"+tc.host+tc.path, strings.NewReader(tc.body)) |
| 279 | if err != nil { |
| 280 | t.Fatal(err) |
| 281 | } |
| 282 | req.Header.Set("Authorization", "Bearer forged") |
| 283 | req.Header.Set("Cookie", "other=forged") |
| 284 | req.Header.Set("Origin", "https://foreign.invalid") |
| 285 | req.Header.Set("Content-Type", "application/json") |
| 286 | res, err := cc.RoundTrip(req) |
| 287 | if err != nil { |
| 288 | t.Fatalf("unexpected mobile protocol failure: %v", err) |
| 289 | } |
| 290 | res.Body.Close() |
| 291 | if res.StatusCode != tc.want { |
| 292 | t.Fatalf("raw %s status=%d, want %d", tc.path, res.StatusCode, tc.want) |
| 293 | } |
| 294 | } |
| 295 | if calls := f.upstream.Load(); calls != 1 { |
| 296 | t.Fatalf("host accepted %d upstream requests, want 1", calls) |
| 297 | } |
| 298 | } |
| 299 | |
| 300 | func TestLocalBrowserSessionAndHostHeaders(t *testing.T) { |
| 301 | f := newFixture(t) |
| 302 | id, err := remotelink.NewIdentity() |
| 303 | if err != nil { |
| 304 | t.Fatal(err) |
| 305 | } |
| 306 | room := f.startHost(t, id.Pin) |
| 307 | client, err := mobilelink.ConnectClient(context.Background(), f.base, room.ID, room.ClientToken, id, f.identity.Pin) |
| 308 | if err != nil { |
| 309 | t.Fatal(err) |
| 310 | } |
| 311 | t.Cleanup(func() { _ = client.Close() }) |
| 312 | dir := t.TempDir() |
| 313 | if err := os.WriteFile(filepath.Join(dir, "mobile.html"), []byte("Cage mobile test"), 0600); err != nil { |
| 314 | t.Fatal(err) |
| 315 | } |
| 316 | web := httptest.NewUnstartedServer(nil) |
| 317 | origin := "http://" + web.Listener.Addr().String() |
| 318 | b, launch, err := mobilelink.NewBrowser(origin, dir, client) |
| 319 | if err != nil { |
| 320 | t.Fatal(err) |
| 321 | } |
| 322 | t.Cleanup(func() { b.Close() }) |
| 323 | web.Config.Handler = b |
| 324 | web.Start() |
| 325 | t.Cleanup(web.Close) |
| 326 | entry, _ := url.Parse(launch) |
| 327 | body, _ := json.Marshal(map[string]string{"token": entry.Fragment}) |
| 328 | call := func(method, path, ref string, cookie *http.Cookie, data []byte) *http.Response { |
| 329 | t.Helper() |
| 330 | req, _ := http.NewRequest(method, origin+path, bytes.NewReader(data)) |
| 331 | if ref != "" { |
| 332 | req.Header.Set("Origin", ref) |
| 333 | } |
| 334 | req.Header.Set("Content-Type", "application/json") |
| 335 | req.Header.Set("Authorization", "Bearer untrusted-browser-value") |
| 336 | if cookie != nil { |
| 337 | req.AddCookie(cookie) |
| 338 | req.AddCookie(&http.Cookie{Name: "cage_session_host", Value: "untrusted-browser-value"}) |
| 339 | } |
| 340 | res, e := web.Client().Do(req) |
| 341 | if e != nil { |
| 342 | t.Fatal(e) |
| 343 | } |
| 344 | t.Cleanup(func() { res.Body.Close() }) |
| 345 | return res |
| 346 | } |
| 347 | if res := call("GET", "/", "", nil, nil); res.StatusCode != 401 { |
| 348 | t.Fatal("unauthenticated browser obtained UI") |
| 349 | } |
| 350 | if res := call("GET", "/link-bootstrap?page=archived", "", nil, nil); res.StatusCode != 200 { |
| 351 | t.Fatal("native archive entry could not bootstrap") |
| 352 | } |
| 353 | if res := call("GET", "/link-bootstrap?page=other", "", nil, nil); res.StatusCode != 401 { |
| 354 | t.Fatal("unexpected native bootstrap query accepted") |
| 355 | } |
| 356 | if res := call("POST", "/link-session", "https://untrusted.invalid", nil, body); res.StatusCode != 403 { |
| 357 | t.Fatal("cross-origin browser obtained session") |
| 358 | } |
| 359 | res := call("POST", "/link-session", origin, nil, body) |
| 360 | cookies := res.Cookies() |
| 361 | if res.StatusCode != 204 || len(cookies) != 1 || !cookies[0].HttpOnly || cookies[0].SameSite != http.SameSiteStrictMode { |
| 362 | t.Fatal("browser bootstrap did not issue a protected local cookie") |
| 363 | } |
| 364 | if res := call("POST", "/link-session", origin, nil, body); res.StatusCode != 401 { |
| 365 | t.Fatal("bootstrap was usable twice") |
| 366 | } |
| 367 | for _, path := range []string{"/", "/?page=archived", "/api/mobile/cli/projects"} { |
| 368 | res = call("GET", path, "", cookies[0], nil) |
| 369 | if res.StatusCode != 200 || len(res.Cookies()) != 0 { |
| 370 | t.Fatalf("local browser route failed or leaked cookie: %s", path) |
| 371 | } |
| 372 | } |
| 373 | if res := call("POST", session+"/messages", "https://untrusted.invalid", cookies[0], []byte("{}")); res.StatusCode != 403 { |
| 374 | t.Fatal("foreign origin used authenticated bridge") |
| 375 | } |
| 376 | if res := call("POST", "/api/account/unlock", origin, cookies[0], []byte("{}")); res.StatusCode != 404 { |
| 377 | t.Fatal("non-mobile route exposed to browser") |
| 378 | } |
| 379 | } |
| 380 | |
| 381 | func TestSavedNativeClientUsesNewRoomsAndChecksHostIdentity(t *testing.T) { |
| 382 | f := newFixture(t) |
| 383 | key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| 384 | if err != nil { |
| 385 | t.Fatal(err) |
| 386 | } |
| 387 | d := device{key} |
| 388 | pin, err := nativeclient.Fingerprint(d) |
| 389 | if err != nil { |
| 390 | t.Fatal(err) |
| 391 | } |
| 392 | lookup := "AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" |
| 393 | wrong := "BBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBBA" |
| 394 | if _, err := mobilelink.CreateDiscoverableRoom(context.Background(), f.base, strings.Repeat("x", 64), lookup); err == nil || mobilelink.Retryable(err) { |
| 395 | t.Fatal("invalid admin credentials must stop the host service") |
| 396 | } |
| 397 | if _, err := mobilelink.LookupRoom(context.Background(), f.base, wrong); err == nil { |
| 398 | t.Fatal("unregistered lookup token accepted") |
| 399 | } |
| 400 | other, err := remotelink.NewIdentity() |
| 401 | if err != nil { |
| 402 | t.Fatal(err) |
| 403 | } |
| 404 | previous := "" |
| 405 | for _, expectedPin := range []string{other.Pin, f.identity.Pin, f.identity.Pin} { |
| 406 | ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) |
| 407 | inv, err := mobilelink.CreateDiscoverableRoom(ctx, f.base, strings.Repeat("t", 64), lookup) |
| 408 | |
| 409 | |
| 410 | |
| 411 | for previous != "" && err != nil && mobilelink.Retryable(err) && ctx.Err() == nil { |
| 412 | time.Sleep(10 * time.Millisecond) |
| 413 | inv, err = mobilelink.CreateDiscoverableRoom(ctx, f.base, strings.Repeat("t", 64), lookup) |
| 414 | } |
| 415 | if err != nil { |
| 416 | cancel() |
| 417 | t.Fatal(err) |
| 418 | } |
| 419 | if inv.ID == previous { |
| 420 | cancel() |
| 421 | t.Fatal("room reused after disconnect") |
| 422 | } |
| 423 | if _, err := mobilelink.CreateDiscoverableRoom(ctx, f.base, strings.Repeat("t", 64), lookup); err == nil || !mobilelink.Retryable(err) { |
| 424 | cancel() |
| 425 | t.Fatal("an occupied saved room must remain intact and back off") |
| 426 | } |
| 427 | previous = inv.ID |
| 428 | done := make(chan error, 1) |
| 429 | go func() { done <- mobilelink.ServeHost(ctx, f.base, inv.ID, inv.HostToken, f.identity, pin, f.backend) }() |
| 430 | for { |
| 431 | visible, err := mobilelink.LookupRoom(ctx, f.base, lookup) |
| 432 | if err == nil && visible.ID == inv.ID { |
| 433 | break |
| 434 | } |
| 435 | if ctx.Err() != nil { |
| 436 | cancel() |
| 437 | t.Fatal("registered host never became discoverable") |
| 438 | } |
| 439 | time.Sleep(10 * time.Millisecond) |
| 440 | } |
| 441 | if _, err := mobilelink.LookupRoom(ctx, f.base, wrong); err == nil { |
| 442 | cancel() |
| 443 | t.Fatal("incorrect lookup token revealed ready room") |
| 444 | } |
| 445 | c, err := nativeclient.OpenSaved(f.base, lookup, expectedPin, d) |
| 446 | if expectedPin != f.identity.Pin { |
| 447 | if err == nil { |
| 448 | c.Close() |
| 449 | cancel() |
| 450 | t.Fatal("saved client accepted the wrong host fingerprint") |
| 451 | } |
| 452 | } else { |
| 453 | if err != nil { |
| 454 | cancel() |
| 455 | t.Fatal(err) |
| 456 | } |
| 457 | resp, err := c.Request("GET", "/api/mobile/cli/projects", nil) |
| 458 | if err != nil || resp.Status != 200 { |
| 459 | c.Close() |
| 460 | cancel() |
| 461 | t.Fatal("saved native operation failed") |
| 462 | } |
| 463 | _ = c.Close() |
| 464 | } |
| 465 | select { |
| 466 | case <-done: |
| 467 | case <-ctx.Done(): |
| 468 | cancel() |
| 469 | t.Fatal("used room did not close") |
| 470 | } |
| 471 | cancel() |
| 472 | } |
| 473 | } |
| 474 | |
| 475 | |
| 476 | |
| 477 | func TestSavedClientRecoversReadAfterHostDisconnect(t *testing.T) { |
| 478 | f := newFixture(t) |
| 479 | key, err := ecdsa.GenerateKey(elliptic.P256(), rand.Reader) |
| 480 | if err != nil { |
| 481 | t.Fatal(err) |
| 482 | } |
| 483 | d := device{key} |
| 484 | pin, err := nativeclient.Fingerprint(d) |
| 485 | if err != nil { |
| 486 | t.Fatal(err) |
| 487 | } |
| 488 | lookup := strings.Repeat("A", 43) |
| 489 | start := func(reconnecting bool) func() { |
| 490 | t.Helper() |
| 491 | ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) |
| 492 | t.Cleanup(cancel) |
| 493 | room, err := mobilelink.CreateDiscoverableRoom(ctx, f.base, strings.Repeat("t", 64), lookup) |
| 494 | |
| 495 | |
| 496 | for reconnecting && err != nil && mobilelink.Retryable(err) && ctx.Err() == nil { |
| 497 | time.Sleep(10 * time.Millisecond) |
| 498 | room, err = mobilelink.CreateDiscoverableRoom(ctx, f.base, strings.Repeat("t", 64), lookup) |
| 499 | } |
| 500 | if err != nil { |
| 501 | t.Fatal(err) |
| 502 | } |
| 503 | done := make(chan struct{}) |
| 504 | go func() { |
| 505 | defer close(done) |
| 506 | _ = mobilelink.ServeHost(ctx, f.base, room.ID, room.HostToken, f.identity, pin, f.backend) |
| 507 | }() |
| 508 | return func() { cancel(); <-done } |
| 509 | } |
| 510 | drop := start(false) |
| 511 | c, err := nativeclient.OpenSaved(f.base, lookup, f.identity.Pin, d) |
| 512 | if err != nil { |
| 513 | t.Fatal(err) |
| 514 | } |
| 515 | defer c.Close() |
| 516 | if _, err := c.Request("GET", "/api/mobile/cli/projects", nil); err != nil { |
| 517 | t.Fatal(err) |
| 518 | } |
| 519 | drop() |
| 520 | stop := start(true) |
| 521 | defer stop() |
| 522 | |
| 523 | calls := f.upstream.Load() |
| 524 | if _, err := c.Request("POST", session+"/approval", []byte(`{"allow":true}`)); err == nil { |
| 525 | t.Fatal("a pending approval silently crossed into the replacement connection") |
| 526 | } |
| 527 | if f.upstream.Load() != calls { |
| 528 | t.Fatal("approval reached the host") |
| 529 | } |
| 530 | results := make(chan error, 2) |
| 531 | for range 2 { |
| 532 | go func() { |
| 533 | reply, err := c.Request("GET", "/api/mobile/cli/projects", nil) |
| 534 | if err == nil && reply.Status != http.StatusOK { |
| 535 | err = fmt.Errorf("unexpected status %d", reply.Status) |
| 536 | } |
| 537 | results <- err |
| 538 | }() |
| 539 | } |
| 540 | for range 2 { |
| 541 | if err := <-results; err != nil { |
| 542 | t.Fatal(err) |
| 543 | } |
| 544 | } |
| 545 | if got := f.upstream.Load() - calls; got != 2 { |
| 546 | t.Fatalf("expected only two recovered reads, got %d requests", got) |
| 547 | } |
| 548 | } |