From 37e0df5408fde20231e6a694bacc5f458946535e Mon Sep 17 00:00:00 2001 From: clover caruso Date: Sat, 17 Oct 2026 13:43:51 -0700 Subject: [PATCH] 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 --- service/cliproxy/nginx.conf | 23 +++++++ service/cliproxy/panel-test.mjs | 110 ++++++++++++++++++++++++++++++++ service/cliproxy/prepare.py | 25 +++++++- service/cliproxy/service.pkl | 2 + tools/cliproxy-test.py | 95 ++++++++++++++++++++++++++- tools/cliproxy.md | 29 ++++++--- 6 files changed, 271 insertions(+), 13 deletions(-) create mode 100644 service/cliproxy/panel-test.mjs diff --git a/service/cliproxy/nginx.conf b/service/cliproxy/nginx.conf index 6ac1195f0945c38e3dd54d33d6875a87a1e9265a..630178a8748f3e625ad4bd6f3a1a22ec50c21bd9 100644 --- a/service/cliproxy/nginx.conf +++ b/service/cliproxy/nginx.conf @@ -26,10 +26,26 @@ http { default 0; ~^(?:GET|HEAD):/(?:v0/management/oauth-callback|v8/management/oauth/callback|(?:anthropic|codex|antigravity|devin)/callback|callback)/?$ 1; } + map "$request_method:$http_origin" $admin_origin { + default 0; + "GET:" 1; + "HEAD:" 1; + "GET:https://ADMIN_HOST" 1; + "HEAD:https://ADMIN_HOST" 1; + "POST:https://ADMIN_HOST" 1; + "PUT:https://ADMIN_HOST" 1; + "PATCH:https://ADMIN_HOST" 1; + "DELETE:https://ADMIN_HOST" 1; + } {{ with nomadVar "NOMAD_VARIABLE" }} map $http_authorization $bearer_key { default 0; "Bearer {{ .api_key.Value }}" 1; } map $http_x_api_key $claude_key { default 0; "{{ .api_key.Value }}" 1; } map $client_key $upstream_authorization { default ""; 1 "Bearer {{ .api_key.Value }}"; } + map "$request_method:$uri" $admin_authorization { + default ""; + ~^[A-Z]+:/v(?:0|8)/management/ "Bearer {{ .management_key.Value }}"; + "GET:/v1/models" "Bearer {{ .api_key.Value }}"; + } {{ end }} map "$bearer_key:$claude_key" $client_key { default 1; "0:0" 0; } upstream cliproxy_backend { @@ -46,12 +62,19 @@ http { server_name ADMIN_HOST; client_max_body_size 32m; location = / { return 302 /management.html; } + location = /sign-out { return 303 /snow.oauth2/sign_out?rd=https%3A%2F%2FSSO_HOST%2Fsign-in; } location / { if ($browser_oauth_callback = 1) { return 404; } if ($arg_code != "") { return 404; } + if ($admin_origin = 0) { return 403; } proxy_pass http://cliproxy_backend; proxy_http_version 1.1; proxy_set_header Host $host; + proxy_set_header Authorization $admin_authorization; + proxy_set_header X-Management-Key ""; + proxy_set_header Cookie ""; + proxy_hide_header Access-Control-Allow-Origin; + add_header Cache-Control no-store always; proxy_buffering off; proxy_read_timeout 3600s; } diff --git a/service/cliproxy/panel-test.mjs b/service/cliproxy/panel-test.mjs new file mode 100644 index 0000000000000000000000000000000000000000..377eba99234d0348fea1a233ed54cce5461d4922 --- /dev/null +++ b/service/cliproxy/panel-test.mjs @@ -0,0 +1,110 @@ +import assert from 'node:assert/strict'; +import { readFileSync } from 'node:fs'; +import { request } from 'node:http'; +import vm from 'node:vm'; + +const [panelPath, origin, host] = process.argv.slice(2); +const panel = readFileSync(panelPath, 'utf8'); +function between(start, end) { + const offset = panel.indexOf(start); + assert(offset >= 0, 'Pinned native code entry exists'); + const limit = panel.indexOf(end, offset); + assert(limit > offset, 'Pinned native code exit exists'); + return panel.slice(offset, limit); +} +const nativeStore = between('var yc=e=>', 'function Tc()'); +const nativeStorage = 'var ' + between('_l=`enc::v1::`', 'function Al(e,t)'); +const nativeAuth = 'var Pm=null,' + between('Fm=wc()(', '));typeof window') + '));'; +const nativeRoute = between('function tse({children:e})', 'function nse()'); + +for (const [remembered, rejected] of [[false, false], [true, false], [true, true]]) { + const storage = new Map(); + const requests = []; + const effects = []; + const location = { origin, host: new URL(origin).host, assign: value => requests.push(value) }; + const localStorage = { + getItem: key => storage.get(key) ?? null, + setItem: (key, value) => storage.set(key, String(value)), + removeItem: key => storage.delete(key), + }; + let connection; + let revision = 0; + const context = vm.createContext({ + window: { location, localStorage }, localStorage, + navigator: { userAgent: 'synthetic-native-auth-test' }, + TextEncoder, TextDecoder, Uint8Array, btoa, atob, console, + y: { + useSyncExternalStore: (_, snapshot) => snapshot(), + useCallback: callback => callback, + useDebugValue() {}, + useState: value => [value, () => {}], + useEffect: callback => effects.push(callback), + }, + dr: () => ({ pathname: '/' }), + H: { jsx: (type, props) => ({ type, props }) }, + ti: 'redirect', tO: 'loading', + Bc: 'cli-proxy-auth', + tp: value => value.replace(/\/+$/, ''), + G: { + setConfig: value => { connection = value; revision++; }, + getConnectionRevision: () => revision, + }, + Vp: { getState: () => ({ + clearCache() {}, + async fetchConfig() { + assert(connection.apiBase === origin, 'Restore uses the current origin'); + assert(connection.managementKey === '', 'Browser sends no management secret'); + requests.push(connection.apiBase); + return new Promise((resolve, reject) => { + const pending = request(connection.apiBase + '/v8/management/config', { + headers: { Host: host, ...(rejected ? { 'X-Synthetic-Reject': 'yes' } : {}) }, + }, response => { + let body = ''; + response.setEncoding('utf8'); + response.on('data', chunk => { body += chunk; }); + response.on('end', () => { + if (response.statusCode !== 200) reject(Object.assign(new Error('Synthetic backend rejection'), { status: response.statusCode })); + else resolve(JSON.parse(body)); + }); + }); + pending.on('error', reject); + pending.end(); + }); + }, + }) }, + sm: { getState: () => ({ clearCache() {} }) }, + jm: { getState: () => ({ clearQuotaCache() {} }) }, + }); + vm.runInContext(nativeStore + nativeStorage, context); + if (remembered) { + 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); + } + vm.runInContext(nativeAuth + nativeRoute, context); + const auth = context.Fm; + assert(!auth.getState().isAuthenticated, 'Stored credentials do not establish authentication'); + assert(auth.getState().managementKey === '', 'Remembered password never hydrates into the native store'); + assert(auth.getState().apiBase === '', 'Remembered connection never hydrates into the native store'); + const route = vm.runInContext('tse({children:"protected"})', context); + for (const effect of effects) effect(); + assert(route.type === 'redirect' && route.props.to === '/login', 'Protected route enters the SSO restore flow'); + assert(requests.length === 0, 'Protected route never revalidates a remembered password'); + const pending = auth.getState().restoreSession(); + assert(!auth.getState().isAuthenticated, 'Authentication waits for the real config response'); + assert(localStorage.getItem('managementKey') === null, 'Legacy password is removed before the request'); + assert(localStorage.getItem('cli-proxy-auth') === null, 'Persisted password is removed before the request'); + assert(await pending === !rejected, 'Restore follows the backend result'); + assert(await auth.getState().restoreSession() === !rejected, 'Concurrent restore shares the validated result'); + assert(requests.length === 1, 'Restore validates once'); + assert(auth.getState().isAuthenticated === !rejected, 'Only the successful backend response authenticates'); + assert(auth.getState().connectionStatus === (rejected ? 'error' : 'connected'), 'Native connection status follows the backend'); + assert(auth.getState().managementKey === '', 'Native state retains no password'); + assert(!auth.getState().rememberPassword, 'Native password persistence is disabled'); + assert(localStorage.getItem('isLoggedIn') === null, 'No persisted authenticated flag is needed'); + assert(localStorage.getItem('cli-proxy-auth') === null, 'Native auth state remains transient'); + if (!rejected) assert(await auth.getState().checkAuth(), 'Native revalidation accepts SSO without a browser key'); + const logout = panel.match(/onClick:(\(\)=>window\.location\.assign\([^)]*\)),title:e\(`header\.logout`\)/); + assert(logout, 'Native logout uses the SSO exit'); + vm.runInContext('(' + logout[1] + ')()', context); + assert(requests.at(-1) === '/sign-out', 'Logout reaches the fixed server redirect'); +} +console.log('Pinned native auth store: fresh, remembered, rejected, revalidation, and logout passed'); diff --git a/service/cliproxy/prepare.py b/service/cliproxy/prepare.py index efb82d064a674f9e60ba72fc28ed14e377bae904..4133bddacfbd825a9b826c85586250f2645f306a 100644 --- a/service/cliproxy/prepare.py +++ b/service/cliproxy/prepare.py @@ -3,6 +3,7 @@ import hashlib import json import os from pathlib import Path +import re import stat import sys import tempfile @@ -12,6 +13,7 @@ import urllib.request PANEL_URL = "https://github.com/router-for-me/Cli-Proxy-API-Management-Center/releases/download/v1.26.5/management.html" PANEL_SHA256 = "57558cd023475674634a114824b014d3e5ac161f6f3791e3d86b6adab962a700" PANEL_SIZE = 3312180 +PANEL_SSO_SHA256 = "fdb185df6395bb6652af7171d7193be9a568d027d66d5cd0106b797494f5b4f0" def prepare(data): @@ -25,13 +27,34 @@ def prepare(data): metadata = panel.stat() if not stat.S_ISREG(metadata.st_mode): raise ValueError("CLIProxyAPI panel must be a regular file") - if metadata.st_size == PANEL_SIZE and hashlib.sha256(panel.read_bytes()).hexdigest() == PANEL_SHA256: + if metadata.st_size <= PANEL_SIZE and hashlib.sha256(panel.read_bytes()).hexdigest() == PANEL_SSO_SHA256: panel.chmod(0o444) return with urllib.request.urlopen(PANEL_URL, timeout=60) as response: contents = response.read(PANEL_SIZE + 1) if len(contents) != PANEL_SIZE or hashlib.sha256(contents).hexdigest() != PANEL_SHA256: raise ValueError("CLIProxyAPI management panel failed checksum verification") + contents, count = re.subn( + rb"restoreSession:\(\)=>Pm\|\|\(Pm=\(async\(\)=>\{.*?\}\)\(\),Pm\),login:async", + 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', + contents, + ) + if count != 1: + raise ValueError("CLIProxyAPI session restoration seam changed") + for before, after in [ + (b'Fm=wc()(Xc(', b'Fm=wc()('), + (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})}));', + b'}));'), + (b'checkAuth:async()=>{let{managementKey:n,apiBase:r}=t();if(!n||!r)return!1;', + b'checkAuth:async()=>{let{managementKey:n,apiBase:r}=t();if(!r)return!1;'), + (b'onClick:r,title:e(`header.logout`)', + b'onClick:()=>window.location.assign(`/sign-out`),title:e(`header.logout`)'), + ]: + if contents.count(before) != 1: + raise ValueError("CLIProxyAPI management panel authentication seam changed") + contents = contents.replace(before, after) + if hashlib.sha256(contents).hexdigest() != PANEL_SSO_SHA256: + raise ValueError("CLIProxyAPI SSO panel failed checksum verification") with tempfile.NamedTemporaryFile(dir=static, prefix=".panel-", delete=False) as file: pending = Path(file.name) try: diff --git a/service/cliproxy/service.pkl b/service/cliproxy/service.pkl index a1af0a6d95cf36292347f6024b04c49e64c6ee2a..eba3cdd94a1d627dc4d7051b4e06585c800c49ae 100644 --- a/service/cliproxy/service.pkl +++ b/service/cliproxy/service.pkl @@ -1,6 +1,7 @@ amends "../../config/Service.pkl" import "../../config/site.pkl" as site +import "../../config/OpenID.pkl" as sso name = "CLIProxyAPI" tagline = "Codex and Claude API access" @@ -55,5 +56,6 @@ container { .replaceAll("NOMAD_VARIABLE", "nomad/jobs/\(module.id)") .replaceAll("ADMIN_HOST", module.container.http.hostname!!) .replaceAll("API_HOST", module.container.http.plainHostnames[0]) + .replaceAll("SSO_HOST", sso.hostname) } } diff --git a/tools/cliproxy-test.py b/tools/cliproxy-test.py index d20c8cd31f6fc65eb960c8d11b26674de2155bbf..e59559fe7a7707206e365aeb0baa8a4f3db20e53 100644 --- a/tools/cliproxy-test.py +++ b/tools/cliproxy-test.py @@ -27,6 +27,7 @@ spec = importlib.util.spec_from_file_location("cliproxy_prepare", SERVICE / "pre prepare = importlib.util.module_from_spec(spec) spec.loader.exec_module(prepare) NGINX = None +PANEL = None API_KEY = "a1" * 32 MANAGEMENT_KEY = "b2" * 32 ADMIN_HOST = "cliproxy-preview-12345678.paperclover.net" @@ -132,7 +133,7 @@ class ServiceTests(unittest.TestCase): panel = static / "management.html" contents = b"pinned synthetic panel" panel.write_bytes(contents) - 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")): + with patch.object(prepare, "PANEL_SSO_SHA256", hashlib.sha256(contents).hexdigest()), patch.object(prepare.urllib.request, "urlopen", side_effect=AssertionError("unexpected download")): prepare.prepare({"hostRoot": str(root), "uid": os.getuid()}) self.assertEqual(panel.read_bytes(), contents) @@ -144,7 +145,7 @@ class GatewayTests(unittest.TestCase): self.addCleanup(self.temporary.cleanup) root = Path(self.temporary.name) self.observed = [] - self.secret_markers = [API_KEY] + self.secret_markers = [API_KEY, MANAGEMENT_KEY] observed = self.observed class Backend(BaseHTTPRequestHandler): @@ -156,8 +157,17 @@ class GatewayTests(unittest.TestCase): def do_POST(self): self.respond() + do_PUT = do_POST + do_PATCH = do_POST + do_DELETE = do_POST + def respond(self): observed.append((self.command, self.path, dict(self.headers), self.rfile.read(int(self.headers.get('Content-Length', '0'))))) + if self.path == '/v8/management/config' and (self.headers.get('Authorization') != 'Bearer ' + MANAGEMENT_KEY or self.headers.get('X-Synthetic-Reject')): + self.send_response(401) + self.send_header('Content-Length', '0') + self.end_headers() + return if self.headers.get("Upgrade", "").lower() == "websocket": accept = base64.b64encode(hashlib.sha1((self.headers['Sec-WebSocket-Key'] + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11').encode()).digest()).decode() self.send_response(101) @@ -187,6 +197,7 @@ class GatewayTests(unittest.TestCase): return body = json.dumps({"method": self.command, "path": self.path}).encode() self.send_response(200) + self.send_header('Access-Control-Allow-Origin', '*') self.send_header("Content-Length", str(len(body))) self.end_headers() self.wfile.write(body) @@ -205,8 +216,10 @@ class GatewayTests(unittest.TestCase): config = config.replace('server 127.0.0.1:8317;', 'server 127.0.0.1:' + str(backend.server_port) + ';') config = re.sub(r'{{ with nomadVar .*?}}|{{ end }}', '', config) config = config.replace('{{ .api_key.Value }}', API_KEY) + config = config.replace('{{ .management_key.Value }}', MANAGEMENT_KEY) config = config.replace('/tmp/', str(root) + '/').replace('listen 8080', f'listen 127.0.0.1:{self.port}') config = config.replace('ADMIN_HOST', ADMIN_HOST).replace('API_HOST', API_HOST) + config = config.replace('SSO_HOST', 'snowglobe.paperclover.net') self.assertNotIn('{{', config) path = root / "nginx.conf" path.write_text(config) @@ -266,6 +279,80 @@ class GatewayTests(unittest.TestCase): response.read() self.assertEqual(len(self.observed), count) + def test_sso_management_key_is_injected_only_on_admin_management_paths(self): + for path in ['/v0/management/auth-files', '/v8/management/config', '/v8/management/config.yaml']: + with self.request('GET', path, {'Host': ADMIN_HOST, 'Authorization': 'Bearer stale-browser-key', 'X-Management-Key': 'stale-browser-key', 'Cookie': 'synthetic-session'}) as response: + self.assertEqual(response.status, 200) + self.assertEqual(response.getheader('Cache-Control'), 'no-store') + self.assertIsNone(response.getheader('Access-Control-Allow-Origin')) + self.assertNotIn(MANAGEMENT_KEY.encode(), response.read()) + headers = self.observed[-1][2] + self.assertEqual(headers['Authorization'], 'Bearer ' + MANAGEMENT_KEY) + self.assertNotIn('X-Management-Key', headers) + self.assertNotIn('Cookie', headers) + for path in ['/management.html', '/v8/management-other/config']: + with self.request('GET', path, {'Host': ADMIN_HOST, 'Authorization': 'Bearer ' + MANAGEMENT_KEY}) as response: + self.assertEqual(response.status, 200) + response.read() + self.assertNotIn('Authorization', self.observed[-1][2]) + count = len(self.observed) + for host in [API_HOST, 'other.example.test']: + with self.request('GET', '/v8/management/config', {'Host': host, 'Authorization': 'Bearer ' + API_KEY}) as response: + self.assertEqual(response.status, 404) + response.read() + self.assertEqual(len(self.observed), count) + + def test_admin_model_list_uses_client_key_only_for_exact_read(self): + for path in ['/v1/models', '/v1/models?fixture=yes']: + with self.request('GET', path, {'Host': ADMIN_HOST, 'Authorization': 'Bearer ' + MANAGEMENT_KEY, 'Cookie': 'synthetic-session'}) as response: + self.assertEqual(response.status, 200) + self.assertNotIn(API_KEY.encode(), response.read()) + self.assertEqual(self.observed[-1][2]['Authorization'], 'Bearer ' + API_KEY) + self.assertNotIn('Cookie', self.observed[-1][2]) + for method, path in [('GET', '/v1/models/'), ('GET', '/v1/models/nearby'), ('POST', '/v1/models'), ('POST', '/v1/responses'), ('POST', '/v1/chat/completions'), ('GET', '/v1/responses')]: + with self.subTest(method=method, path=path), self.request(method, path, {'Host': ADMIN_HOST, 'Origin': 'https://' + ADMIN_HOST, 'Authorization': 'Bearer ' + MANAGEMENT_KEY}) as response: + self.assertEqual(response.status, 200) + response.read() + self.assertNotIn('Authorization', self.observed[-1][2]) + count = len(self.observed) + with self.request('GET', '/v1/models') as response: + self.assertEqual(response.status, 401) + response.read() + self.assertEqual(len(self.observed), count) + + def test_management_mutations_require_exact_admin_origin(self): + for method in ['POST', 'PUT', 'PATCH', 'DELETE']: + for origin in ['', 'null', 'https://other.example.test', 'https://' + ADMIN_HOST.replace('.', '-'), 'http://' + ADMIN_HOST, 'https://' + API_HOST]: + with self.subTest(method=method, origin=origin), self.request(method, '/v8/management/config', {'Host': ADMIN_HOST, **({'Origin': origin} if origin else {})}, body='{}') as response: + self.assertEqual(response.status, 403) + response.read() + self.assertEqual(self.observed, []) + for method in ['GET', 'POST', 'PUT', 'PATCH', 'DELETE']: + with self.request(method, '/v8/management/config', {'Host': ADMIN_HOST, 'Origin': 'https://' + ADMIN_HOST}, body='{}' if method != 'GET' else None) as response: + self.assertEqual(response.status, 200) + response.read() + with self.request('GET', '/v8/management/config', {'Host': ADMIN_HOST, 'Origin': 'https://other.example.test'}) as response: + self.assertEqual(response.status, 403) + response.read() + + def test_logout_uses_fixed_sso_destination(self): + with self.request('GET', '/sign-out?rd=https://other.example.test', {'Host': ADMIN_HOST}) as response: + self.assertEqual(response.status, 303) + self.assertEqual(response.getheader('Location'), '/snow.oauth2/sign_out?rd=https%3A%2F%2Fsnowglobe.paperclover.net%2Fsign-in') + response.read() + self.assertEqual(self.observed, []) + + def test_pinned_native_panel_auth_flow_through_gateway(self): + if not PANEL: + self.skipTest('pass --panel with the pinned upstream management.html') + root = Path(self.temporary.name) + with patch.object(prepare.urllib.request, 'urlopen', return_value=io.BytesIO(PANEL.read_bytes())), patch.object(prepare.os, 'fchown'), patch.object(prepare.os, 'chown'): + prepare.prepare({'hostRoot': str(root), 'uid': os.getuid()}) + panel = root / 'data/static/management.html' + with patch.object(prepare.urllib.request, 'urlopen', side_effect=AssertionError('unexpected download')): + prepare.prepare({'hostRoot': str(root), 'uid': os.getuid()}) + subprocess.run(['node', str(SERVICE / 'panel-test.mjs'), str(panel), 'http://127.0.0.1:' + str(self.port), ADMIN_HOST], check=True, timeout=15) + def test_browser_oauth_callback_credentials_never_reach_upstream_or_logs(self): code = 'synthetic-oauth-code-must-not-be-logged' state = 'synthetic-oauth-state-must-not-be-logged' @@ -286,7 +373,7 @@ class GatewayTests(unittest.TestCase): self.assertEqual(self.observed, []) payload = json.dumps({'provider': 'codex', 'redirect_url': 'http://localhost:1455/auth/callback?code=' + code + '&state=' + state}).encode() for path in paths[:2]: - with self.request('POST', path, {'Host': ADMIN_HOST, 'Content-Type': 'application/json'}, body=payload) as response: + with self.request('POST', path, {'Host': ADMIN_HOST, 'Origin': 'https://' + ADMIN_HOST, 'Content-Type': 'application/json'}, body=payload) as response: self.assertEqual(response.status, 200) response.read() self.assertEqual(self.observed[-1][3], payload) @@ -349,7 +436,9 @@ class GatewayTests(unittest.TestCase): if __name__ == '__main__': parser = argparse.ArgumentParser() parser.add_argument('--nginx', type=Path) + parser.add_argument('--panel', type=Path) options, remaining = parser.parse_known_args() NGINX = str(options.nginx.resolve()) if options.nginx else None + PANEL = options.panel.resolve() if options.panel else None GatewayTests.__unittest_skip__ = not NGINX unittest.main(argv=[__file__, *remaining]) diff --git a/tools/cliproxy.md b/tools/cliproxy.md index 0763db9d4687b2c88a60e5f14e4dc4915f1d5a44..755e175a3332c6ded7a17a6666cf48e29d634352 100644 --- a/tools/cliproxy.md +++ b/tools/cliproxy.md @@ -1,24 +1,26 @@ # CLIProxyAPI `cliproxy.paperclover.net` is the management panel, protected by Snow's -`infra-admin` role and CLIProxyAPI's independent management key. +`infra-admin` role. Snow sign-in opens it automatically; nginx supplies the +independent management key to its management endpoints on the server. `cliproxy-api.paperclover.net` is the client endpoint: use `https://cliproxy-api.paperclover.net/v1` for OpenAI-compatible clients or `https://cliproxy-api.paperclover.net` for Claude-compatible clients. Nomad variable `nomad/jobs/cliproxy` owns `api_key` and `management_key`. Keep values in restricted private files or a password manager; do not paste them -into chat, command arguments, or tracked configuration. The native panel asks -for its management key once and offers **Remember password**. That stores the -key in this browser's local storage; use it only in a trusted browser profile. +into chat, command arguments, or tracked configuration. The management key never +needs to enter the browser. Opening the panel clears any previously remembered +native management password and validates access through the native config API. +Its Logout button clears the shared forward-auth cookie and opens Snow sign-in. API clients accept the separate client key through `Authorization: Bearer …` or `X-Api-Key`. The gateway independently enforces this one infra-managed key, even if the native panel removes its own API keys. Query-string keys are rejected. ## Connect providers -Open the management panel, sign in through Snow, then unlock the panel with the -management key. Its OAuth section supports **Codex** and **Claude**. Start the +Open the management panel and sign in through Snow. +Its OAuth section supports **Codex** and **Claude**. Start the chosen provider's login and complete consent in the provider's own browser page. For remote OAuth flows that finish on an unreachable `localhost` URL, copy that entire 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 container loopback; nginx publishes the sole port. Both processes exit together if either fails. The host-side route requires Snow for management; nginx's admin-host routing does not replace that authentication boundary. +Management writes require the exact admin origin; cross-origin reads with an +Origin header are rejected, and upstream CORS headers are suppressed. The +management key is added only to `/v0/management/` and `/v8/management/` paths. +The panel's `GET /v1/models` uses the client key server-side; other client routes +and methods receive no injected key on the admin hostname. The service pins CLIProxyAPI v8.0.32 and the management panel v1.26.5. Panel downloads are size- and SHA-256-checked during preparation; runtime auto-update -is disabled. Request-body logging is omitted by `commercial-mode: true` and +is disabled. Preparation patches session restoration, removes auth-store +persistence, permits empty-key revalidation, and redirects Logout; the resulting +asset has its own pinned checksum. Native login still establishes authentication only after its config +request succeeds. Request-body logging is omitted by `commercial-mode: true` and `request-log: false`. Plugins, discovery, usage aggregation, and profiling start disabled. The read-only image has only `/data` and a private `/tmp` writable; the pinned `/data/static` subdirectory is mounted read-only separately. -Run `python3 tools/cliproxy-test.py --nginx /path/to/nginx` for bootstrap, -rendering, pinned-asset, and actual HTTP/streaming/WebSocket boundary checks. +Run `python3 tools/cliproxy-test.py --nginx /path/to/nginx --panel /path/to/upstream-management.html` +with the pinned upstream v1.26.5 asset for bootstrap, rendering, pinned-asset, +actual HTTP/streaming/WebSocket boundaries, and the native auth-store flow. The test uses temporary synthetic credentials and a loopback fixture upstream. Stage with the normal deployment command, verify anonymous management is routed to Snow, valid/invalid client-key behavior, provider persistence on restart, -- 2.54.1