fix(http): incorrect URL on relative redirect (#2116)
diff --git a/pkgs/http/CHANGELOG.md b/pkgs/http/CHANGELOG.md
index fae086f..525f3d3 100644
--- a/pkgs/http/CHANGELOG.md
+++ b/pkgs/http/CHANGELOG.md
@@ -37,6 +37,8 @@
   final response = await client.send(request);
   await response.stream.drain<void>();
   ```
+* Fix a bug in `IOClient` where `BaseResponseWithUrl.url` was a bare relative
+  `Uri` after a relative redirect.
 
 ## 1.6.0
 
diff --git a/pkgs/http/lib/src/io_client.dart b/pkgs/http/lib/src/io_client.dart
index 8337a7e..0de0f69 100644
--- a/pkgs/http/lib/src/io_client.dart
+++ b/pkgs/http/lib/src/io_client.dart
@@ -224,6 +224,17 @@
         headers[key] = values.map((value) => value.trimRight()).join(',');
       });
 
+      var url = request.url;
+      // Resolve each URI relative to the previous one. For example:
+      //
+      // http://www.example.com/foo redirects to /bar
+      // http://www.example.com/bar redirects to http://www.example2.com/baz
+      // http://www.example2.com/baz redirects to /foo
+      // http://www.example2.com/foo is the final URL
+      for (final redirect in response.redirects) {
+        url = url.resolveUri(redirect.location);
+      }
+
       abortHandler?.setHandler(abortResponse);
 
       return _IOStreamedResponseV2(
@@ -234,9 +245,7 @@
         request: request,
         headers: headers,
         isRedirect: response.isRedirect,
-        url: response.redirects.isNotEmpty
-            ? response.redirects.last.location
-            : request.url,
+        url: url,
         persistentConnection: response.persistentConnection,
         reasonPhrase: response.reasonPhrase,
         inner: response,
diff --git a/pkgs/http/test/html/client_conformance_test.dart b/pkgs/http/test/html/client_conformance_test.dart
index 51a8134..2dabfa7 100644
--- a/pkgs/http/test/html/client_conformance_test.dart
+++ b/pkgs/http/test/html/client_conformance_test.dart
@@ -15,7 +15,10 @@
     redirectAlwaysAllowed: true,
     canStreamRequestBody: false,
     canStreamResponseBody: true,
+    canSendProxyAuthorizationHeaders: false,
+    canSetUserInfo: false,
     canWorkInIsolates: false,
+    correctCrossHostRedirect: true,
     supportsMultipartRequest: false,
     supportsAbort: true,
   );
diff --git a/pkgs/http/test/io/client_conformance_test.dart b/pkgs/http/test/io/client_conformance_test.dart
index 8a307cb..05cbcc0 100644
--- a/pkgs/http/test/io/client_conformance_test.dart
+++ b/pkgs/http/test/io/client_conformance_test.dart
@@ -14,6 +14,7 @@
     IOClient.new, preservesMethodCase: false, // https://dartbug.com/54187
     canReceiveSetCookieHeaders: true,
     canSendCookieHeaders: true,
+    correctCrossHostRedirect: true,
     correctlyHandlesNullHeaderValues:
         false, // https://github.com/dart-lang/sdk/issues/56636
     supportsAbort: true,
diff --git a/pkgs/http_client_conformance_tests/lib/http_client_conformance_tests.dart b/pkgs/http_client_conformance_tests/lib/http_client_conformance_tests.dart
index 146a8a3..fe79fa2 100644
--- a/pkgs/http_client_conformance_tests/lib/http_client_conformance_tests.dart
+++ b/pkgs/http_client_conformance_tests/lib/http_client_conformance_tests.dart
@@ -66,8 +66,20 @@
 /// If [preservesMethodCase] is `false` then tests that assume that the
 /// [Client] preserves custom request method casing will be skipped.
 ///
-/// If [canSendCookieHeaders] is `false` then tests that require that "cookie"
-/// headers be sent by the client will not be run.
+/// If [canSendCookieHeaders] is `false` then tests will not set "cookie"
+/// headers in requests, and tests that only verify "cookie" headers will be
+/// skipped.
+///
+/// If [canSendProxyAuthorizationHeaders] is `false` then tests will not set
+/// "proxy-authorization" headers in requests.
+///
+/// If [canSetUserInfo] is `false` then tests that require that the request URL
+/// contain userinfo (e.g. `http://user:password@example.com/`) will not be
+/// run.
+///
+/// If [correctCrossHostRedirect] is `false` then tests that verify the behavior
+/// of relative redirects and of redirects across host/port boundaries will be
+/// skipped.
 ///
 /// If [canReceiveSetCookieHeaders] is `false` then tests that require that
 /// "set-cookie" headers be received by the client will not be run.
@@ -99,6 +111,9 @@
   bool supportsFoldedHeaders = true,
   bool correctlyHandlesNullHeaderValues = true,
   bool canSendCookieHeaders = false,
+  bool canSendProxyAuthorizationHeaders = true,
+  bool canSetUserInfo = true,
+  bool correctCrossHostRedirect = false,
   bool canReceiveSetCookieHeaders = false,
   bool supportsMultipartRequest = true,
   bool supportsAbort = false,
@@ -117,7 +132,12 @@
       supportsFoldedHeaders: supportsFoldedHeaders,
       correctlyHandlesNullHeaderValues: correctlyHandlesNullHeaderValues);
   testResponseStatusLine(clientFactory);
-  testRedirect(clientFactory, redirectAlwaysAllowed: redirectAlwaysAllowed);
+  testRedirect(clientFactory,
+      canSendCookieHeaders: canSendCookieHeaders,
+      canSendProxyAuthorizationHeaders: canSendProxyAuthorizationHeaders,
+      canSetUserInfo: canSetUserInfo,
+      correctCrossHostRedirect: correctCrossHostRedirect,
+      redirectAlwaysAllowed: redirectAlwaysAllowed);
   testServerErrors(clientFactory);
   testCompressedResponseBody(clientFactory);
   testMultipleClients(clientFactory);
diff --git a/pkgs/http_client_conformance_tests/lib/src/redirect_server.dart b/pkgs/http_client_conformance_tests/lib/src/redirect_server.dart
index 2813e32..a29eb23 100644
--- a/pkgs/http_client_conformance_tests/lib/src/redirect_server.dart
+++ b/pkgs/http_client_conformance_tests/lib/src/redirect_server.dart
@@ -3,43 +3,173 @@
 // BSD-style license that can be found in the LICENSE file.
 
 import 'dart:async';
+import 'dart:convert';
 import 'dart:io';
 
 import 'package:stream_channel/stream_channel.dart';
 
-/// Starts an HTTP server and sends the port back on the given channel.
+/// Starts two HTTP servers (`server1` and `server2`) and communicates over
+/// [channel].
 ///
-/// Quits when anything is received on the channel.
+/// Channel protocol:
+/// - On startup: sends `server1.port`, then `server2.port`.
+/// - On non-`OPTIONS` request: sends
+///   `['server1' | 'server2', method, body, headers]`.
+/// - On receiving any message: closes both servers and exits.
 ///
-///        URI |  Redirects TO
-/// ===========|==============
-/// ".../loop" |    ".../loop"
-///   ".../10" |       ".../9"
-///    ".../9" |       ".../8"
-///        ... |           ...
-///    ".../1" |           "/"
-///        "/" |  &lt;200 return&gt;
+/// `server1` routes:
+///
+/// | Request path       | Response                                         |
+/// | :----------------- | :----------------------------------------------- |
+/// | `/cross-port`      | `302` -> `http://localhost:<server2.port>/`      |
+/// | `/cross-host`      | `302` -> `http://127.0.0.1:<server1.port>/`      |
+/// | `/cross-host-301`  | `301` -> `http://127.0.0.1:<server2.port>/`      |
+/// | `/cross-host-302`  | `302` -> `http://127.0.0.1:<server2.port>/`      |
+/// | `/cross-host-303`  | `303` -> `http://127.0.0.1:<server2.port>/`      |
+/// | `/cross-host-307`  | `307` -> `http://127.0.0.1:<server2.port>/`      |
+/// | `/cross-host-308`  | `308` -> `http://127.0.0.1:<server2.port>/`      |
+/// | `/cross-ping`      | `302` -> `http://127.0.0.1:<server2.port>/pong`  |
+/// | `/cookie-ping`     | `/cross-ping` + `Set-Cookie`, to `/cookie-pong`  |
+/// | `/relative`        | `302` -> `/`                                     |
+/// | `/scheme-relative` | `302` -> `//127.0.0.1:<server1.port>/`           |
+/// | `/loop`            | `302` -> `http://localhost:<server1.port>/loop`  |
+/// | `/<n>` (n>1)       | `302` -> `http://localhost:<server1.port>/<n-1>` |
+/// | `/1`               | `302` -> `http://localhost:<server1.port>/`      |
+/// | `/`                | `200 OK`                                         |
+///
+/// `server2` routes:
+///
+/// | Request path       | Response                                         |
+/// | :----------------- | :----------------------------------------------- |
+/// | `/pong`            | `302` -> `http://localhost:<server1.port>/`      |
+/// | `/cookie-pong`     | `/pong` + `Set-Cookie`                           |
+/// | `/`                | `200 OK`                                         |
+///
+/// `/cookie-ping` sets the cookie `localhost-cookie=secret` and `/cookie-pong`
+/// sets the cookie `loopback-cookie=secret`.
 void hybridMain(StreamChannel<Object?> channel) async {
-  late HttpServer server;
+  late HttpServer server1;
+  late HttpServer server2;
 
-  server = await HttpServer.bind('localhost', 0)
+  server1 = await HttpServer.bind(InternetAddress.loopbackIPv4, 0)
     ..listen((request) async {
       request.response.headers.set('Access-Control-Allow-Origin', '*');
+      if (request.method == 'OPTIONS') {
+        // Handle a CORS preflight request:
+        // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#preflighted_requests
+        request.response.headers
+          ..set('Access-Control-Allow-Methods', 'GET, POST')
+          ..set('Access-Control-Allow-Headers', '*, Authorization');
+        unawaited(request.response.close());
+        return;
+      }
+
+      final body = await utf8.decodeStream(request);
+      final headers = <String, List<String>>{};
+      request.headers.forEach((field, value) {
+        headers[field] = value;
+      });
+      channel.sink.add(['server1', request.method, body, headers]);
+
       if (request.requestedUri.pathSegments.isEmpty) {
         unawaited(request.response.close());
-      } else if (request.requestedUri.pathSegments.last == 'loop') {
-        unawaited(request.response
-            .redirect(Uri.http('localhost:${server.port}', '/loop')));
       } else {
-        final n = int.parse(request.requestedUri.pathSegments.last);
-        final nextPath = n - 1 == 0 ? '' : '${n - 1}';
-        unawaited(request.response
-            .redirect(Uri.http('localhost:${server.port}', '/$nextPath')));
+        switch (request.requestedUri.pathSegments.last) {
+          case 'cross-port':
+            unawaited(request.response
+                .redirect(Uri.http('localhost:${server2.port}', '/')));
+          case 'cross-host':
+            unawaited(request.response
+                .redirect(Uri.http('127.0.0.1:${server1.port}', '/')));
+          case 'cross-host-301':
+            unawaited(request.response.redirect(
+                Uri.http('127.0.0.1:${server2.port}', '/'),
+                status: HttpStatus.movedPermanently));
+          case 'cross-host-302':
+            unawaited(request.response.redirect(
+                Uri.http('127.0.0.1:${server2.port}', '/'),
+                status: HttpStatus.found));
+          case 'cross-host-303':
+            unawaited(request.response.redirect(
+                Uri.http('127.0.0.1:${server2.port}', '/'),
+                status: HttpStatus.seeOther));
+          case 'cross-host-307':
+            unawaited(request.response.redirect(
+                Uri.http('127.0.0.1:${server2.port}', '/'),
+                status: HttpStatus.temporaryRedirect));
+          case 'cross-host-308':
+            unawaited(request.response.redirect(
+                Uri.http('127.0.0.1:${server2.port}', '/'),
+                status: HttpStatus.permanentRedirect));
+          case 'cross-ping':
+            unawaited(request.response
+                .redirect(Uri.http('127.0.0.1:${server2.port}', '/pong')));
+          case 'cookie-ping':
+            request.response.headers
+                .add('set-cookie', 'localhost-cookie=secret');
+            unawaited(request.response.redirect(
+                Uri.http('127.0.0.1:${server2.port}', '/cookie-pong')));
+          case 'relative':
+            request.response
+              ..statusCode = HttpStatus.found
+              ..headers.set('location', '/');
+            unawaited(request.response.close());
+          case 'scheme-relative':
+            request.response
+              ..statusCode = HttpStatus.found
+              ..headers.set('location', '//127.0.0.1:${server1.port}/');
+            unawaited(request.response.close());
+          case 'loop':
+            unawaited(request.response
+                .redirect(Uri.http('localhost:${server1.port}', '/loop')));
+          case final segment:
+            final n = int.parse(segment);
+            final nextPath = n - 1 == 0 ? '' : '${n - 1}';
+            unawaited(request.response
+                .redirect(Uri.http('localhost:${server1.port}', '/$nextPath')));
+        }
       }
     });
 
-  channel.sink.add(server.port);
+  server2 = await HttpServer.bind(InternetAddress.loopbackIPv4, 0)
+    ..listen((request) async {
+      request.response.headers.set('Access-Control-Allow-Origin', '*');
+      if (request.method == 'OPTIONS') {
+        // Handle a CORS preflight request:
+        // https://developer.mozilla.org/en-US/docs/Web/HTTP/CORS#preflighted_requests
+        request.response.headers
+          ..set('Access-Control-Allow-Methods', 'GET, POST')
+          ..set('Access-Control-Allow-Headers', '*, Authorization');
+        unawaited(request.response.close());
+        return;
+      }
+
+      final body = await utf8.decodeStream(request);
+      final headers = <String, List<String>>{};
+      request.headers.forEach((field, value) {
+        headers[field] = value;
+      });
+      channel.sink.add(['server2', request.method, body, headers]);
+
+      if (request.requestedUri.pathSegments.isEmpty) {
+        unawaited(request.response.close());
+      } else if (request.requestedUri.pathSegments.last == 'pong') {
+        unawaited(request.response
+            .redirect(Uri.http('localhost:${server1.port}', '/')));
+      } else if (request.requestedUri.pathSegments.last == 'cookie-pong') {
+        request.response.headers.add('set-cookie', 'loopback-cookie=secret');
+        unawaited(request.response
+            .redirect(Uri.http('localhost:${server1.port}', '/')));
+      } else {
+        request.response.statusCode = HttpStatus.notFound;
+        unawaited(request.response.close());
+      }
+    });
+
+  channel.sink.add(server1.port);
+  channel.sink.add(server2.port);
   await channel
       .stream.first; // Any writes indicates that the server should exit.
-  unawaited(server.close());
+  unawaited(server1.close());
+  unawaited(server2.close());
 }
diff --git a/pkgs/http_client_conformance_tests/lib/src/redirect_tests.dart b/pkgs/http_client_conformance_tests/lib/src/redirect_tests.dart
index 494c773..25e5791 100644
--- a/pkgs/http_client_conformance_tests/lib/src/redirect_tests.dart
+++ b/pkgs/http_client_conformance_tests/lib/src/redirect_tests.dart
@@ -12,51 +12,79 @@
 
 /// Tests that the [Client] correctly implements HTTP redirect logic.
 ///
+/// If [canSendCookieHeaders] is `false` then tests will not set "cookie"
+/// headers in requests.
+///
+/// If [canSendProxyAuthorizationHeaders] is `false` then tests will not set
+/// "proxy-authorization" headers in requests.
+///
+/// If [canSetUserInfo] is `false` then tests that require that the request URL
+/// contain userinfo (e.g. `http://user:password@example.com/`) will not be
+/// run.
+///
+/// If [correctCrossHostRedirect] is `false` then tests that verify the behavior
+/// of relative redirects and of redirects across host/port boundaries will be
+/// skipped.
+///
 /// If [redirectAlwaysAllowed] is `true` then tests that require the [Client]
 /// to limit redirects will be skipped.
 void testRedirect(Client Function() clientFactory,
-    {bool redirectAlwaysAllowed = false}) {
+    {bool canSendCookieHeaders = false,
+    bool canSendProxyAuthorizationHeaders = true,
+    bool canSetUserInfo = true,
+    bool correctCrossHostRedirect = false,
+    bool redirectAlwaysAllowed = false}) {
   group('redirects', () {
     late Client client;
-    late final String host;
-    late final StreamChannel<Object?> httpServerChannel;
-    late final StreamQueue<Object?> httpServerQueue;
+    late String localhost1;
+    late String localhost2;
+    late String loopback1;
+    late String loopback2;
+    late StreamChannel<Object?> httpServerChannel;
+    late StreamQueue<Object?> httpServerQueue;
 
-    setUpAll(() async {
+    setUp(() async {
       httpServerChannel = await startServer();
       httpServerQueue = StreamQueue(httpServerChannel.stream);
-      host = 'localhost:${await httpServerQueue.nextAsInt}';
+      final port1 = await httpServerQueue.nextAsInt;
+      final port2 = await httpServerQueue.nextAsInt;
+      localhost1 = 'localhost:$port1';
+      localhost2 = 'localhost:$port2';
+      loopback1 = '127.0.0.1:$port1';
+      loopback2 = '127.0.0.1:$port2';
+      client = clientFactory();
     });
-    setUp(() => client = clientFactory());
-    tearDown(() => client.close());
-    tearDownAll(() => httpServerChannel.sink.add(null));
+    tearDown(() {
+      client.close();
+      httpServerChannel.sink.add(null);
+    });
 
     test('no redirect', () async {
-      final request = Request('GET', Uri.http(host, '/'))
+      final request = Request('GET', Uri.http(localhost1, '/'))
         ..followRedirects = false;
       final response = await client.send(request);
       await response.stream.drain<void>();
       expect(response.statusCode, 200);
       expect(response.isRedirect, false);
       if (response case BaseResponseWithUrl(url: final url)) {
-        expect(url, Uri.http(host, '/'));
+        expect(url, Uri.http(localhost1, '/'));
       }
     });
 
     test('disallow redirect', () async {
-      final request = Request('GET', Uri.http(host, '/1'))
+      final request = Request('GET', Uri.http(localhost1, '/1'))
         ..followRedirects = false;
       final response = await client.send(request);
       await response.stream.drain<void>();
       expect(response.statusCode, 302);
       expect(response.isRedirect, true);
       if (response case BaseResponseWithUrl(url: final url)) {
-        expect(url, Uri.http(host, '/1'));
+        expect(url, Uri.http(localhost1, '/1'));
       }
     }, skip: redirectAlwaysAllowed ? 'redirects always allowed' : false);
 
     test('disallow redirect, 0 maxRedirects', () async {
-      final request = Request('GET', Uri.http(host, '/1'))
+      final request = Request('GET', Uri.http(localhost1, '/1'))
         ..followRedirects = false
         ..maxRedirects = 0;
       final response = await client.send(request);
@@ -64,24 +92,87 @@
       expect(response.statusCode, 302);
       expect(response.isRedirect, true);
       if (response case BaseResponseWithUrl(url: final url)) {
-        expect(url, Uri.http(host, '/1'));
+        expect(url, Uri.http(localhost1, '/1'));
       }
     }, skip: redirectAlwaysAllowed ? 'redirects always allowed' : false);
 
     test('allow redirect', () async {
-      final request = Request('GET', Uri.http(host, '/1'))
+      final request = Request('GET', Uri.http(localhost1, '/1'))
         ..followRedirects = true;
+      request.headers['hello'] = 'world';
+      if (canSendCookieHeaders) {
+        request.headers['cookie'] = 'foo=bar';
+      }
       final response = await client.send(request);
       await response.stream.drain<void>();
       expect(response.statusCode, 200);
       expect(response.isRedirect, false);
       if (response case BaseResponseWithUrl(url: final url)) {
-        expect(url, Uri.http(host, '/'));
+        expect(url, Uri.http(localhost1, '/'));
+      }
+      final [server1, method1, body1, headers1] =
+          await httpServerQueue.next as List<Object?>;
+      expect(server1, 'server1');
+      expect(method1, 'GET');
+      expect(body1, isEmpty);
+      expect(headers1, containsPair('host', [localhost1]));
+      expect(headers1, containsPair('hello', ['world']));
+      if (canSendCookieHeaders) {
+        expect(headers1, containsPair('cookie', ['foo=bar']));
+      }
+      final [server2, method2, body2, headers2] =
+          await httpServerQueue.next as List<Object?>;
+      expect(server2, 'server1');
+      expect(method2, 'GET');
+      expect(body2, isEmpty);
+      expect(headers2, containsPair('host', [localhost1]));
+      expect(headers2, containsPair('hello', ['world']));
+      if (canSendCookieHeaders) {
+        expect(headers2, containsPair('cookie', ['foo=bar']));
       }
     });
 
+    test('relative redirect', () async {
+      final request = Request('GET', Uri.http(localhost1, '/relative'))
+        ..followRedirects = true;
+      request.headers['hello'] = 'world';
+      if (canSendCookieHeaders) {
+        request.headers['cookie'] = 'foo=bar';
+      }
+      final response = await client.send(request);
+      await response.stream.drain<void>();
+      expect(response.statusCode, 200);
+      expect(response.isRedirect, false);
+      if (response case BaseResponseWithUrl(url: final url)) {
+        expect(url, Uri.http(localhost1, '/'));
+      }
+      final [server1, method1, body1, headers1] =
+          await httpServerQueue.next as List<Object?>;
+      expect(server1, 'server1');
+      expect(method1, 'GET');
+      expect(body1, isEmpty);
+      expect(headers1, containsPair('host', [localhost1]));
+      expect(headers1, containsPair('hello', ['world']));
+      if (canSendCookieHeaders) {
+        expect(headers1, containsPair('cookie', ['foo=bar']));
+      }
+      final [server2, method2, body2, headers2] =
+          await httpServerQueue.next as List<Object?>;
+      expect(server2, 'server1');
+      expect(method2, 'GET');
+      expect(body2, isEmpty);
+      expect(headers2, containsPair('host', [localhost1]));
+      expect(headers2, containsPair('hello', ['world']));
+      if (canSendCookieHeaders) {
+        expect(headers2, containsPair('cookie', ['foo=bar']));
+      }
+    },
+        skip: correctCrossHostRedirect
+            ? false
+            : 'not opted into relative redirect tests');
+
     test('allow redirect, 0 maxRedirects', () async {
-      final request = Request('GET', Uri.http(host, '/1'))
+      final request = Request('GET', Uri.http(localhost1, '/1'))
         ..followRedirects = true
         ..maxRedirects = 0;
       expect(
@@ -91,7 +182,7 @@
     }, skip: redirectAlwaysAllowed ? 'redirects always allowed' : false);
 
     test('exactly the right number of allowed redirects', () async {
-      final request = Request('GET', Uri.http(host, '/5'))
+      final request = Request('GET', Uri.http(localhost1, '/5'))
         ..followRedirects = true
         ..maxRedirects = 5;
       final response = await client.send(request);
@@ -99,12 +190,12 @@
       expect(response.statusCode, 200);
       expect(response.isRedirect, false);
       if (response case BaseResponseWithUrl(url: final url)) {
-        expect(url, Uri.http(host, '/'));
+        expect(url, Uri.http(localhost1, '/'));
       }
     }, skip: redirectAlwaysAllowed ? 'redirects always allowed' : false);
 
     test('too many redirects', () async {
-      final request = Request('GET', Uri.http(host, '/6'))
+      final request = Request('GET', Uri.http(localhost1, '/6'))
         ..followRedirects = true
         ..maxRedirects = 5;
       expect(
@@ -116,11 +207,529 @@
     test(
       'loop',
       () async {
-        final request = Request('GET', Uri.http(host, '/loop'))
+        final request = Request('GET', Uri.http(localhost1, '/loop'))
           ..followRedirects = true
           ..maxRedirects = 5;
         expect(client.send(request), throwsA(isA<ClientException>()));
       },
     );
+
+    group('cross origin', () {
+      // RFC 9110, 15.4 says:
+      // Consider removing header fields that were not automatically generated
+      // by the implementation...where there are security implications; this
+      // includes but is not limited to Authorization and Cookie.
+      //
+      // RFC 6265, 8.5 says:
+      // Cookies do not provide isolation by port. If a cookie is readable by a
+      // service running on one port, the cookie is also readable by a service
+      // running on another port of the same server.
+      //
+      // So the behavior that we test is:
+      // - if a redirect changes hosts (e.g., localhost -> 127.0.0.1) then it
+      //   MUST drop headers with security implications.
+      // - if a redirect changes ports then it MUST drop headers with security
+      //   implications, except for cookies which MAY be dropped
+      // - headers with no security implications MUST NOT be dropped during
+      //   redirect
+
+      for (final (authorization, cookie, proxyAuthorization) in [
+        ('authorization', 'cookie', 'proxy-authorization'),
+        ('Authorization', 'Cookie', 'Proxy-Authorization'),
+        ('AUTHORIZATION', 'COOKIE', 'PROXY-AUTHORIZATION'),
+      ]) {
+        test(
+            'cross port redirect '
+            '($authorization, $cookie, $proxyAuthorization)', () async {
+          final request = Request('GET', Uri.http(localhost1, '/cross-port'))
+            ..followRedirects = true
+            ..maxRedirects = 1;
+          request.headers['hello'] = 'world';
+          request.headers[authorization] = 'anything';
+          if (canSendCookieHeaders) {
+            request.headers[cookie] = 'foo=bar';
+          }
+          if (canSendProxyAuthorizationHeaders) {
+            request.headers[proxyAuthorization] = 'anything';
+          }
+
+          final response = await client.send(request);
+          await response.stream.drain<void>();
+          expect(response.statusCode, 200);
+          expect(response.isRedirect, false);
+          if (response case BaseResponseWithUrl(url: final url)) {
+            expect(url, Uri.http(localhost2, '/'));
+          }
+
+          final [server1, _, _, headers1] =
+              await httpServerQueue.next as List<Object?>;
+          expect(server1, 'server1');
+          expect(headers1, containsPair('host', [localhost1]));
+          expect(headers1, containsPair('hello', ['world']));
+          expect(headers1, containsPair('authorization', ['anything']));
+          if (canSendCookieHeaders) {
+            expect(headers1, containsPair('cookie', ['foo=bar']));
+          }
+          if (canSendProxyAuthorizationHeaders) {
+            expect(headers1, containsPair('proxy-authorization', ['anything']));
+          }
+
+          final [server2, _, _, headers2] =
+              await httpServerQueue.next as List<Object?>;
+          expect(server2, 'server2');
+          expect(headers2, containsPair('host', [localhost2]));
+          expect(headers2, containsPair('hello', ['world']));
+          // Cookies may or may not be preserved.
+          expect(headers2, isNot(contains('authorization')));
+          expect(
+              skip: 'enable this test when `package:http` requires Dart >=3.13',
+              headers2,
+              isNot(contains('proxy-authorization')));
+        });
+
+        test(
+            'cross host redirect '
+            '($authorization, $cookie, $proxyAuthorization)', () async {
+          final request = Request('GET', Uri.http(localhost1, '/cross-host'))
+            ..followRedirects = true
+            ..maxRedirects = 1;
+          request.headers['hello'] = 'world';
+          request.headers[authorization] = 'anything';
+          if (canSendCookieHeaders) {
+            request.headers[cookie] = 'foo=bar';
+          }
+          if (canSendProxyAuthorizationHeaders) {
+            request.headers[proxyAuthorization] = 'anything';
+          }
+          final response = await client.send(request);
+          await response.stream.drain<void>();
+          expect(response.statusCode, 200);
+          expect(response.isRedirect, false);
+          if (response case BaseResponseWithUrl(url: final url)) {
+            expect(url, Uri.http(loopback1, '/'));
+          }
+
+          final [server1, _, _, headers1] =
+              await httpServerQueue.next as List<Object?>;
+          expect(server1, 'server1');
+          expect(headers1, containsPair('host', [localhost1]));
+          expect(headers1, containsPair('hello', ['world']));
+          expect(headers1, containsPair('authorization', ['anything']));
+          if (canSendCookieHeaders) {
+            expect(headers1, containsPair('cookie', ['foo=bar']));
+          }
+          if (canSendProxyAuthorizationHeaders) {
+            expect(headers1, containsPair('proxy-authorization', ['anything']));
+          }
+
+          final [server2, _, _, headers2] =
+              await httpServerQueue.next as List<Object?>;
+          expect(server2, 'server1');
+          expect(headers2, containsPair('host', [loopback1]));
+          expect(headers2, containsPair('hello', ['world']));
+          expect(headers2, isNot(contains('authorization')));
+          expect(headers2, isNot(contains('cookie')));
+          // TODO: enable this test when `package:http` requires Dart >=3.13
+          // expect(headers2, isNot(contains('proxy-authorization')));
+        });
+
+        test(
+            'cross host and back '
+            '($authorization, $cookie, $proxyAuthorization)', () async {
+          final request = Request('GET', Uri.http(localhost1, '/cross-ping'))
+            ..followRedirects = true
+            ..maxRedirects = 2;
+          request.headers['hello'] = 'world';
+          request.headers[authorization] = 'anything';
+          if (canSendCookieHeaders) {
+            request.headers[cookie] = 'foo=bar';
+          }
+          if (canSendProxyAuthorizationHeaders) {
+            request.headers[proxyAuthorization] = 'anything';
+          }
+          final response = await client.send(request);
+          await response.stream.drain<void>();
+          expect(response.statusCode, 200);
+          expect(response.isRedirect, false);
+          if (response case BaseResponseWithUrl(url: final url)) {
+            expect(url, Uri.http(localhost1, '/'));
+          }
+
+          final [server1, _, _, headers1] =
+              await httpServerQueue.next as List<Object?>;
+          expect(server1, 'server1');
+          expect(headers1, containsPair('host', [localhost1]));
+          expect(headers1, containsPair('hello', ['world']));
+          expect(headers1, containsPair('authorization', ['anything']));
+          if (canSendCookieHeaders) {
+            expect(headers1, containsPair('cookie', ['foo=bar']));
+          }
+          if (canSendProxyAuthorizationHeaders) {
+            expect(headers1, containsPair('proxy-authorization', ['anything']));
+          }
+
+          final [server2, _, _, headers2] =
+              await httpServerQueue.next as List<Object?>;
+          expect(server2, 'server2');
+          expect(headers2, containsPair('host', [loopback2]));
+          expect(headers2, containsPair('hello', ['world']));
+          expect(headers2, isNot(contains('authorization')));
+          expect(headers2, isNot(contains('cookie')));
+          // TODO: enable this test when `package:http` requires Dart >=3.13
+          // expect(headers2, isNot(contains('proxy-authorization')));
+
+          final [server3, _, _, headers3] =
+              await httpServerQueue.next as List<Object?>;
+          expect(server3, 'server1');
+          expect(headers3, containsPair('host', [localhost1]));
+          expect(headers3, containsPair('hello', ['world']));
+          expect(headers3, isNot(contains('authorization')));
+          expect(headers3, isNot(contains('cookie')));
+          // TODO: enable this test when `package:http` requires Dart >=3.13
+          // expect(headers3, isNot(contains('proxy-authorization')));
+        });
+      }
+
+      test('cross host and back with set-cookie', () async {
+        // Each redirect response sets a cookie. A cookie set by one host must
+        // not be sent to the other host.
+        final request = Request('GET', Uri.http(localhost1, '/cookie-ping'))
+          ..followRedirects = true
+          ..maxRedirects = 2;
+        final response = await client.send(request);
+        await response.stream.drain<void>();
+        expect(response.statusCode, 200);
+        expect(response.isRedirect, false);
+        if (response case BaseResponseWithUrl(url: final url)) {
+          expect(url, Uri.http(localhost1, '/'));
+        }
+
+        final [server1, _, _, headers1] =
+            await httpServerQueue.next as List<Object?>;
+        expect(server1, 'server1');
+        expect(headers1, containsPair('host', [localhost1]));
+
+        final [server2, _, _, headers2] =
+            await httpServerQueue.next as List<Object?>;
+        expect(server2, 'server2');
+        expect(headers2, containsPair('host', [loopback2]));
+        expect(
+            headers2,
+            isNot(containsPair(
+                'cookie', contains(contains('localhost-cookie')))));
+
+        // "localhost-cookie" may or may not be sent, depending on whether the
+        // client stores cookies.
+        final [server3, _, _, headers3] =
+            await httpServerQueue.next as List<Object?>;
+        expect(server3, 'server1');
+        expect(headers3, containsPair('host', [localhost1]));
+        expect(
+            headers3,
+            isNot(
+                containsPair('cookie', contains(contains('loopback-cookie')))));
+      });
+
+      test('cross host redirect with userinfo', () async {
+        // The client may use the userinfo in the URL to generate an
+        // "authorization" header. If it does, that header must not be sent to
+        // another host.
+        final request = Request(
+            'GET', Uri.parse('http://user:password@$localhost1/cross-host'))
+          ..followRedirects = true
+          ..maxRedirects = 1;
+        final response = await client.send(request);
+        await response.stream.drain<void>();
+        expect(response.statusCode, 200);
+        expect(response.isRedirect, false);
+        if (response case BaseResponseWithUrl(url: final url)) {
+          expect(url, Uri.http(loopback1, '/'));
+        }
+
+        final [server1, _, _, headers1] =
+            await httpServerQueue.next as List<Object?>;
+        expect(server1, 'server1');
+        expect(headers1, containsPair('host', [localhost1]));
+
+        final [server2, _, _, headers2] =
+            await httpServerQueue.next as List<Object?>;
+        expect(server2, 'server1');
+        expect(headers2, containsPair('host', [loopback1]));
+        expect(headers2, isNot(contains('authorization')));
+      }, skip: canSetUserInfo ? null : 'cannot set userinfo');
+
+      test('scheme-relative cross host redirect', () async {
+        final request = Request('GET', Uri.http(localhost1, '/scheme-relative'))
+          ..followRedirects = true
+          ..maxRedirects = 1;
+        request.headers['hello'] = 'world';
+        request.headers['authorization'] = 'anything';
+        if (canSendCookieHeaders) {
+          request.headers['cookie'] = 'foo=bar';
+        }
+        if (canSendProxyAuthorizationHeaders) {
+          request.headers['proxy-authorization'] = 'anything';
+        }
+        final response = await client.send(request);
+        await response.stream.drain<void>();
+        expect(response.statusCode, 200);
+        expect(response.isRedirect, false);
+        if (response case BaseResponseWithUrl(url: final url)) {
+          expect(url, Uri.http(loopback1, '/'));
+        }
+
+        final [server1, _, _, headers1] =
+            await httpServerQueue.next as List<Object?>;
+        expect(server1, 'server1');
+        expect(headers1, containsPair('host', [localhost1]));
+        expect(headers1, containsPair('hello', ['world']));
+        expect(headers1, containsPair('authorization', ['anything']));
+        if (canSendCookieHeaders) {
+          expect(headers1, containsPair('cookie', ['foo=bar']));
+        }
+        if (canSendProxyAuthorizationHeaders) {
+          expect(headers1, containsPair('proxy-authorization', ['anything']));
+        }
+
+        final [server2, _, _, headers2] =
+            await httpServerQueue.next as List<Object?>;
+        expect(server2, 'server1');
+        expect(headers2, containsPair('host', [loopback1]));
+        expect(headers2, containsPair('hello', ['world']));
+        expect(headers2, isNot(contains('authorization')));
+        expect(headers2, isNot(contains('cookie')));
+        // TODO: enable this test when `package:http` requires Dart >=3.13
+        // expect(headers2, isNot(contains('proxy-authorization')));
+      });
+
+      for (final code in [301, 302]) {
+        test('POST $code cross host redirect', () async {
+          final request =
+              Request('POST', Uri.http(localhost1, '/cross-host-$code'))
+                ..body = 'Hello World!'
+                ..followRedirects = true
+                ..maxRedirects = 1;
+          request.headers['hello'] = 'world';
+          request.headers['authorization'] = 'anything';
+          if (canSendCookieHeaders) {
+            request.headers['cookie'] = 'foo=bar';
+          }
+          if (canSendProxyAuthorizationHeaders) {
+            request.headers['proxy-authorization'] = 'anything';
+          }
+
+          final response = await client.send(request);
+          await response.stream.drain<void>();
+
+          final [server1, method1, body1, headers1] =
+              await httpServerQueue.next as List<Object?>;
+          expect(server1, 'server1');
+          expect(method1, 'POST');
+          expect(body1, 'Hello World!');
+          expect(headers1, containsPair('host', [localhost1]));
+          expect(headers1, containsPair('hello', ['world']));
+          expect(headers1, containsPair('authorization', ['anything']));
+          if (canSendCookieHeaders) {
+            expect(headers1, containsPair('cookie', ['foo=bar']));
+          }
+          if (canSendProxyAuthorizationHeaders) {
+            expect(headers1, containsPair('proxy-authorization', ['anything']));
+          }
+
+          // RFC 9110, 15.4.2-15.4.3:
+          // The server SHOULD generate a Location header field in the
+          // response containing a preferred URI reference for the new
+          // permanent URI. The user agent MAY use the Location field value
+          // for automatic redirection.
+          // Note: For historical reasons, a user agent MAY change the request
+          // method from POST to GET for the subsequent request.
+          expect(response.statusCode, anyOf(200, code));
+
+          if (response.statusCode == 200) {
+            expect(response.isRedirect, false);
+            if (response case BaseResponseWithUrl(url: final url)) {
+              expect(url, Uri.http(loopback2, '/'));
+            }
+
+            final [server2, method2, body2, headers2] =
+                await httpServerQueue.next as List<Object?>;
+            expect(server2, 'server2');
+            expect(method2, 'GET');
+            expect(body2, isEmpty);
+            expect(headers2, containsPair('host', [loopback2]));
+            expect(headers2, containsPair('hello', ['world']));
+            expect(headers2, isNot(contains('authorization')));
+            expect(headers2, isNot(contains('cookie')));
+            // TODO: enable this test when `package:http` requires Dart >=3.13
+            // expect(headers2, isNot(contains('proxy-authorization')));
+          }
+        });
+      }
+
+      test('POST 303 cross host redirect', () async {
+        final request = Request('POST', Uri.http(localhost1, '/cross-host-303'))
+          ..body = 'Hello World!'
+          ..followRedirects = true
+          ..maxRedirects = 1;
+        request.headers['hello'] = 'world';
+        request.headers['authorization'] = 'anything';
+        if (canSendCookieHeaders) {
+          request.headers['cookie'] = 'foo=bar';
+        }
+        if (canSendProxyAuthorizationHeaders) {
+          request.headers['proxy-authorization'] = 'anything';
+        }
+
+        final response = await client.send(request);
+        await response.stream.drain<void>();
+        // RFC 9110, 15.4.4: 303 redirects POST to GET.
+        expect(response.statusCode, 200);
+        expect(response.isRedirect, false);
+        if (response case BaseResponseWithUrl(url: final url)) {
+          expect(url, Uri.http(loopback2, '/'));
+        }
+
+        final [server1, method1, body1, headers1] =
+            await httpServerQueue.next as List<Object?>;
+        expect(server1, 'server1');
+        expect(method1, 'POST');
+        expect(body1, 'Hello World!');
+        expect(headers1, containsPair('host', [localhost1]));
+        expect(headers1, containsPair('hello', ['world']));
+        expect(headers1, containsPair('authorization', ['anything']));
+        if (canSendCookieHeaders) {
+          expect(headers1, containsPair('cookie', ['foo=bar']));
+        }
+        if (canSendProxyAuthorizationHeaders) {
+          expect(headers1, containsPair('proxy-authorization', ['anything']));
+        }
+
+        final [server2, method2, body2, headers2] =
+            await httpServerQueue.next as List<Object?>;
+        expect(server2, 'server2');
+        expect(method2, 'GET');
+        expect(body2, isEmpty);
+        expect(headers2, containsPair('host', [loopback2]));
+        expect(headers2, containsPair('hello', ['world']));
+        expect(headers2, isNot(contains('authorization')));
+        expect(headers2, isNot(contains('cookie')));
+        // TODO: enable this test when `package:http` requires Dart >=3.13
+        // expect(headers2, isNot(contains('proxy-authorization')));
+      });
+
+      for (final code in [307, 308]) {
+        test('GET $code cross host redirect', () async {
+          final request =
+              Request('GET', Uri.http(localhost1, '/cross-host-$code'))
+                ..followRedirects = true
+                ..maxRedirects = 1;
+          request.headers['hello'] = 'world';
+          request.headers['authorization'] = 'anything';
+          if (canSendCookieHeaders) {
+            request.headers['cookie'] = 'foo=bar';
+          }
+          if (canSendProxyAuthorizationHeaders) {
+            request.headers['proxy-authorization'] = 'anything';
+          }
+
+          final response = await client.send(request);
+          await response.stream.drain<void>();
+          expect(response.statusCode, 200);
+          expect(response.isRedirect, false);
+          if (response case BaseResponseWithUrl(url: final url)) {
+            expect(url, Uri.http(loopback2, '/'));
+          }
+
+          final [server1, method1, body1, headers1] =
+              await httpServerQueue.next as List<Object?>;
+          expect(server1, 'server1');
+          expect(method1, 'GET');
+          expect(body1, isEmpty);
+          expect(headers1, containsPair('host', [localhost1]));
+          expect(headers1, containsPair('hello', ['world']));
+          expect(headers1, containsPair('authorization', ['anything']));
+          if (canSendCookieHeaders) {
+            expect(headers1, containsPair('cookie', ['foo=bar']));
+          }
+          if (canSendProxyAuthorizationHeaders) {
+            expect(headers1, containsPair('proxy-authorization', ['anything']));
+          }
+
+          final [server2, method2, body2, headers2] =
+              await httpServerQueue.next as List<Object?>;
+          expect(server2, 'server2');
+          expect(method2, 'GET');
+          expect(body2, isEmpty);
+          expect(headers2, containsPair('host', [loopback2]));
+          expect(headers2, containsPair('hello', ['world']));
+          expect(headers2, isNot(contains('authorization')));
+          expect(headers2, isNot(contains('cookie')));
+          // TODO: enable this test when `package:http` requires Dart >=3.13
+          // expect(headers2, isNot(contains('proxy-authorization')));
+        });
+
+        test('POST $code cross host redirect', () async {
+          final request =
+              Request('POST', Uri.http(localhost1, '/cross-host-$code'))
+                ..body = 'Hello World!'
+                ..followRedirects = true
+                ..maxRedirects = 1;
+          request.headers['hello'] = 'world';
+          request.headers['authorization'] = 'anything';
+          if (canSendCookieHeaders) {
+            request.headers['cookie'] = 'foo=bar';
+          }
+          if (canSendProxyAuthorizationHeaders) {
+            request.headers['proxy-authorization'] = 'anything';
+          }
+
+          final response = await client.send(request);
+          await response.stream.drain<void>();
+
+          final [server1, method1, body1, headers1] =
+              await httpServerQueue.next as List<Object?>;
+          expect(server1, 'server1');
+          expect(method1, 'POST');
+          expect(body1, 'Hello World!');
+          expect(headers1, containsPair('host', [localhost1]));
+          expect(headers1, containsPair('hello', ['world']));
+          expect(headers1, containsPair('authorization', ['anything']));
+          if (canSendCookieHeaders) {
+            expect(headers1, containsPair('cookie', ['foo=bar']));
+          }
+          if (canSendProxyAuthorizationHeaders) {
+            expect(headers1, containsPair('proxy-authorization', ['anything']));
+          }
+
+          // RFC 9110, 15.4.8-15.4.9:
+          // The user agent MAY use the Location field value for automatic
+          // redirection, and MUST NOT change the request method if it performs
+          // an automatic redirection to that URI.
+          expect(response.statusCode, anyOf(200, code));
+
+          if (response.statusCode == 200) {
+            expect(response.isRedirect, false);
+            if (response case BaseResponseWithUrl(url: final url)) {
+              expect(url, Uri.http(loopback2, '/'));
+            }
+
+            final [server2, method2, body2, headers2] =
+                await httpServerQueue.next as List<Object?>;
+            expect(server2, 'server2');
+            expect(method2, 'POST');
+            expect(body2, 'Hello World!');
+            expect(headers2, containsPair('host', [loopback2]));
+            expect(headers2, containsPair('hello', ['world']));
+            expect(headers2, isNot(contains('authorization')));
+            expect(headers2, isNot(contains('cookie')));
+            // TODO: enable this test when `package:http` requires Dart >=3.13
+            // expect(headers2, isNot(contains('proxy-authorization')));
+          }
+        });
+      }
+    },
+        skip: correctCrossHostRedirect
+            ? false
+            : 'not opted into cross origin redirect tests');
   });
 }