| author | |
| committer | |
| log | 37e0df5408fde20231e6a694bacc5f458946535e |
| tree | 519073da5ce32a8370f837c4603f4788eabd5a28 |
| parent | 2532a0bae3c550f509e7d8945df1357b8639ef01 |
| signature | Signed by SSH key SHA256:52mNGHRsVFBDED9IAX5pe+LRWUefqTbxEReunq21QvU |
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-sol6 files changed, 271 insertions(+), 13 deletions(-)
service/cliproxy/nginx.conf+23| ... | @@ -26,10 +26,26 @@ http { | ... | @@ -26,10 +26,26 @@ http { |
| 26 | default 0; | 26 | default 0; |
| 27 | ~^(?:GET|HEAD):/(?:v0/management/oauth-callback|v8/management/oauth/callback|(?:anthropic|codex|antigravity|devin)/callback|callback)/?$ 1; | 27 | ~^(?:GET|HEAD):/(?:v0/management/oauth-callback|v8/management/oauth/callback|(?:anthropic|codex|antigravity|devin)/callback|callback)/?$ 1; |
| 28 | } | 28 | } |
| 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 | } | ||
| 29 | {{ with nomadVar "NOMAD_VARIABLE" }} | 40 | {{ with nomadVar "NOMAD_VARIABLE" }} |
| 30 | map $http_authorization $bearer_key { default 0; "Bearer {{ .api_key.Value }}" 1; } | 41 | map $http_authorization $bearer_key { default 0; "Bearer {{ .api_key.Value }}" 1; } |
| 31 | map $http_x_api_key $claude_key { default 0; "{{ .api_key.Value }}" 1; } | 42 | map $http_x_api_key $claude_key { default 0; "{{ .api_key.Value }}" 1; } |
| 32 | map $client_key $upstream_authorization { default ""; 1 "Bearer {{ .api_key.Value }}"; } | 43 | 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 | } | ||
| 33 | {{ end }} | 49 | {{ end }} |
| 34 | map "$bearer_key:$claude_key" $client_key { default 1; "0:0" 0; } | 50 | map "$bearer_key:$claude_key" $client_key { default 1; "0:0" 0; } |
| 35 | upstream cliproxy_backend { | 51 | upstream cliproxy_backend { |
| ... | @@ -46,12 +62,19 @@ http { | ... | @@ -46,12 +62,19 @@ http { |
| 46 | server_name ADMIN_HOST; | 62 | server_name ADMIN_HOST; |
| 47 | client_max_body_size 32m; | 63 | client_max_body_size 32m; |
| 48 | location = / { return 302 /management.html; } | 64 | location = / { return 302 /management.html; } |
| 65 | location = /sign-out { return 303 /snow.oauth2/sign_out?rd=https%3A%2F%2FSSO_HOST%2Fsign-in; } | ||
| 49 | location / { | 66 | location / { |
| 50 | if ($browser_oauth_callback = 1) { return 404; } | 67 | if ($browser_oauth_callback = 1) { return 404; } |
| 51 | if ($arg_code != "") { return 404; } | 68 | if ($arg_code != "") { return 404; } |
| 69 | if ($admin_origin = 0) { return 403; } | ||
| 52 | proxy_pass http://cliproxy_backend; | 70 | proxy_pass http://cliproxy_backend; |
| 53 | proxy_http_version 1.1; | 71 | proxy_http_version 1.1; |
| 54 | proxy_set_header Host $host; | 72 | 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; | ||
| 55 | proxy_buffering off; | 78 | proxy_buffering off; |
| 56 | proxy_read_timeout 3600s; | 79 | proxy_read_timeout 3600s; |
| 57 | } | 80 | } |
service/cliproxy/panel-test.mjs created+110| ... | @@ -0,0 +1,110 @@ | ||
| 1 | import assert from 'node:assert/strict'; | ||
| 2 | import { readFileSync } from 'node:fs'; | ||
| 3 | import { request } from 'node:http'; | ||
| 4 | import vm from 'node:vm'; | ||
| 5 | |||
| 6 | const [panelPath, origin, host] = process.argv.slice(2); | ||
| 7 | const panel = readFileSync(panelPath, 'utf8'); | ||
| 8 | function 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 | } | ||
| 15 | const nativeStore = between('var yc=e=>', 'function Tc()'); | ||
| 16 | const nativeStorage = 'var ' + between('_l=`enc::v1::`', 'function Al(e,t)'); | ||
| 17 | const nativeAuth = 'var Pm=null,' + between('Fm=wc()(', '));typeof window') + '));'; | ||
| 18 | const nativeRoute = between('function tse({children:e})', 'function nse()'); | ||
| 19 | |||
| 20 | for (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 | } | ||
| 110 | console.log('Pinned native auth store: fresh, remembered, rejected, revalidation, and logout passed'); | ||
service/cliproxy/prepare.py+24-1| ... | @@ -3,6 +3,7 @@ import hashlib | ... | @@ -3,6 +3,7 @@ import hashlib |
| 3 | import json | 3 | import json |
| 4 | import os | 4 | import os |
| 5 | from pathlib import Path | 5 | from pathlib import Path |
| 6 | import re | ||
| 6 | import stat | 7 | import stat |
| 7 | import sys | 8 | import sys |
| 8 | import tempfile | 9 | import tempfile |
| ... | @@ -12,6 +13,7 @@ import urllib.request | ... | @@ -12,6 +13,7 @@ import urllib.request |
| 12 | PANEL_URL = "https://github.com/router-for-me/Cli-Proxy-API-Management-Center/releases/download/v1.26.5/management.html" | 13 | PANEL_URL = "https://github.com/router-for-me/Cli-Proxy-API-Management-Center/releases/download/v1.26.5/management.html" |
| 13 | PANEL_SHA256 = "57558cd023475674634a114824b014d3e5ac161f6f3791e3d86b6adab962a700" | 14 | PANEL_SHA256 = "57558cd023475674634a114824b014d3e5ac161f6f3791e3d86b6adab962a700" |
| 14 | PANEL_SIZE = 3312180 | 15 | PANEL_SIZE = 3312180 |
| 16 | PANEL_SSO_SHA256 = "fdb185df6395bb6652af7171d7193be9a568d027d66d5cd0106b797494f5b4f0" | ||
| 15 | 17 | ||
| 16 | 18 | ||
| 17 | def prepare(data): | 19 | def prepare(data): |
| ... | @@ -25,13 +27,34 @@ def prepare(data): | ... | @@ -25,13 +27,34 @@ def prepare(data): |
| 25 | metadata = panel.stat() | 27 | metadata = panel.stat() |
| 26 | if not stat.S_ISREG(metadata.st_mode): | 28 | if not stat.S_ISREG(metadata.st_mode): |
| 27 | raise ValueError("CLIProxyAPI panel must be a regular file") | 29 | 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: |
| 29 | panel.chmod(0o444) | 31 | panel.chmod(0o444) |
| 30 | return | 32 | return |
| 31 | with urllib.request.urlopen(PANEL_URL, timeout=60) as response: | 33 | with urllib.request.urlopen(PANEL_URL, timeout=60) as response: |
| 32 | contents = response.read(PANEL_SIZE + 1) | 34 | contents = response.read(PANEL_SIZE + 1) |
| 33 | if len(contents) != PANEL_SIZE or hashlib.sha256(contents).hexdigest() != PANEL_SHA256: | 35 | if len(contents) != PANEL_SIZE or hashlib.sha256(contents).hexdigest() != PANEL_SHA256: |
| 34 | raise ValueError("CLIProxyAPI management panel failed checksum verification") | 36 | 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") | ||
| 35 | with tempfile.NamedTemporaryFile(dir=static, prefix=".panel-", delete=False) as file: | 58 | with tempfile.NamedTemporaryFile(dir=static, prefix=".panel-", delete=False) as file: |
| 36 | pending = Path(file.name) | 59 | pending = Path(file.name) |
| 37 | try: | 60 | try: |
service/cliproxy/service.pkl+2| ... | @@ -1,6 +1,7 @@ | ... | @@ -1,6 +1,7 @@ |
| 1 | amends "../../config/Service.pkl" | 1 | amends "../../config/Service.pkl" |
| 2 | 2 | ||
| 3 | import "../../config/site.pkl" as site | 3 | import "../../config/site.pkl" as site |
| 4 | import "../../config/OpenID.pkl" as sso | ||
| 4 | 5 | ||
| 5 | name = "CLIProxyAPI" | 6 | name = "CLIProxyAPI" |
| 6 | tagline = "Codex and Claude API access" | 7 | tagline = "Codex and Claude API access" |
| ... | @@ -55,5 +56,6 @@ container { | ... | @@ -55,5 +56,6 @@ container { |
| 55 | .replaceAll("NOMAD_VARIABLE", "nomad/jobs/\(module.id)") | 56 | .replaceAll("NOMAD_VARIABLE", "nomad/jobs/\(module.id)") |
| 56 | .replaceAll("ADMIN_HOST", module.container.http.hostname!!) | 57 | .replaceAll("ADMIN_HOST", module.container.http.hostname!!) |
| 57 | .replaceAll("API_HOST", module.container.http.plainHostnames[0]) | 58 | .replaceAll("API_HOST", module.container.http.plainHostnames[0]) |
| 59 | .replaceAll("SSO_HOST", sso.hostname) | ||
| 58 | } | 60 | } |
| 59 | } | 61 | } |
tools/cliproxy-test.py+92-3| ... | @@ -27,6 +27,7 @@ spec = importlib.util.spec_from_file_location("cliproxy_prepare", SERVICE / "pre | ... | @@ -27,6 +27,7 @@ spec = importlib.util.spec_from_file_location("cliproxy_prepare", SERVICE / "pre |
| 27 | prepare = importlib.util.module_from_spec(spec) | 27 | prepare = importlib.util.module_from_spec(spec) |
| 28 | spec.loader.exec_module(prepare) | 28 | spec.loader.exec_module(prepare) |
| 29 | NGINX = None | 29 | NGINX = None |
| 30 | PANEL = None | ||
| 30 | API_KEY = "a1" * 32 | 31 | API_KEY = "a1" * 32 |
| 31 | MANAGEMENT_KEY = "b2" * 32 | 32 | MANAGEMENT_KEY = "b2" * 32 |
| 32 | ADMIN_HOST = "cliproxy-preview-12345678.paperclover.net" | 33 | ADMIN_HOST = "cliproxy-preview-12345678.paperclover.net" |
| ... | @@ -132,7 +133,7 @@ class ServiceTests(unittest.TestCase): | ... | @@ -132,7 +133,7 @@ class ServiceTests(unittest.TestCase): |
| 132 | panel = static / "management.html" | 133 | panel = static / "management.html" |
| 133 | contents = b"pinned synthetic panel" | 134 | contents = b"pinned synthetic panel" |
| 134 | panel.write_bytes(contents) | 135 | 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")): |
| 136 | prepare.prepare({"hostRoot": str(root), "uid": os.getuid()}) | 137 | prepare.prepare({"hostRoot": str(root), "uid": os.getuid()}) |
| 137 | self.assertEqual(panel.read_bytes(), contents) | 138 | self.assertEqual(panel.read_bytes(), contents) |
| 138 | 139 | ||
| ... | @@ -144,7 +145,7 @@ class GatewayTests(unittest.TestCase): | ... | @@ -144,7 +145,7 @@ class GatewayTests(unittest.TestCase): |
| 144 | self.addCleanup(self.temporary.cleanup) | 145 | self.addCleanup(self.temporary.cleanup) |
| 145 | root = Path(self.temporary.name) | 146 | root = Path(self.temporary.name) |
| 146 | self.observed = [] | 147 | self.observed = [] |
| 147 | self.secret_markers = [API_KEY] | 148 | self.secret_markers = [API_KEY, MANAGEMENT_KEY] |
| 148 | observed = self.observed | 149 | observed = self.observed |
| 149 | 150 | ||
| 150 | class Backend(BaseHTTPRequestHandler): | 151 | class Backend(BaseHTTPRequestHandler): |
| ... | @@ -156,8 +157,17 @@ class GatewayTests(unittest.TestCase): | ... | @@ -156,8 +157,17 @@ class GatewayTests(unittest.TestCase): |
| 156 | def do_POST(self): | 157 | def do_POST(self): |
| 157 | self.respond() | 158 | self.respond() |
| 158 | 159 | ||
| 160 | do_PUT = do_POST | ||
| 161 | do_PATCH = do_POST | ||
| 162 | do_DELETE = do_POST | ||
| 163 | |||
| 159 | def respond(self): | 164 | def respond(self): |
| 160 | observed.append((self.command, self.path, dict(self.headers), self.rfile.read(int(self.headers.get('Content-Length', '0'))))) | 165 | 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 | ||
| 161 | if self.headers.get("Upgrade", "").lower() == "websocket": | 171 | if self.headers.get("Upgrade", "").lower() == "websocket": |
| 162 | accept = base64.b64encode(hashlib.sha1((self.headers['Sec-WebSocket-Key'] + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11').encode()).digest()).decode() | 172 | accept = base64.b64encode(hashlib.sha1((self.headers['Sec-WebSocket-Key'] + '258EAFA5-E914-47DA-95CA-C5AB0DC85B11').encode()).digest()).decode() |
| 163 | self.send_response(101) | 173 | self.send_response(101) |
| ... | @@ -187,6 +197,7 @@ class GatewayTests(unittest.TestCase): | ... | @@ -187,6 +197,7 @@ class GatewayTests(unittest.TestCase): |
| 187 | return | 197 | return |
| 188 | body = json.dumps({"method": self.command, "path": self.path}).encode() | 198 | body = json.dumps({"method": self.command, "path": self.path}).encode() |
| 189 | self.send_response(200) | 199 | self.send_response(200) |
| 200 | self.send_header('Access-Control-Allow-Origin', '*') | ||
| 190 | self.send_header("Content-Length", str(len(body))) | 201 | self.send_header("Content-Length", str(len(body))) |
| 191 | self.end_headers() | 202 | self.end_headers() |
| 192 | self.wfile.write(body) | 203 | self.wfile.write(body) |
| ... | @@ -205,8 +216,10 @@ class GatewayTests(unittest.TestCase): | ... | @@ -205,8 +216,10 @@ class GatewayTests(unittest.TestCase): |
| 205 | config = config.replace('server 127.0.0.1:8317;', 'server 127.0.0.1:' + str(backend.server_port) + ';') | 216 | config = config.replace('server 127.0.0.1:8317;', 'server 127.0.0.1:' + str(backend.server_port) + ';') |
| 206 | config = re.sub(r'{{ with nomadVar .*?}}|{{ end }}', '', config) | 217 | config = re.sub(r'{{ with nomadVar .*?}}|{{ end }}', '', config) |
| 207 | config = config.replace('{{ .api_key.Value }}', API_KEY) | 218 | config = config.replace('{{ .api_key.Value }}', API_KEY) |
| 219 | config = config.replace('{{ .management_key.Value }}', MANAGEMENT_KEY) | ||
| 208 | config = config.replace('/tmp/', str(root) + '/').replace('listen 8080', f'listen 127.0.0.1:{self.port}') | 220 | config = config.replace('/tmp/', str(root) + '/').replace('listen 8080', f'listen 127.0.0.1:{self.port}') |
| 209 | config = config.replace('ADMIN_HOST', ADMIN_HOST).replace('API_HOST', API_HOST) | 221 | config = config.replace('ADMIN_HOST', ADMIN_HOST).replace('API_HOST', API_HOST) |
| 222 | config = config.replace('SSO_HOST', 'snowglobe.paperclover.net') | ||
| 210 | self.assertNotIn('{{', config) | 223 | self.assertNotIn('{{', config) |
| 211 | path = root / "nginx.conf" | 224 | path = root / "nginx.conf" |
| 212 | path.write_text(config) | 225 | path.write_text(config) |
| ... | @@ -266,6 +279,80 @@ class GatewayTests(unittest.TestCase): | ... | @@ -266,6 +279,80 @@ class GatewayTests(unittest.TestCase): |
| 266 | response.read() | 279 | response.read() |
| 267 | self.assertEqual(len(self.observed), count) | 280 | self.assertEqual(len(self.observed), count) |
| 268 | 281 | ||
| 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 | |||
| 269 | def test_browser_oauth_callback_credentials_never_reach_upstream_or_logs(self): | 356 | def test_browser_oauth_callback_credentials_never_reach_upstream_or_logs(self): |
| 270 | code = 'synthetic-oauth-code-must-not-be-logged' | 357 | code = 'synthetic-oauth-code-must-not-be-logged' |
| 271 | state = 'synthetic-oauth-state-must-not-be-logged' | 358 | state = 'synthetic-oauth-state-must-not-be-logged' |
| ... | @@ -286,7 +373,7 @@ class GatewayTests(unittest.TestCase): | ... | @@ -286,7 +373,7 @@ class GatewayTests(unittest.TestCase): |
| 286 | self.assertEqual(self.observed, []) | 373 | self.assertEqual(self.observed, []) |
| 287 | payload = json.dumps({'provider': 'codex', 'redirect_url': 'http://localhost:1455/auth/callback?code=' + code + '&state=' + state}).encode() | 374 | payload = json.dumps({'provider': 'codex', 'redirect_url': 'http://localhost:1455/auth/callback?code=' + code + '&state=' + state}).encode() |
| 288 | for path in paths[:2]: | 375 | 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: |
| 290 | self.assertEqual(response.status, 200) | 377 | self.assertEqual(response.status, 200) |
| 291 | response.read() | 378 | response.read() |
| 292 | self.assertEqual(self.observed[-1][3], payload) | 379 | self.assertEqual(self.observed[-1][3], payload) |
| ... | @@ -349,7 +436,9 @@ class GatewayTests(unittest.TestCase): | ... | @@ -349,7 +436,9 @@ class GatewayTests(unittest.TestCase): |
| 349 | if __name__ == '__main__': | 436 | if __name__ == '__main__': |
| 350 | parser = argparse.ArgumentParser() | 437 | parser = argparse.ArgumentParser() |
| 351 | parser.add_argument('--nginx', type=Path) | 438 | parser.add_argument('--nginx', type=Path) |
| 439 | parser.add_argument('--panel', type=Path) | ||
| 352 | options, remaining = parser.parse_known_args() | 440 | options, remaining = parser.parse_known_args() |
| 353 | NGINX = str(options.nginx.resolve()) if options.nginx else None | 441 | NGINX = str(options.nginx.resolve()) if options.nginx else None |
| 442 | PANEL = options.panel.resolve() if options.panel else None | ||
| 354 | GatewayTests.__unittest_skip__ = not NGINX | 443 | GatewayTests.__unittest_skip__ = not NGINX |
| 355 | unittest.main(argv=[__file__, *remaining]) | 444 | unittest.main(argv=[__file__, *remaining]) |
tools/cliproxy.md+20-9| ... | @@ -1,24 +1,26 @@ | ... | @@ -1,24 +1,26 @@ |
| 1 | # CLIProxyAPI | 1 | # CLIProxyAPI |
| 2 | 2 | ||
| 3 | `cliproxy.paperclover.net` is the management panel, protected by Snow's | 3 | `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 |
| 5 | independent management key to its management endpoints on the server. | ||
| 5 | `cliproxy-api.paperclover.net` is the client endpoint: use | 6 | `cliproxy-api.paperclover.net` is the client endpoint: use |
| 6 | `https://cliproxy-api.paperclover.net/v1` for OpenAI-compatible clients or | 7 | `https://cliproxy-api.paperclover.net/v1` for OpenAI-compatible clients or |
| 7 | `https://cliproxy-api.paperclover.net` for Claude-compatible clients. | 8 | `https://cliproxy-api.paperclover.net` for Claude-compatible clients. |
| 8 | 9 | ||
| 9 | Nomad variable `nomad/jobs/cliproxy` owns `api_key` and `management_key`. | 10 | Nomad variable `nomad/jobs/cliproxy` owns `api_key` and `management_key`. |
| 10 | Keep values in restricted private files or a password manager; do not paste them | 11 | Keep values in restricted private files or a password manager; do not paste them |
| 11 | into chat, command arguments, or tracked configuration. The native panel asks | 12 | into chat, command arguments, or tracked configuration. The management key never |
| 12 | for its management key once and offers **Remember password**. That stores the | 13 | needs to enter the browser. Opening the panel clears any previously remembered |
| 13 | key in this browser's local storage; use it only in a trusted browser profile. | 14 | native management password and validates access through the native config API. |
| 15 | Its Logout button clears the shared forward-auth cookie and opens Snow sign-in. | ||
| 14 | API clients accept the separate client key through `Authorization: Bearer …` | 16 | API clients accept the separate client key through `Authorization: Bearer …` |
| 15 | or `X-Api-Key`. The gateway independently enforces this one infra-managed key, | 17 | or `X-Api-Key`. The gateway independently enforces this one infra-managed key, |
| 16 | even if the native panel removes its own API keys. Query-string keys are rejected. | 18 | even if the native panel removes its own API keys. Query-string keys are rejected. |
| 17 | 19 | ||
| 18 | ## Connect providers | 20 | ## Connect providers |
| 19 | 21 | ||
| 20 | Open the management panel, sign in through Snow, then unlock the panel with the | 22 | Open the management panel and sign in through Snow. |
| 21 | management key. Its OAuth section supports **Codex** and **Claude**. Start the | 23 | Its OAuth section supports **Codex** and **Claude**. Start the |
| 22 | chosen provider's login and complete consent in the provider's own browser page. | 24 | chosen provider's login and complete consent in the provider's own browser page. |
| 23 | For remote OAuth flows that finish on an unreachable `localhost` URL, copy that | 25 | For remote OAuth flows that finish on an unreachable `localhost` URL, copy that |
| 24 | entire callback URL into the panel's callback form. Treat the callback URL as a | 26 | 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 | ... | @@ -44,16 +46,25 @@ unapproved methods return 404 on the API hostname. The app listens only on |
| 44 | container loopback; nginx publishes the sole port. Both processes exit together | 46 | container loopback; nginx publishes the sole port. Both processes exit together |
| 45 | if either fails. The host-side route requires Snow for management; nginx's | 47 | if either fails. The host-side route requires Snow for management; nginx's |
| 46 | admin-host routing does not replace that authentication boundary. | 48 | admin-host routing does not replace that authentication boundary. |
| 49 | Management writes require the exact admin origin; cross-origin reads with an | ||
| 50 | Origin header are rejected, and upstream CORS headers are suppressed. The | ||
| 51 | management key is added only to `/v0/management/` and `/v8/management/` paths. | ||
| 52 | The panel's `GET /v1/models` uses the client key server-side; other client routes | ||
| 53 | and methods receive no injected key on the admin hostname. | ||
| 47 | 54 | ||
| 48 | The service pins CLIProxyAPI v8.0.32 and the management panel v1.26.5. Panel | 55 | The service pins CLIProxyAPI v8.0.32 and the management panel v1.26.5. Panel |
| 49 | downloads are size- and SHA-256-checked during preparation; runtime auto-update | 56 | downloads are size- and SHA-256-checked during preparation; runtime auto-update |
| 50 | is disabled. Request-body logging is omitted by `commercial-mode: true` and | 57 | is disabled. Preparation patches session restoration, removes auth-store |
| 58 | persistence, permits empty-key revalidation, and redirects Logout; the resulting | ||
| 59 | asset has its own pinned checksum. Native login still establishes authentication only after its config | ||
| 60 | request succeeds. Request-body logging is omitted by `commercial-mode: true` and | ||
| 51 | `request-log: false`. Plugins, discovery, usage aggregation, and profiling start | 61 | `request-log: false`. Plugins, discovery, usage aggregation, and profiling start |
| 52 | disabled. The read-only image has only `/data` and a private `/tmp` writable; | 62 | disabled. The read-only image has only `/data` and a private `/tmp` writable; |
| 53 | the pinned `/data/static` subdirectory is mounted read-only separately. | 63 | the pinned `/data/static` subdirectory is mounted read-only separately. |
| 54 | 64 | ||
| 55 | Run `python3 tools/cliproxy-test.py --nginx /path/to/nginx` for bootstrap, | 65 | Run `python3 tools/cliproxy-test.py --nginx /path/to/nginx --panel /path/to/upstream-management.html` |
| 56 | rendering, pinned-asset, and actual HTTP/streaming/WebSocket boundary checks. | 66 | with the pinned upstream v1.26.5 asset for bootstrap, rendering, pinned-asset, |
| 67 | actual HTTP/streaming/WebSocket boundaries, and the native auth-store flow. | ||
| 57 | The test uses temporary synthetic credentials and a loopback fixture upstream. | 68 | The test uses temporary synthetic credentials and a loopback fixture upstream. |
| 58 | Stage with the normal deployment command, verify anonymous management is routed | 69 | Stage with the normal deployment command, verify anonymous management is routed |
| 59 | to Snow, valid/invalid client-key behavior, provider persistence on restart, | 70 | to Snow, valid/invalid client-key behavior, provider persistence on restart, |