Debian Codegraph @

testsuite/daemon-http-proxy_test.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 """Coverage: RSYNC_PROXY HTTP CONNECT support (socket.c
3 establish_proxy_connection() + open_socket_out()'s proxy branch +
4 authenticate.c base64_encode() Proxy-Authorization).
5
6 A tiny in-process HTTP CONNECT proxy listens on PROXY_PORT, parses
7 `CONNECT host:port HTTP/1.0` (+ optional Proxy-Authorization), responds
8 `HTTP/1.0 200 OK`, then transparently relays bytes to the real test
9 daemon. Three legs:
10
11 1. RSYNC_PROXY=host:port (no auth) -> base CONNECT path
12 2. RSYNC_PROXY=user:pass@host:port -> base64_encode + Proxy-Auth header
13 3. proxy returns `HTTP/1.0 503 ...` -> the non-2xx error branch
14
15 This is the client-side counterpart to daemon-proxy-protocol_test.py
16 (which covers the daemon's PROXY-v1/v2 listener).
17 """
18
19 import base64
20 import os
21 import select
22 import socket
23 import subprocess
24 import threading
25
26 from rsyncfns import (
27 SCRATCHDIR, FROMDIR,
28 claim_ports, make_tree, makepath, require_tcp, rmtree, rsync_argv,
29 start_test_daemon, test_fail, write_daemon_conf,
30 )
31
32 # RSYNC_PROXY only fires on a real TCP socket connect (open_socket_out),
33 # not the RSYNC_CONNECT_PROG pipe transport.
34 require_tcp("RSYNC_PROXY uses open_socket_out(), needs a real TCP connect")
35
36 DAEMON_PORT = 19880
37 PROXY_PORT = 19881
38 claim_ports(DAEMON_PORT, PROXY_PORT)
39
40 src = FROMDIR
41 dst = SCRATCHDIR / 'dest-httpproxy'
42 rmtree(src); rmtree(dst)
43 make_tree(src, depth=1)
44 makepath(dst)
45
46 conf = write_daemon_conf(
47 [('mod', {'path': str(dst), 'read only': 'no'})],
48 name='http-proxy.conf',
49 )
50 url = start_test_daemon(conf, DAEMON_PORT)
51
52 seen_connects = []
53 seen_auths = []
54 deny_next = threading.Event()
55
56
57 def relay(a, b):
58 socks = [a, b]
59 while True:
60 r, _, _ = select.select(socks, [], [], 5)
61 if not r:
62 break
63 done = False
64 for s in r:
65 try:
66 buf = s.recv(65536)
67 except OSError:
68 buf = b''
69 if not buf:
70 done = True
71 break
72 (b if s is a else a).sendall(buf)
73 if done:
74 break
75 for s in socks:
76 try:
77 s.close()
78 except OSError:
79 pass
80
81
82 def proxy_handle(cli):
83 # Read header bytes until blank line. establish_proxy_connection() sends
84 # one CONNECT line + optional Proxy-Authorization line + CRLFCRLF.
85 hdr = b''
86 while b'\r\n\r\n' not in hdr and len(hdr) < 4096:
87 c = cli.recv(1)
88 if not c:
89 cli.close(); return
90 hdr += c
91 lines = hdr.split(b'\r\n')
92 seen_connects.append(lines[0].decode('ascii', 'replace'))
93 for ln in lines[1:]:
94 if ln.lower().startswith(b'proxy-authorization:'):
95 seen_auths.append(ln.decode('ascii', 'replace'))
96 if deny_next.is_set():
97 deny_next.clear()
98 cli.sendall(b'HTTP/1.0 503 Service Unavailable\r\n\r\n')
99 cli.close(); return
100 cli.sendall(b'HTTP/1.0 200 Connection established\r\n\r\n')
101 up = socket.create_connection(('127.0.0.1', DAEMON_PORT))
102 relay(cli, up)
103
104
105 def proxy_loop(lsock):
106 while True:
107 try:
108 c, _ = lsock.accept()
109 except OSError:
110 return
111 threading.Thread(target=proxy_handle, args=(c,), daemon=True).start()
112
113
114 lsock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
115 lsock.setsockopt(socket.SOL_SOCKET, socket.SO_REUSEADDR, 1)
116 lsock.bind(('127.0.0.1', PROXY_PORT))
117 lsock.listen(8)
118 threading.Thread(target=proxy_loop, args=(lsock,), daemon=True).start()
119
120
121 def push_via_proxy(proxy_spec, expect_ok=True):
122 env = dict(os.environ, RSYNC_PROXY=proxy_spec)
123 # Any host:port the client asks to CONNECT to is fine; the mock proxy
124 # always relays to DAEMON_PORT regardless. Use a non-loopback name so
125 # the CONNECT line is recognizable.
126 r = subprocess.run(
127 rsync_argv('-r', f'{src}/',
128 f'rsync://upstream.example:{DAEMON_PORT}/mod/'),
129 env=env, capture_output=True, text=True,
130 )
131 if expect_ok and r.returncode != 0:
132 test_fail(f"RSYNC_PROXY={proxy_spec!r}: rc={r.returncode}\n{r.stderr}")
133 if not expect_ok and r.returncode == 0:
134 test_fail(f"RSYNC_PROXY={proxy_spec!r}: expected failure, got rc=0")
135 return r
136
137
138 # --- leg 1: no auth --------------------------------------------------------
139 push_via_proxy(f'127.0.0.1:{PROXY_PORT}')
140 if not seen_connects or 'CONNECT upstream.example:' not in seen_connects[-1]:
141 test_fail(f"mock proxy never saw CONNECT (got: {seen_connects!r})")
142
143 # --- leg 2: user:pass@ -> Proxy-Authorization: Basic base64(...) ----------
144 seen_auths.clear()
145 push_via_proxy(f'puser:[email protected]:{PROXY_PORT}')
146 if not seen_auths:
147 test_fail("RSYNC_PROXY=user:pass@... should have sent Proxy-Authorization")
148 want = 'Basic ' + base64.b64encode(b'puser:ppass').decode()
149 if want not in seen_auths[-1]:
150 test_fail(f"Proxy-Authorization mismatch: {seen_auths[-1]!r} vs {want!r}")
151
152 # --- leg 3: proxy returns 503 -> client must fail with the bad-response msg
153 deny_next.set()
154 r = push_via_proxy(f'127.0.0.1:{PROXY_PORT}', expect_ok=False)
155 if 'bad response from proxy' not in r.stderr and '503' not in r.stderr:
156 test_fail(f"503 from proxy should surface as 'bad response': {r.stderr!r}")
157
158 lsock.close()
159 print(f"daemon-http-proxy: CONNECT (no-auth + Basic auth) + 503-deny ok")