Imagine a client replacement sends Authorization: Bearer ci-only-secret to the initial server, which redirects to another loopback port. Test that the second server receives no credential, but also that a same-origin redirect retains it, so stripping every Authorization header cannot pass.
A second loopback port is a different origin.
I would judge the client change by what the receiving endpoints observe, alongside review of where credentials enter the request. The initial request alone cannot establish what happens after a redirect.
Define the credential policy before writing the test
This example chooses a narrow, origin-based policy. It is an acceptance criterion for the application, not a claim about the behavior any particular HTTP library promises:
- The initial request receives a synthetic Authorization header.
- A redirect within the same origin retains that header.
- A redirect to a different origin removes it.
- Once removed, the credential stays removed for the rest of that redirect chain, including a return to the original origin.
Decide whether this is your application's required policy before adapting the test. Do not silently substitute a library's defaults for that decision.
An origin consists of a scheme, host, and effective port. Different ports therefore create separate origins without needing external DNS or services.
This policy does not authorize sending credentials to arbitrary initial URLs. The caller must already trust the starting destination.
Use this redirect check table as the acceptance criteria:
| Check | Expected observation | What it catches |
|---|---|---|
| Direct request | Initial server receives the synthetic credential | A client that never attaches credentials |
| Same-origin redirect | Final endpoint receives the credential | An implementation that strips credentials on every redirect |
| Cross-origin redirect | Destination receives no Authorization header | Credential forwarding across the origin boundary |
| Cross-origin redirect followed by a return | Neither the intermediate destination nor the final source endpoint receives Authorization | Credentials restored after returning to the original origin |
| Deliberately unsafe implementation | Cross-origin assertion fails | A check that cannot detect the intended regression |
Observe both servers, not the client's request object
Save this fixture as test_redirect_credentials.py. It binds two servers to 127.0.0.1 on operating-system-assigned ports and records Authorization headers at the receiving endpoints. Replace the client import with your application's entry point as described below, or use the reference client in the appendix to check the fixture itself.
import unittest
from contextlib import ExitStack, contextmanager
from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer
from threading import Thread
from app_http import get
TOKEN = "Bearer ci-only-secret"
@contextmanager
def local_server(routes):
seen = []
class Handler(BaseHTTPRequestHandler):
def do_GET(self):
seen.append((
self.path,
self.headers.get_all("Authorization", []),
))
location = routes.get(self.path)
if location is not None:
self.send_response(302)
self.send_header("Location", location)
self.send_header("Content-Length", "0")
self.end_headers()
else:
body = b"ok"
self.send_response(200)
self.send_header("Content-Length", str(len(body)))
self.end_headers()
self.wfile.write(body)
def log_message(self, *_args):
pass
server = ThreadingHTTPServer(("127.0.0.1", 0), Handler)
thread = Thread(target=server.serve_forever, daemon=True)
thread.start()
base_url = f"http://127.0.0.1:{server.server_port}"
try:
yield base_url, seen
finally:
server.shutdown()
server.server_close()
thread.join()
class RedirectCredentialsTest(unittest.TestCase):
def setUp(self):
stack = ExitStack()
self.addCleanup(stack.close)
destination_routes = {}
self.destination, self.destination_seen = stack.enter_context(
local_server(destination_routes)
)
routes = {}
self.source, self.source_seen = stack.enter_context(
local_server(routes)
)
routes["/same"] = self.source + "/sink"
routes["/cross"] = self.destination + "/sink"
routes["/return"] = self.destination + "/back"
destination_routes["/back"] = self.source + "/sink"
def request(self, path):
result = get(
self.source + path,
headers={"Authorization": TOKEN},
)
self.assertEqual(result, (200, b"ok"))
def test_direct_request_retains_authorization(self):
self.request("/sink")
self.assertEqual(self.source_seen, [("/sink", [TOKEN])])
self.assertEqual(self.destination_seen, [])
def test_same_origin_redirect_retains_authorization(self):
self.request("/same")
self.assertEqual(self.source_seen, [
("/same", [TOKEN]),
("/sink", [TOKEN]),
])
self.assertEqual(self.destination_seen, [])
def test_cross_origin_redirect_removes_authorization(self):
self.request("/cross")
self.assertEqual(self.source_seen, [("/cross", [TOKEN])])
self.assertEqual(self.destination_seen, [("/sink", [])])
def test_return_to_origin_does_not_restore_authorization(self):
self.request("/return")
self.assertEqual(self.source_seen, [
("/return", [TOKEN]),
("/sink", []),
])
self.assertEqual(self.destination_seen, [("/back", [])])
if __name__ == "__main__":
unittest.main()
The assertions check exact request sequences as well as headers. A client that refuses to follow the redirect cannot pass merely because the destination saw no credentials: the test requires a request to /sink and a successful response.
Using get_all() also makes duplicate Authorization fields visible. The cross-origin destination must receive none, rather than an empty value or a single acceptable-looking field. The return-to-origin test checks both receiving servers, enforcing that credentials stay absent after the first boundary crossing.
A test that never reaches the destination cannot verify destination behavior.
Point the fixture at the application's real client path
Replace from app_http import get with an import or thin adapter around the function your application actually calls. A green run against the reference implementation alone does not verify your application's HTTP stack.
The adapter should normalize the call and return value, not implement its own redirect policy. Otherwise, the fixture verifies the adapter while bypassing the behavior under review.
Keep the relevant production configuration in that path, including redirect settings, authentication middleware, and any wrapper that retries requests. Those layers can change which headers reach the destination even when the initial request looks correct.
I would use this behavioral check alongside static analysis. Static review can inspect the header-removal logic; the two-server fixture observes the result after the exercised client layers have run. Neither substitutes for the other.
The fixture exercises HTTP GET requests, cross-origin port changes, a return to the original origin, and 302 responses. It does not establish behavior for HTTPS transitions, other redirect statuses, different hostnames, cookies, proxy authentication, or broader server-side request forgery defenses. Add cases for supported application behavior rather than extending the claim beyond what the fixture exercises.
Keep stripped headers stripped on subsequent hops
The reference client in the appendix follows redirects explicitly. Its important state transition is current_headers:
next_url = urljoin(current_url, location)
current_headers = _redirect_headers(
current_headers, current_url, next_url
)
current_url = next_url
After crossing an origin boundary, subsequent hops use the stripped headers rather than reconstructing them from the original credentials. Returning to the original origin therefore does not restore Authorization.
To run the fixture:
python -m unittest -v test_redirect_credentials
Make the unsafe implementation fail on purpose
Temporarily replace _redirect_headers in the isolated reference client with this deliberately unsafe implementation:
def _redirect_headers(headers, current_url, next_url):
return dict(headers)
Run the same test command again. In test_cross_origin_redirect_removes_authorization, the destination assertion expects [], but unsafe forwarding sends [TOKEN]. The return-to-origin test should also fail because the credential is forwarded throughout the chain.
That mutation checks the test's sensitivity to the exact bug you care about. If the test still passes, investigate whether it is importing the expected code or whether another layer is changing the headers. Restore the safe implementation afterward.
The same-origin control catches the opposite mistake: stripping credentials on every redirect.
Appendix: reference client for checking the fixture
Save this Python standard-library implementation as app_http.py beside the test file. It supports HTTP GET requests for this isolated fixture, follows redirects explicitly, and closes each connection. It is not a general-purpose replacement for an application's HTTP client.
from http.client import HTTPConnection
from urllib.parse import urljoin, urlsplit
REDIRECTS = {301, 302, 303, 307, 308}
def _origin(url):
parts = urlsplit(url)
if parts.scheme != "http" or not parts.hostname:
raise ValueError("This fixture supports HTTP URLs only")
if parts.username is not None or parts.password is not None:
raise ValueError("URL credentials are outside this fixture")
return (parts.scheme, parts.hostname, parts.port or 80)
def _redirect_headers(headers, current_url, next_url):
if _origin(current_url) == _origin(next_url):
return dict(headers)
return {
name: value
for name, value in headers.items()
if name.lower() != "authorization"
}
def get(url, headers):
current_url = url
current_headers = dict(headers)
for hop in range(6):
_, host, port = _origin(current_url)
parts = urlsplit(current_url)
target = parts.path or "/"
if parts.query:
target += "?" + parts.query
connection = HTTPConnection(host, port, timeout=2)
try:
connection.request("GET", target, headers=current_headers)
response = connection.getresponse()
status = response.status
location = response.getheader("Location")
body = response.read()
finally:
connection.close()
if status not in REDIRECTS:
return status, body
if not location:
raise ValueError("Redirect has no Location header")
if hop == 5:
raise ValueError("Too many redirects")
next_url = urljoin(current_url, location)
current_headers = _redirect_headers(
current_headers, current_url, next_url
)
current_url = next_url
Connect the production entry point and run four checks
Today's action is to connect the fixture to the production entry point and run the direct, same-origin, cross-origin, and return-to-origin checks together. Use synthetic credentials and loopback endpoints, then keep that command in CI. Running the reference suite first is an optional fixture sanity check, not production verification.
Spend the first five minutes identifying the function and configuration the adapter must exercise. Completing the production transport setup may take longer. If the client does not support local HTTP endpoints, adapt the transport setup rather than weakening the assertion: the fixture needs a reachable test destination to provide evidence.