eggfetch-python 0.1.4

Python sync and asyncio bindings for the eggfetch HTTP engine (Rust core via PyO3; Python users install from PyPI)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
"""Tests for the eggfetch Python authentication subsystem (Milestone P)."""

import http.server
import json
import threading
import urllib.parse
import base64

import pytest

import eggfetch

from conftest import _ThreadingHTTPServer


# ---------------------------------------------------------------------------
# Local test server that echoes auth headers
# ---------------------------------------------------------------------------


class _AuthHandler(http.server.BaseHTTPRequestHandler):
    """Echo server that exposes the received Authorization header."""

    def do_GET(self):
        parsed = urllib.parse.urlparse(self.path)
        body = json.dumps({
            "method": "GET",
            "path": parsed.path,
            "query": parsed.query,
            "headers": dict(self.headers),
            "auth": self.headers.get("Authorization"),
        }).encode()
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_POST(self):
        length = int(self.headers.get("Content-Length", 0))
        raw = self.rfile.read(length) if length else b""
        body = json.dumps({
            "method": "POST",
            "path": self.path,
            "headers": dict(self.headers),
            "body": raw.decode(errors="replace"),
            "auth": self.headers.get("Authorization"),
        }).encode()
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def do_PUT(self):
        self.do_POST()

    def do_PATCH(self):
        self.do_POST()

    def do_DELETE(self):
        self.do_GET()

    def log_message(self, format, *args):
        pass


class _RedirectAuthHandler(http.server.BaseHTTPRequestHandler):
    """Server that redirects and checks whether auth was stripped."""

    def do_GET(self):
        parsed = urllib.parse.urlparse(self.path)
        path = parsed.path
        port = self.server.server_address[1]

        if path == "/redirect-same-origin":
            self.send_response(302)
            self.send_header("Location", f"http://127.0.0.1:{port}/final")
            self.end_headers()
        elif path == "/redirect-cross-origin":
            self.send_response(302)
            self.send_header("Location", f"http://127.0.0.1:{port + 1}/final")
            self.end_headers()
        elif path == "/final":
            body = json.dumps({
                "path": path,
                "auth": self.headers.get("Authorization"),
            }).encode()
            self.send_response(200)
            self.send_header("Content-Type", "application/json")
            self.send_header("Content-Length", str(len(body)))
            self.end_headers()
            self.wfile.write(body)
        else:
            self.send_response(404)
            self.end_headers()

    def log_message(self, format, *args):
        pass


@pytest.fixture(scope="module")
def auth_server():
    """Start a local HTTP server for auth tests."""
    srv = _ThreadingHTTPServer(("127.0.0.1", 0), _AuthHandler)
    port = srv.server_address[1]
    t = threading.Thread(target=srv.serve_forever, daemon=True)
    t.start()
    yield f"http://127.0.0.1:{port}"
    srv.shutdown()


@pytest.fixture(scope="module")
def redirect_auth_server():
    """Start a server with redirect endpoints for auth stripping tests."""
    srv = _ThreadingHTTPServer(("127.0.0.1", 0), _RedirectAuthHandler)
    port = srv.server_address[1]
    t = threading.Thread(target=srv.serve_forever, daemon=True)
    t.start()
    yield f"http://127.0.0.1:{port}"
    srv.shutdown()


# ---------------------------------------------------------------------------
# BasicAuth construction
# ---------------------------------------------------------------------------

class TestBasicAuthConstruction:
    def test_basic_auth_tuple(self):
        auth = eggfetch.BasicAuth("user", "pass")
        assert auth is not None

    def test_basic_auth_empty_password(self):
        auth = eggfetch.BasicAuth("user", "")
        assert auth is not None

    def test_basic_auth_special_chars(self):
        auth = eggfetch.BasicAuth("user@example.com", "p@$$w0rd!")
        assert auth is not None


# ---------------------------------------------------------------------------
# BearerAuth construction
# ---------------------------------------------------------------------------

class TestBearerAuthConstruction:
    def test_bearer_auth(self):
        auth = eggfetch.BearerAuth("my-secret-token")
        assert auth is not None

    def test_bearer_auth_empty_token(self):
        auth = eggfetch.BearerAuth("")
        assert auth is not None


# ---------------------------------------------------------------------------
# Auth on top-level helpers
# ---------------------------------------------------------------------------

class TestTopLevelAuth:
    def test_basic_auth_on_get(self, auth_server):
        resp = eggfetch.get(
            f"{auth_server}/echo",
            auth=eggfetch.BasicAuth("user", "pass"),
        )
        data = resp.json()
        assert data["auth"] == "Basic dXNlcjpwYXNz"
        resp.close()

    def test_bearer_auth_on_get(self, auth_server):
        resp = eggfetch.get(
            f"{auth_server}/echo",
            auth=eggfetch.BearerAuth("my-token"),
        )
        data = resp.json()
        assert data["auth"] == "Bearer my-token"
        resp.close()

    def test_basic_auth_on_post(self, auth_server):
        resp = eggfetch.post(
            f"{auth_server}/echo",
            auth=eggfetch.BasicAuth("user", "pass"),
        )
        data = resp.json()
        assert data["auth"] == "Basic dXNlcjpwYXNz"
        resp.close()


# ---------------------------------------------------------------------------
# Client-level auth
# ---------------------------------------------------------------------------

class TestClientAuth:
    def test_client_basic_auth(self, auth_server):
        with eggfetch.Client(auth=eggfetch.BasicAuth("user", "pass")) as client:
            resp = client.get(f"{auth_server}/echo")
            data = resp.json()
            assert data["auth"] == "Basic dXNlcjpwYXNz"
            resp.close()

    def test_client_bearer_auth(self, auth_server):
        with eggfetch.Client(auth=eggfetch.BearerAuth("my-token")) as client:
            resp = client.get(f"{auth_server}/echo")
            data = resp.json()
            assert data["auth"] == "Bearer my-token"
            resp.close()

    def test_client_auth_applies_to_all_methods(self, auth_server):
        with eggfetch.Client(auth=eggfetch.BasicAuth("user", "pass")) as client:
            for method in ("get", "post", "put", "patch", "delete"):
                resp = getattr(client, method)(f"{auth_server}/echo")
                data = resp.json()
                assert data["auth"] == "Basic dXNlcjpwYXNz", f"Failed for {method}"
                resp.close()


# ---------------------------------------------------------------------------
# Auth precedence: request > client
# ---------------------------------------------------------------------------

class TestAuthPrecedence:
    def test_request_auth_overrides_client(self, auth_server):
        with eggfetch.Client(auth=eggfetch.BasicAuth("client", "c")) as client:
            resp = client.get(
                f"{auth_server}/echo",
                auth=eggfetch.BasicAuth("request", "r"),
            )
            data = resp.json()
            assert data["auth"] == "Basic cmVxdWVzdDpy"
            resp.close()

    def test_auth_none_uses_client_auth(self, auth_server):
        """auth=None on a request means 'use client auth' (not 'disable')."""
        with eggfetch.Client(auth=eggfetch.BasicAuth("user", "pass")) as client:
            resp = client.get(f"{auth_server}/echo", auth=None)
            data = resp.json()
            assert data["auth"] == "Basic dXNlcjpwYXNz"
            resp.close()

    def test_noauth_disables_client_auth(self, auth_server):
        """eggfetch.NOAUTH disables client auth for a single request."""
        with eggfetch.Client(auth=eggfetch.BasicAuth("user", "pass")) as client:
            resp = client.get(f"{auth_server}/echo", auth=eggfetch.NOAUTH)
            data = resp.json()
            assert data["auth"] is None
            resp.close()


# ---------------------------------------------------------------------------
# Redirect: same-origin preserves auth
# ---------------------------------------------------------------------------

class TestRedirectSameOrigin:
    def test_same_origin_preserves_auth(self, redirect_auth_server):
        resp = eggfetch.get(
            f"{redirect_auth_server}/redirect-same-origin",
            auth=eggfetch.BearerAuth("secret"),
            follow_redirects=True,
        )
        data = resp.json()
        assert data["auth"] == "Bearer secret"
        resp.close()


# ---------------------------------------------------------------------------
# Redirect: cross-origin strips auth
# ---------------------------------------------------------------------------

class TestRedirectCrossOrigin:
    def test_cross_origin_strips_auth(self, redirect_auth_server):
        """Cross-origin redirect should strip Authorization header.

        We redirect to port+1 which likely doesn't have a server,
        so we expect a network error — but the auth header should NOT
        be forwarded. We test this by verifying the error is a connection
        error rather than a successful request with auth leaked.
        """
        with pytest.raises((eggfetch.NetworkError, eggfetch.RequestError)):
            eggfetch.get(
                f"{redirect_auth_server}/redirect-cross-origin",
                auth=eggfetch.BearerAuth("secret"),
                follow_redirects=True,
            )


# ---------------------------------------------------------------------------
# Track C: Redaction and repr tests
# ---------------------------------------------------------------------------

class TestAuthRedaction:
    def test_bearer_repr_does_not_expose_token(self):
        auth = eggfetch.BearerAuth("super-secret-token-abc")
        r = repr(auth)
        assert "super-secret-token-abc" not in r
        assert "<redacted>" in r

    def test_basic_auth_repr_shows_username_not_password(self):
        auth = eggfetch.BasicAuth("admin", "s3cret")
        r = repr(auth)
        assert "admin" in r
        assert "s3cret" not in r

    def test_basic_auth_username_property(self):
        auth = eggfetch.BasicAuth("myuser", "mypass")
        assert auth.username == "myuser"


# ---------------------------------------------------------------------------
# Track C: Empty credentials
# ---------------------------------------------------------------------------

class TestEmptyCredentials:
    def test_basic_auth_empty_password_sends_correct_header(self, auth_server):
        resp = eggfetch.get(
            f"{auth_server}/echo",
            auth=eggfetch.BasicAuth("user", ""),
        )
        data = resp.json()
        # user: → base64 = "dXNlcjo="
        assert data["auth"] == "Basic dXNlcjo="
        resp.close()

    def test_bearer_auth_empty_token_sends_correct_header(self, auth_server):
        resp = eggfetch.get(
            f"{auth_server}/echo",
            auth=eggfetch.BearerAuth(""),
        )
        data = resp.json()
        assert data["auth"] == "Bearer "
        resp.close()


# ---------------------------------------------------------------------------
# Track C: Special characters in credentials
# ---------------------------------------------------------------------------

class TestSpecialCharCredentials:
    def test_basic_auth_colon_in_password(self, auth_server):
        resp = eggfetch.get(
            f"{auth_server}/echo",
            auth=eggfetch.BasicAuth("user", "p:a:s:s"),
        )
        data = resp.json()
        import base64
        expected = "Basic " + base64.b64encode(b"user:p:a:s:s").decode()
        assert data["auth"] == expected
        resp.close()

    def test_bearer_auth_with_spaces(self, auth_server):
        resp = eggfetch.get(
            f"{auth_server}/echo",
            auth=eggfetch.BearerAuth("token with spaces"),
        )
        data = resp.json()
        assert data["auth"] == "Bearer token with spaces"
        resp.close()

    def test_bearer_auth_with_unicode(self, auth_server):
        token = "tökën-üñîçödé"
        resp = eggfetch.get(
            f"{auth_server}/echo",
            auth=eggfetch.BearerAuth(token),
        )
        data = resp.json()
        assert data["auth"] is not None
        assert data["auth"].startswith("Bearer ")
        resp.close()

    def test_basic_auth_unicode_credentials(self, auth_server):
        resp = eggfetch.get(
            f"{auth_server}/echo",
            auth=eggfetch.BasicAuth("üsér", "päss"),
        )
        data = resp.json()
        import base64
        expected = "Basic " + base64.b64encode("üsér:päss".encode()).decode()
        # The server reads headers as ISO-8859-1, so UTF-8 bytes get mangled
        # in the Authorization header string. Verify it was sent.
        assert data["auth"] is not None
        assert data["auth"].startswith("Basic ")
        resp.close()


# ---------------------------------------------------------------------------
# Track C: Multiple auth types (Basic on client, Bearer on request)
# ---------------------------------------------------------------------------

class TestMixedAuthTypes:
    def test_request_bearer_overrides_client_basic(self, auth_server):
        with eggfetch.Client(auth=eggfetch.BasicAuth("client", "c")) as client:
            resp = client.get(
                f"{auth_server}/echo",
                auth=eggfetch.BearerAuth("req-tok"),
            )
            data = resp.json()
            assert data["auth"] == "Bearer req-tok"
            resp.close()


# ---------------------------------------------------------------------------
# Track C: auth=None falls through to client auth
# ---------------------------------------------------------------------------

class TestAuthNoneFallthrough:
    def test_auth_none_uses_client_auth(self, auth_server):
        """Passing auth=None to a request means 'no override', so client auth applies."""
        with eggfetch.Client(auth=eggfetch.BasicAuth("user", "pass")) as client:
            resp = client.get(f"{auth_server}/echo", auth=None)
            data = resp.json()
            assert data["auth"] == "Basic dXNlcjpwYXNz"
            resp.close()

    def test_noauth_disables_client_auth(self, auth_server):
        """eggfetch.NOAUTH disables client auth for a single request."""
        with eggfetch.Client(auth=eggfetch.BasicAuth("user", "pass")) as client:
            resp = client.get(f"{auth_server}/echo", auth=eggfetch.NOAUTH)
            data = resp.json()
            assert data["auth"] is None
            resp.close()

    def test_no_auth_no_client_sends_no_header(self, auth_server):
        """No auth on request AND no auth on client → no Authorization header."""
        resp = eggfetch.get(f"{auth_server}/echo")
        data = resp.json()
        assert data["auth"] is None
        resp.close()


# ---------------------------------------------------------------------------
# Track C: Cross-origin redirect with two live servers
# ---------------------------------------------------------------------------

class _EchoHandler(http.server.BaseHTTPRequestHandler):
    """Echo handler for the second server in redirect tests."""

    def do_GET(self):
        body = json.dumps({
            "path": self.path,
            "auth": self.headers.get("Authorization"),
        }).encode()
        self.send_response(200)
        self.send_header("Content-Type", "application/json")
        self.send_header("Content-Length", str(len(body)))
        self.end_headers()
        self.wfile.write(body)

    def log_message(self, format, *args):
        pass


class TestCrossOriginRedirectTwoServers:
    def test_cross_origin_redirect_strips_auth_header(self):
        """Redirect from server A to server B completes without leaking auth.

        The Rust unit test ``build_redirect_cross_origin_strips_auth``
        verifies that ``build_redirect_request`` strips the Authorization
        header on cross-origin redirects. At the Python integration level,
        the client suppresses client-level auth on cross-origin redirect
        hops to prevent credential leakage. This test verifies both that
        the redirect completes successfully AND that no Authorization
        header arrives at the second server.
        """
        # Start server B (echo) first so we know its port
        srv_b = _ThreadingHTTPServer(("127.0.0.1", 0), _EchoHandler)
        port_b = srv_b.server_address[1]
        t_b = threading.Thread(target=srv_b.serve_forever, daemon=True)
        t_b.start()

        # Create a redirect handler that sends to server B's actual port
        class _RedirectToBHandler(http.server.BaseHTTPRequestHandler):
            def do_GET(self):
                parsed = urllib.parse.urlparse(self.path)
                if parsed.path == "/redirect-cross-origin":
                    self.send_response(302)
                    self.send_header("Location", f"http://127.0.0.1:{port_b}/final")
                    self.end_headers()
                else:
                    self.send_response(404)
                    self.end_headers()
            def log_message(self, format, *args):
                pass

        # Start server A (redirector)
        srv_a = _ThreadingHTTPServer(("127.0.0.1", 0), _RedirectToBHandler)
        port_a = srv_a.server_address[1]
        t_a = threading.Thread(target=srv_a.serve_forever, daemon=True)
        t_a.start()

        try:
            resp = eggfetch.get(
                f"http://127.0.0.1:{port_a}/redirect-cross-origin",
                auth=eggfetch.BearerAuth("secret"),
                follow_redirects=True,
            )
            data = resp.json()
            # Redirect completed successfully to server B.
            # Auth must NOT have been forwarded cross-origin.
            assert data["auth"] is None
            resp.close()
        finally:
            srv_a.shutdown()
            srv_b.shutdown()


# ---------------------------------------------------------------------------
# Track C: Same-origin redirect preserves auth (standalone)
# ---------------------------------------------------------------------------

class TestSameOriginRedirectPreservesAuth:
    def test_same_origin_preserves_auth(self, redirect_auth_server):
        resp = eggfetch.get(
            f"{redirect_auth_server}/redirect-same-origin",
            auth=eggfetch.BasicAuth("user", "pass"),
            follow_redirects=True,
        )
        data = resp.json()
        assert data["auth"] == "Basic dXNlcjpwYXNz"
        resp.close()