authoravatarclover caruso<git@paperclover.net>2026-10-17 13:43:51-07:00
committeravatarclover caruso<git@paperclover.net>2026-10-21 02:52:29-07:00
log37e0df5408fde20231e6a694bacc5f458946535e
tree519073da5ce32a8370f837c4603f4788eabd5a28
parent2532a0bae3c550f509e7d8945df1357b8639ef01
signature Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU

Open CLIProxyAPI management through Snow SSO

Validate native panel access through same-origin config requests after Snow sign-in. Keep management credentials on the server, remove remembered native auth, enforce management write origins, and send logout through forward-auth. Preserve the independent client API gate. Verified with 17 native gateway/panel tests, isolated inference and restart checks, browser remembered-key and logout flows, and an independent security review. Assisted-by: gpt-6.1-sol

6 files changed, 271 insertions(+), 13 deletions(-)

service/cliproxy/nginx.conf+23
......@@ -26,10 +26,26 @@ http {
2626 default 0;
2727 ~^(?:GET|HEAD):/(?:v0/management/oauth-callback|v8/management/oauth/callback|(?:anthropic|codex|antigravity|devin)/callback|callback)/?$ 1;
2828 }
29 map "$request_method:$http_origin" $admin_origin {
30 default 0;
31 "GET:" 1;
32 "HEAD:" 1;
33 "GET:https://ADMIN_HOST" 1;
34 "HEAD:https://ADMIN_HOST" 1;
35 "POST:https://ADMIN_HOST" 1;
36 "PUT:https://ADMIN_HOST" 1;
37 "PATCH:https://ADMIN_HOST" 1;
38 "DELETE:https://ADMIN_HOST" 1;
39 }
2940 {{ with nomadVar "NOMAD_VARIABLE" }}
3041 map $http_authorization $bearer_key { default 0; "Bearer {{ .api_key.Value }}" 1; }
3142 map $http_x_api_key $claude_key { default 0; "{{ .api_key.Value }}" 1; }
3243 map $client_key $upstream_authorization { default ""; 1 "Bearer {{ .api_key.Value }}"; }
44 map "$request_method:$uri" $admin_authorization {
45 default "";
46 ~^[A-Z]+:/v(?:0|8)/management/ "Bearer {{ .management_key.Value }}";
47 "GET:/v1/models" "Bearer {{ .api_key.Value }}";
48 }
3349 {{ end }}
3450 map "$bearer_key:$claude_key" $client_key { default 1; "0:0" 0; }
3551 upstream cliproxy_backend {
......@@ -46,12 +62,19 @@ http {
4662 server_name ADMIN_HOST;
4763 client_max_body_size 32m;
4864 location = / { return 302 /management.html; }
65 location = /sign-out { return 303 /snow.oauth2/sign_out?rd=https%3A%2F%2FSSO_HOST%2Fsign-in; }
4966 location / {
5067 if ($browser_oauth_callback = 1) { return 404; }
5168 if ($arg_code != "") { return 404; }
69 if ($admin_origin = 0) { return 403; }
5270 proxy_pass http://cliproxy_backend;
5371 proxy_http_version 1.1;
5472 proxy_set_header Host $host;
73 proxy_set_header Authorization $admin_authorization;
74 proxy_set_header X-Management-Key "";
75 proxy_set_header Cookie "";
76 proxy_hide_header Access-Control-Allow-Origin;
77 add_header Cache-Control no-store always;
5578 proxy_buffering off;
5679 proxy_read_timeout 3600s;
5780 }
service/cliproxy/panel-test.mjs created+110
......@@ -0,0 +1,110 @@
1import assert from 'node:assert/strict';
2import { readFileSync } from 'node:fs';
3import { request } from 'node:http';
4import vm from 'node:vm';
5
6const [panelPath, origin, host] = process.argv.slice(2);
7const panel = readFileSync(panelPath, 'utf8');
8function between(start, end) {
9 const offset = panel.indexOf(start);
10 assert(offset >= 0, 'Pinned native code entry exists');
11 const limit = panel.indexOf(end, offset);
12 assert(limit > offset, 'Pinned native code exit exists');
13 return panel.slice(offset, limit);
14}
15const nativeStore = between('var yc=e=>', 'function Tc()');
16const nativeStorage = 'var ' + between('_l=`enc::v1::`', 'function Al(e,t)');
17const nativeAuth = 'var Pm=null,' + between('Fm=wc()(', '));typeof window') + '));';
18const nativeRoute = between('function tse({children:e})', 'function nse()');
19
20for (const [remembered, rejected] of [[false, false], [true, false], [true, true]]) {
21 const storage = new Map();
22 const requests = [];
23 const effects = [];
24 const location = { origin, host: new URL(origin).host, assign: value => requests.push(value) };
25 const localStorage = {
26 getItem: key => storage.get(key) ?? null,
27 setItem: (key, value) => storage.set(key, String(value)),
28 removeItem: key => storage.delete(key),
29 };
30 let connection;
31 let revision = 0;
32 const context = vm.createContext({
33 window: { location, localStorage }, localStorage,
34 navigator: { userAgent: 'synthetic-native-auth-test' },
35 TextEncoder, TextDecoder, Uint8Array, btoa, atob, console,
36 y: {
37 useSyncExternalStore: (_, snapshot) => snapshot(),
38 useCallback: callback => callback,
39 useDebugValue() {},
40 useState: value => [value, () => {}],
41 useEffect: callback => effects.push(callback),
42 },
43 dr: () => ({ pathname: '/' }),
44 H: { jsx: (type, props) => ({ type, props }) },
45 ti: 'redirect', tO: 'loading',
46 Bc: 'cli-proxy-auth',
47 tp: value => value.replace(/\/+$/, ''),
48 G: {
49 setConfig: value => { connection = value; revision++; },
50 getConnectionRevision: () => revision,
51 },
52 Vp: { getState: () => ({
53 clearCache() {},
54 async fetchConfig() {
55 assert(connection.apiBase === origin, 'Restore uses the current origin');
56 assert(connection.managementKey === '', 'Browser sends no management secret');
57 requests.push(connection.apiBase);
58 return new Promise((resolve, reject) => {
59 const pending = request(connection.apiBase + '/v8/management/config', {
60 headers: { Host: host, ...(rejected ? { 'X-Synthetic-Reject': 'yes' } : {}) },
61 }, response => {
62 let body = '';
63 response.setEncoding('utf8');
64 response.on('data', chunk => { body += chunk; });
65 response.on('end', () => {
66 if (response.statusCode !== 200) reject(Object.assign(new Error('Synthetic backend rejection'), { status: response.statusCode }));
67 else resolve(JSON.parse(body));
68 });
69 });
70 pending.on('error', reject);
71 pending.end();
72 });
73 },
74 }) },
75 sm: { getState: () => ({ clearCache() {} }) },
76 jm: { getState: () => ({ clearQuotaCache() {} }) },
77 });
78 vm.runInContext(nativeStore + nativeStorage, context);
79 if (remembered) {
80 vm.runInContext('kl.setItem(Bc,{state:{apiBase:"https://obsolete.example",managementKey:"synthetic-old-password",rememberPassword:true},version:0});kl.setItem("managementKey","synthetic-old-password");localStorage.setItem("isLoggedIn","true")', context);
81 }
82 vm.runInContext(nativeAuth + nativeRoute, context);
83 const auth = context.Fm;
84 assert(!auth.getState().isAuthenticated, 'Stored credentials do not establish authentication');
85 assert(auth.getState().managementKey === '', 'Remembered password never hydrates into the native store');
86 assert(auth.getState().apiBase === '', 'Remembered connection never hydrates into the native store');
87 const route = vm.runInContext('tse({children:"protected"})', context);
88 for (const effect of effects) effect();
89 assert(route.type === 'redirect' && route.props.to === '/login', 'Protected route enters the SSO restore flow');
90 assert(requests.length === 0, 'Protected route never revalidates a remembered password');
91 const pending = auth.getState().restoreSession();
92 assert(!auth.getState().isAuthenticated, 'Authentication waits for the real config response');
93 assert(localStorage.getItem('managementKey') === null, 'Legacy password is removed before the request');
94 assert(localStorage.getItem('cli-proxy-auth') === null, 'Persisted password is removed before the request');
95 assert(await pending === !rejected, 'Restore follows the backend result');
96 assert(await auth.getState().restoreSession() === !rejected, 'Concurrent restore shares the validated result');
97 assert(requests.length === 1, 'Restore validates once');
98 assert(auth.getState().isAuthenticated === !rejected, 'Only the successful backend response authenticates');
99 assert(auth.getState().connectionStatus === (rejected ? 'error' : 'connected'), 'Native connection status follows the backend');
100 assert(auth.getState().managementKey === '', 'Native state retains no password');
101 assert(!auth.getState().rememberPassword, 'Native password persistence is disabled');
102 assert(localStorage.getItem('isLoggedIn') === null, 'No persisted authenticated flag is needed');
103 assert(localStorage.getItem('cli-proxy-auth') === null, 'Native auth state remains transient');
104 if (!rejected) assert(await auth.getState().checkAuth(), 'Native revalidation accepts SSO without a browser key');
105 const logout = panel.match(/onClick:(\(\)=>window\.location\.assign\([^)]*\)),title:e\(`header\.logout`\)/);
106 assert(logout, 'Native logout uses the SSO exit');
107 vm.runInContext('(' + logout[1] + ')()', context);
108 assert(requests.at(-1) === '/sign-out', 'Logout reaches the fixed server redirect');
109}
110console.log('Pinned native auth store: fresh, remembered, rejected, revalidation, and logout passed');
service/cliproxy/prepare.py+24-1
......@@ -3,6 +3,7 @@ import hashlib
33import json
44import os
55from pathlib import Path
6import re
67import stat
78import sys
89import tempfile
......@@ -12,6 +13,7 @@ import urllib.request
1213PANEL_URL = "https://github.com/router-for-me/Cli-Proxy-API-Management-Center/releases/download/v1.26.5/management.html"
1314PANEL_SHA256 = "57558cd023475674634a114824b014d3e5ac161f6f3791e3d86b6adab962a700"
1415PANEL_SIZE = 3312180
16PANEL_SSO_SHA256 = "fdb185df6395bb6652af7171d7193be9a568d027d66d5cd0106b797494f5b4f0"
1517
1618
1719def prepare(data):
......@@ -25,13 +27,34 @@ def prepare(data):
2527 metadata = panel.stat()
2628 if not stat.S_ISREG(metadata.st_mode):
2729 raise ValueError("CLIProxyAPI panel must be a regular file")
28 if metadata.st_size == PANEL_SIZE and hashlib.sha256(panel.read_bytes()).hexdigest() == PANEL_SHA256:
30 if metadata.st_size <= PANEL_SIZE and hashlib.sha256(panel.read_bytes()).hexdigest() == PANEL_SSO_SHA256:
2931 panel.chmod(0o444)
3032 return
3133 with urllib.request.urlopen(PANEL_URL, timeout=60) as response:
3234 contents = response.read(PANEL_SIZE + 1)
3335 if len(contents) != PANEL_SIZE or hashlib.sha256(contents).hexdigest() != PANEL_SHA256:
3436 raise ValueError("CLIProxyAPI management panel failed checksum verification")
37 contents, count = re.subn(
38 rb"restoreSession:\(\)=>Pm\|\|\(Pm=\(async\(\)=>\{.*?\}\)\(\),Pm\),login:async",
39 b'restoreSession:()=>Pm||(Pm=(async()=>{localStorage.removeItem(`managementKey`);localStorage.removeItem(`isLoggedIn`);localStorage.removeItem(`cli-proxy-auth`);try{await t().login({apiBase:window.location.origin,managementKey:``,rememberPassword:!1});return!0}catch{return!1}})(),Pm),login:async',
40 contents,
41 )
42 if count != 1:
43 raise ValueError("CLIProxyAPI session restoration seam changed")
44 for before, after in [
45 (b'Fm=wc()(Xc(', b'Fm=wc()('),
46 (b'}),{name:Bc,storage:Jc(()=>({getItem:e=>{let t=kl.getItem(e);return t?JSON.stringify(t):null},setItem:(e,t)=>{kl.setItem(e,JSON.parse(t))},removeItem:e=>{kl.removeItem(e)}})),partialize:e=>({apiBase:e.apiBase,...e.rememberPassword?{managementKey:e.managementKey}:{},rememberPassword:e.rememberPassword,serverVersion:e.serverVersion,serverBuildDate:e.serverBuildDate})}));',
47 b'}));'),
48 (b'checkAuth:async()=>{let{managementKey:n,apiBase:r}=t();if(!n||!r)return!1;',
49 b'checkAuth:async()=>{let{managementKey:n,apiBase:r}=t();if(!r)return!1;'),
50 (b'onClick:r,title:e(`header.logout`)',
51 b'onClick:()=>window.location.assign(`/sign-out`),title:e(`header.logout`)'),
52 ]:
53 if contents.count(before) != 1:
54 raise ValueError("CLIProxyAPI management panel authentication seam changed")
55 contents = contents.replace(before, after)
56 if hashlib.sha256(contents).hexdigest() != PANEL_SSO_SHA256:
57 raise ValueError("CLIProxyAPI SSO panel failed checksum verification")
3558 with tempfile.NamedTemporaryFile(dir=static, prefix=".panel-", delete=False) as file:
3659 pending = Path(file.name)
3760 try:
service/cliproxy/service.pkl+2
......@@ -1,6 +1,7 @@
11amends "../../config/Service.pkl"
22
33import "../../config/site.pkl" as site
4import "../../config/OpenID.pkl" as sso
45
56name = "CLIProxyAPI"
67tagline = "Codex and Claude API access"
......@@ -55,5 +56,6 @@ container {
5556 .replaceAll("NOMAD_VARIABLE", "nomad/jobs/\(module.id)")
5657 .replaceAll("ADMIN_HOST", module.container.http.hostname!!)
5758 .replaceAll("API_HOST", module.container.http.plainHostnames[0])
59 .replaceAll("SSO_HOST", sso.hostname)
5860 }
5961}
tools/cliproxy-test.py+92-3
......@@ -27,6 +27,7 @@ spec = importlib.util.spec_from_file_location("cliproxy_prepare", SERVICE / "pre
2727prepare = importlib.util.module_from_spec(spec)
2828spec.loader.exec_module(prepare)
2929NGINX = None
30PANEL = None
3031API_KEY = "a1" * 32
3132MANAGEMENT_KEY = "b2" * 32
3233ADMIN_HOST = "cliproxy-preview-12345678.paperclover.net"
......@@ -132,7 +133,7 @@ class ServiceTests(unittest.TestCase):
132133 panel = static / "management.html"
133134 contents = b"pinned synthetic panel"
134135 panel.write_bytes(contents)
135 with patch.object(prepare, "PANEL_SIZE", len(contents)), patch.object(prepare, "PANEL_SHA256", hashlib.sha256(contents).hexdigest()), patch.object(prepare.urllib.request, "urlopen", side_effect=AssertionError("unexpected download")):
136 with patch.object(prepare, "PANEL_SSO_SHA256", hashlib.sha256(contents).hexdigest()), patch.object(prepare.urllib.request, "urlopen", side_effect=AssertionError("unexpected download")):
136137 prepare.prepare({"hostRoot": str(root), "uid": os.getuid()})
137138 self.assertEqual(panel.read_bytes(), contents)
138139
......@@ -144,7 +145,7 @@ class GatewayTests(unittest.TestCase):
144145 self.addCleanup(self.temporary.cleanup)
145146 root = Path(self.temporary.name)
146147 self.observed = []
147 self.secret_markers = [API_KEY]
148 self.secret_markers = [API_KEY, MANAGEMENT_KEY]
148149 observed = self.observed
149150
150151 class Backend(BaseHTTPRequestHandler):
......@@ -156,8 +157,17 @@ class GatewayTests(unittest.TestCase):
156157 def do_POST(self):
157158 self.respond()
158159
160 do_PUT = do_POST
161 do_PATCH = do_POST
162 do_DELETE = do_POST
163
159164 def respond(self):
160165 observed.append((self.command, self.path, dict(self.headers), self.rfile.read(int(self.headers.get('Content-Length', '0')))))
166 if self.path == '/v8/management/config' and (self.headers.get('Authorization') != 'Bearer ' + MANAGEMENT_KEY or self.headers.get('X-Synthetic-Reject')):
167 self.send_response(401)
168 self.send_header('Content-Length', '0')
169 self.end_headers()
170 return
161171 if self.headers.get("Upgrade", "").lower() == "websocket":
162172 accept = base64.b64encode(hashlib.sha1((self.headers['Sec-WebSocket-Key'] + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11').encode()).digest()).decode()
163173 self.send_response(101)
......@@ -187,6 +197,7 @@ class GatewayTests(unittest.TestCase):
187197 return
188198 body = json.dumps({"method": self.command, "path": self.path}).encode()
189199 self.send_response(200)
200 self.send_header('Access-Control-Allow-Origin', '*')
190201 self.send_header("Content-Length", str(len(body)))
191202 self.end_headers()
192203 self.wfile.write(body)
......@@ -205,8 +216,10 @@ class GatewayTests(unittest.TestCase):
205216 config = config.replace('server 127.0.0.1:8317;', 'server 127.0.0.1:' + str(backend.server_port) + ';')
206217 config = re.sub(r'{{ with nomadVar .*?}}|{{ end }}', '', config)
207218 config = config.replace('{{ .api_key.Value }}', API_KEY)
219 config = config.replace('{{ .management_key.Value }}', MANAGEMENT_KEY)
208220 config = config.replace('/tmp/', str(root) + '/').replace('listen 8080', f'listen 127.0.0.1:{self.port}')
209221 config = config.replace('ADMIN_HOST', ADMIN_HOST).replace('API_HOST', API_HOST)
222 config = config.replace('SSO_HOST', 'snowglobe.paperclover.net')
210223 self.assertNotIn('{{', config)
211224 path = root / "nginx.conf"
212225 path.write_text(config)
......@@ -266,6 +279,80 @@ class GatewayTests(unittest.TestCase):
266279 response.read()
267280 self.assertEqual(len(self.observed), count)
268281
282 def test_sso_management_key_is_injected_only_on_admin_management_paths(self):
283 for path in ['/v0/management/auth-files', '/v8/management/config', '/v8/management/config.yaml']:
284 with self.request('GET', path, {'Host': ADMIN_HOST, 'Authorization': 'Bearer stale-browser-key', 'X-Management-Key': 'stale-browser-key', 'Cookie': 'synthetic-session'}) as response:
285 self.assertEqual(response.status, 200)
286 self.assertEqual(response.getheader('Cache-Control'), 'no-store')
287 self.assertIsNone(response.getheader('Access-Control-Allow-Origin'))
288 self.assertNotIn(MANAGEMENT_KEY.encode(), response.read())
289 headers = self.observed[-1][2]
290 self.assertEqual(headers['Authorization'], 'Bearer ' + MANAGEMENT_KEY)
291 self.assertNotIn('X-Management-Key', headers)
292 self.assertNotIn('Cookie', headers)
293 for path in ['/management.html', '/v8/management-other/config']:
294 with self.request('GET', path, {'Host': ADMIN_HOST, 'Authorization': 'Bearer ' + MANAGEMENT_KEY}) as response:
295 self.assertEqual(response.status, 200)
296 response.read()
297 self.assertNotIn('Authorization', self.observed[-1][2])
298 count = len(self.observed)
299 for host in [API_HOST, 'other.example.test']:
300 with self.request('GET', '/v8/management/config', {'Host': host, 'Authorization': 'Bearer ' + API_KEY}) as response:
301 self.assertEqual(response.status, 404)
302 response.read()
303 self.assertEqual(len(self.observed), count)
304
305 def test_admin_model_list_uses_client_key_only_for_exact_read(self):
306 for path in ['/v1/models', '/v1/models?fixture=yes']:
307 with self.request('GET', path, {'Host': ADMIN_HOST, 'Authorization': 'Bearer ' + MANAGEMENT_KEY, 'Cookie': 'synthetic-session'}) as response:
308 self.assertEqual(response.status, 200)
309 self.assertNotIn(API_KEY.encode(), response.read())
310 self.assertEqual(self.observed[-1][2]['Authorization'], 'Bearer ' + API_KEY)
311 self.assertNotIn('Cookie', self.observed[-1][2])
312 for method, path in [('GET', '/v1/models/'), ('GET', '/v1/models/nearby'), ('POST', '/v1/models'), ('POST', '/v1/responses'), ('POST', '/v1/chat/completions'), ('GET', '/v1/responses')]:
313 with self.subTest(method=method, path=path), self.request(method, path, {'Host': ADMIN_HOST, 'Origin': 'https://' + ADMIN_HOST, 'Authorization': 'Bearer ' + MANAGEMENT_KEY}) as response:
314 self.assertEqual(response.status, 200)
315 response.read()
316 self.assertNotIn('Authorization', self.observed[-1][2])
317 count = len(self.observed)
318 with self.request('GET', '/v1/models') as response:
319 self.assertEqual(response.status, 401)
320 response.read()
321 self.assertEqual(len(self.observed), count)
322
323 def test_management_mutations_require_exact_admin_origin(self):
324 for method in ['POST', 'PUT', 'PATCH', 'DELETE']:
325 for origin in ['', 'null', 'https://other.example.test', 'https://' + ADMIN_HOST.replace('.', '-'), 'http://' + ADMIN_HOST, 'https://' + API_HOST]:
326 with self.subTest(method=method, origin=origin), self.request(method, '/v8/management/config', {'Host': ADMIN_HOST, **({'Origin': origin} if origin else {})}, body='{}') as response:
327 self.assertEqual(response.status, 403)
328 response.read()
329 self.assertEqual(self.observed, [])
330 for method in ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']:
331 with self.request(method, '/v8/management/config', {'Host': ADMIN_HOST, 'Origin': 'https://' + ADMIN_HOST}, body='{}' if method != 'GET' else None) as response:
332 self.assertEqual(response.status, 200)
333 response.read()
334 with self.request('GET', '/v8/management/config', {'Host': ADMIN_HOST, 'Origin': 'https://other.example.test'}) as response:
335 self.assertEqual(response.status, 403)
336 response.read()
337
338 def test_logout_uses_fixed_sso_destination(self):
339 with self.request('GET', '/sign-out?rd=https://other.example.test', {'Host': ADMIN_HOST}) as response:
340 self.assertEqual(response.status, 303)
341 self.assertEqual(response.getheader('Location'), '/snow.oauth2/sign_out?rd=https%3A%2F%2Fsnowglobe.paperclover.net%2Fsign-in')
342 response.read()
343 self.assertEqual(self.observed, [])
344
345 def test_pinned_native_panel_auth_flow_through_gateway(self):
346 if not PANEL:
347 self.skipTest('pass --panel with the pinned upstream management.html')
348 root = Path(self.temporary.name)
349 with patch.object(prepare.urllib.request, 'urlopen', return_value=io.BytesIO(PANEL.read_bytes())), patch.object(prepare.os, 'fchown'), patch.object(prepare.os, 'chown'):
350 prepare.prepare({'hostRoot': str(root), 'uid': os.getuid()})
351 panel = root / 'data/static/management.html'
352 with patch.object(prepare.urllib.request, 'urlopen', side_effect=AssertionError('unexpected download')):
353 prepare.prepare({'hostRoot': str(root), 'uid': os.getuid()})
354 subprocess.run(['node', str(SERVICE / 'panel-test.mjs'), str(panel), 'http://127.0.0.1:' + str(self.port), ADMIN_HOST], check=True, timeout=15)
355
269356 def test_browser_oauth_callback_credentials_never_reach_upstream_or_logs(self):
270357 code = 'synthetic-oauth-code-must-not-be-logged'
271358 state = 'synthetic-oauth-state-must-not-be-logged'
......@@ -286,7 +373,7 @@ class GatewayTests(unittest.TestCase):
286373 self.assertEqual(self.observed, [])
287374 payload = json.dumps({'provider': 'codex', 'redirect_url': 'http://localhost:1455/auth/callback?code=' + code + '&state=' + state}).encode()
288375 for path in paths[:2]:
289 with self.request('POST', path, {'Host': ADMIN_HOST, 'Content-Type': 'application/json'}, body=payload) as response:
376 with self.request('POST', path, {'Host': ADMIN_HOST, 'Origin': 'https://' + ADMIN_HOST, 'Content-Type': 'application/json'}, body=payload) as response:
290377 self.assertEqual(response.status, 200)
291378 response.read()
292379 self.assertEqual(self.observed[-1][3], payload)
......@@ -349,7 +436,9 @@ class GatewayTests(unittest.TestCase):
349436if __name__ == '__main__':
350437 parser = argparse.ArgumentParser()
351438 parser.add_argument('--nginx', type=Path)
439 parser.add_argument('--panel', type=Path)
352440 options, remaining = parser.parse_known_args()
353441 NGINX = str(options.nginx.resolve()) if options.nginx else None
442 PANEL = options.panel.resolve() if options.panel else None
354443 GatewayTests.__unittest_skip__ = not NGINX
355444 unittest.main(argv=[__file__, *remaining])
tools/cliproxy.md+20-9
......@@ -1,24 +1,26 @@
11# CLIProxyAPI
22
33`cliproxy.paperclover.net` is the management panel, protected by Snow's
4`infra-admin` role and CLIProxyAPI's independent management key.
4`infra-admin` role. Snow sign-in opens it automatically; nginx supplies the
5independent management key to its management endpoints on the server.
56`cliproxy-api.paperclover.net` is the client endpoint: use
67`https://cliproxy-api.paperclover.net/v1` for OpenAI-compatible clients or
78`https://cliproxy-api.paperclover.net` for Claude-compatible clients.
89
910Nomad variable `nomad/jobs/cliproxy` owns `api_key` and `management_key`.
1011Keep values in restricted private files or a password manager; do not paste them
11into chat, command arguments, or tracked configuration. The native panel asks
12for its management key once and offers **Remember password**. That stores the
13key in this browser's local storage; use it only in a trusted browser profile.
12into chat, command arguments, or tracked configuration. The management key never
13needs to enter the browser. Opening the panel clears any previously remembered
14native management password and validates access through the native config API.
15Its Logout button clears the shared forward-auth cookie and opens Snow sign-in.
1416API clients accept the separate client key through `Authorization: Bearer …`
1517or `X-Api-Key`. The gateway independently enforces this one infra-managed key,
1618even if the native panel removes its own API keys. Query-string keys are rejected.
1719
1820## Connect providers
1921
20Open the management panel, sign in through Snow, then unlock the panel with the
21management key. Its OAuth section supports **Codex** and **Claude**. Start the
22Open the management panel and sign in through Snow.
23Its OAuth section supports **Codex** and **Claude**. Start the
2224chosen provider's login and complete consent in the provider's own browser page.
2325For remote OAuth flows that finish on an unreachable `localhost` URL, copy that
2426entire callback URL into the panel's callback form. Treat the callback URL as a
......@@ -44,16 +46,25 @@ unapproved methods return 404 on the API hostname. The app listens only on
4446container loopback; nginx publishes the sole port. Both processes exit together
4547if either fails. The host-side route requires Snow for management; nginx's
4648admin-host routing does not replace that authentication boundary.
49Management writes require the exact admin origin; cross-origin reads with an
50Origin header are rejected, and upstream CORS headers are suppressed. The
51management key is added only to `/v0/management/` and `/v8/management/` paths.
52The panel's `GET /v1/models` uses the client key server-side; other client routes
53and methods receive no injected key on the admin hostname.
4754
4855The service pins CLIProxyAPI v8.0.32 and the management panel v1.26.5. Panel
4956downloads are size- and SHA-256-checked during preparation; runtime auto-update
50is disabled. Request-body logging is omitted by `commercial-mode: true` and
57is disabled. Preparation patches session restoration, removes auth-store
58persistence, permits empty-key revalidation, and redirects Logout; the resulting
59asset has its own pinned checksum. Native login still establishes authentication only after its config
60request succeeds. Request-body logging is omitted by `commercial-mode: true` and
5161`request-log: false`. Plugins, discovery, usage aggregation, and profiling start
5262disabled. The read-only image has only `/data` and a private `/tmp` writable;
5363the pinned `/data/static` subdirectory is mounted read-only separately.
5464
55Run `python3 tools/cliproxy-test.py --nginx /path/to/nginx` for bootstrap,
56rendering, pinned-asset, and actual HTTP/streaming/WebSocket boundary checks.
65Run `python3 tools/cliproxy-test.py --nginx /path/to/nginx --panel /path/to/upstream-management.html`
66with the pinned upstream v1.26.5 asset for bootstrap, rendering, pinned-asset,
67actual HTTP/streaming/WebSocket boundaries, and the native auth-store flow.
5768The test uses temporary synthetic credentials and a loopback fixture upstream.
5869Stage with the normal deployment command, verify anonymous management is routed
5970to Snow, valid/invalid client-key behavior, provider persistence on restart,