Skip to content

Commit b13a53a

Browse files
authored
fix(cli): report an edge-blocked whoami as unreachable, not a rejected credential (#10635)
* fix(cli): report an edge-blocked whoami as unreachable, not a rejected credential A proxy, VPN, or WAF answering HTML 403 in front of Sim made whoami say the key was rejected (exit 1). Non-JSON failures now carry nonJsonBody, and verifyProfile reports them as unreachable (exit 2) on both the API-key and OAuth-refresh paths. JSON 401/403 refusals are unchanged. * fix(cli): keep the non-JSON flag through the 401 and rate-limit wrappers * fix(cli): keep the plain detail for an html 5xx from the workspace read Only a non-JSON 401/403/404 means an edge refused the request; a non-JSON 5xx from Sim's own load balancer keeps its previous detail instead of pointing at the network or VPN. The 401 wrapper copies the non-JSON flag only where it builds a new error.
1 parent 5832016 commit b13a53a

4 files changed

Lines changed: 187 additions & 13 deletions

File tree

‎packages/sim-cli/src/auth/oauth-flow.ts‎

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -264,10 +264,12 @@ async function readTokens(
264264
try {
265265
body = JSON.parse(raw) as TokenResponse
266266
} catch {
267-
throw new SimApiError(
267+
const error = new SimApiError(
268268
`The authorization server answered HTTP ${response.status} with a non-JSON body.`,
269269
response.status
270270
)
271+
error.nonJsonBody = true
272+
throw error
271273
}
272274
if (!response.ok || typeof body.error === 'string') {
273275
throw new OAuthTokenError(

‎packages/sim-cli/src/commands/auth.ts‎

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -949,6 +949,24 @@ function credentialFactsFrom(response: unknown): CredentialFacts | null {
949949
/** Definitive profile refusals, including a workspace the credential cannot access. */
950950
const PROFILE_REJECTION_STATUSES = new Set([401, 403, 404])
951951

952+
/**
953+
* A failure whose body was not JSON most likely came from a proxy, VPN, or WAF in front of Sim,
954+
* so it neither accepts nor rejects the credential.
955+
*/
956+
function blockedBeforeSim(
957+
error: SimApiError,
958+
authenticated: boolean | null,
959+
facts: CredentialFacts
960+
): Verification {
961+
return {
962+
status: 'unreachable',
963+
authenticated,
964+
workspace: null,
965+
...facts,
966+
detail: `blocked before reaching Sim; check your network or VPN (${error.message})`,
967+
}
968+
}
969+
952970
/**
953971
* Exit 1 reports a definitive refusal or missing credential. Exit 2 means the
954972
* profile check could not finish: retrying or configuring a workspace may help.
@@ -1001,6 +1019,7 @@ async function verifyProfile(
10011019
} catch (error) {
10021020
if (!(error instanceof SimApiError)) throw error
10031021
if (error.status === 401 || error.status === 403) {
1022+
if (error.nonJsonBody) return blockedBeforeSim(error, authenticated, facts)
10041023
return {
10051024
status: 'rejected',
10061025
authenticated: false,
@@ -1037,6 +1056,9 @@ async function verifyProfile(
10371056
}
10381057
} catch (error) {
10391058
if (!(error instanceof SimApiError)) throw error
1059+
if (error.nonJsonBody && PROFILE_REJECTION_STATUSES.has(error.status)) {
1060+
return blockedBeforeSim(error, authenticated, facts)
1061+
}
10401062
return {
10411063
status: PROFILE_REJECTION_STATUSES.has(error.status) ? 'rejected' : 'unreachable',
10421064
authenticated: error.status === 401 ? false : authenticated,
Lines changed: 140 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,140 @@
1+
import { spawn } from 'node:child_process'
2+
import { mkdtempSync, rmSync } from 'node:fs'
3+
import { createServer, type Server } from 'node:http'
4+
import type { AddressInfo } from 'node:net'
5+
import { tmpdir } from 'node:os'
6+
import { join } from 'node:path'
7+
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, it, vi } from 'vitest'
8+
import { writeConfigProfile, writeCredentialsProfile } from '../config/profile'
9+
10+
/** The page an AWS load balancer's WAF serves when it blocks a request before it reaches Sim. */
11+
function edgeRefusal(status: number): string {
12+
return `<html>
13+
<head><title>${status}</title></head>
14+
<body>
15+
<center><h1>${status}</h1></center>
16+
<hr><center>awselb/2.0</center>
17+
</body>
18+
</html>`
19+
}
20+
21+
interface WhoamiRun {
22+
exitCode: number | null
23+
stdout: string
24+
}
25+
26+
describe('whoami behind an edge that answers HTML', () => {
27+
let server: Server
28+
let endpoint: string
29+
let dir: string
30+
/** When set, Sim answers the credential metadata read and the edge blocks only the rest. */
31+
let metaPassesEdge = false
32+
let edgeStatus = 403
33+
34+
beforeAll(async () => {
35+
server = createServer((request, response) => {
36+
if (metaPassesEdge && request.url === '/api/v2/meta') {
37+
response.writeHead(200, { 'content-type': 'application/json' })
38+
response.end(JSON.stringify({ data: { keyType: 'personal', expiresAt: null } }))
39+
return
40+
}
41+
response.writeHead(edgeStatus, { 'content-type': 'text/html', server: 'awselb/2.0' })
42+
response.end(edgeRefusal(edgeStatus))
43+
})
44+
await new Promise<void>((resolve) => server.listen(0, '127.0.0.1', resolve))
45+
endpoint = `http://127.0.0.1:${(server.address() as AddressInfo).port}`
46+
})
47+
48+
afterAll(async () => {
49+
server.closeAllConnections()
50+
await new Promise<void>((resolve) => server.close(() => resolve()))
51+
})
52+
53+
beforeEach(() => {
54+
metaPassesEdge = false
55+
edgeStatus = 403
56+
dir = mkdtempSync(join(tmpdir(), 'sim-cli-whoami-edge-'))
57+
vi.stubEnv('SIM_CONFIG_DIR', dir)
58+
})
59+
60+
afterEach(() => {
61+
rmSync(dir, { recursive: true, force: true })
62+
})
63+
64+
/** Runs `whoami --output json` against the edge; without `apiKey` it uses the stored login. */
65+
function whoami(apiKey?: string): Promise<WhoamiRun> {
66+
const env: NodeJS.ProcessEnv = {
67+
...process.env,
68+
SIM_CONFIG_DIR: dir,
69+
SIM_ENDPOINT: endpoint,
70+
SIM_WORKSPACE: 'ws_1',
71+
SIM_NO_UPDATE_CHECK: '1',
72+
SIM_CLI_TELEMETRY_DISABLED: '1',
73+
NO_PROXY: '127.0.0.1',
74+
}
75+
Reflect.deleteProperty(env, 'SIM_PROFILE')
76+
if (apiKey) env.SIM_API_KEY = apiKey
77+
else Reflect.deleteProperty(env, 'SIM_API_KEY')
78+
const entrypoint = join(import.meta.dirname, '..', 'index.ts')
79+
const child = spawn('bun', [entrypoint, '--output', 'json', 'whoami'], {
80+
env,
81+
stdio: ['ignore', 'pipe', 'pipe'],
82+
})
83+
let stdout = ''
84+
child.stdout.setEncoding('utf8').on('data', (chunk: string) => {
85+
stdout += chunk
86+
})
87+
return new Promise((resolve, reject) => {
88+
child.on('error', reject)
89+
child.on('close', (exitCode) => resolve({ exitCode, stdout }))
90+
})
91+
}
92+
93+
function expectUnreachable(run: WhoamiRun, authenticated: boolean | null = null): void {
94+
const result = JSON.parse(run.stdout)
95+
expect(result.authenticated).toBe(authenticated)
96+
expect(result.verification.status).toBe('unreachable')
97+
expect(result.verification.detail).toContain('blocked before reaching Sim')
98+
expect(run.exitCode).toBe(2)
99+
}
100+
101+
it('reports an API key the edge blocked as unreachable, not rejected', async () => {
102+
expectUnreachable(await whoami('sk-test'))
103+
}, 60_000)
104+
105+
it('reports an API key the edge answered HTML 401 as unreachable, not rejected', async () => {
106+
edgeStatus = 401
107+
expectUnreachable(await whoami('sk-test'))
108+
}, 60_000)
109+
110+
it('keeps a credential Sim accepted when the edge blocks the workspace read', async () => {
111+
metaPassesEdge = true
112+
expectUnreachable(await whoami('sk-test'), true)
113+
}, 60_000)
114+
115+
it('does not blame the network when the workspace read answers an HTML 5xx', async () => {
116+
metaPassesEdge = true
117+
edgeStatus = 502
118+
const run = await whoami('sk-test')
119+
const result = JSON.parse(run.stdout)
120+
expect(result.verification.status).toBe('unreachable')
121+
expect(result.verification.detail).not.toContain('blocked before reaching Sim')
122+
expect(run.exitCode).toBe(2)
123+
}, 60_000)
124+
125+
it('reports an OAuth refresh the edge blocked as unreachable, not rejected', async () => {
126+
writeConfigProfile('default', { endpoint })
127+
writeCredentialsProfile('default', {
128+
kind: 'oauth',
129+
oauth: {
130+
accessToken: 'expired-access',
131+
refreshToken: 'stored-refresh',
132+
expiresAt: 1,
133+
issuer: `${endpoint}/api/auth`,
134+
loginId: 'edge-test',
135+
scope: 'offline_access api:read',
136+
},
137+
})
138+
expectUnreachable(await whoami())
139+
}, 60_000)
140+
})

‎packages/sim-cli/src/http/client.ts‎

Lines changed: 22 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,12 @@ import { warnIfCredentialOverCleartext, warnIfProxyIgnored } from './environment
2121
*/
2222
export class SimApiError extends Error {
2323
retryAfterMs: number | null = null
24+
/**
25+
* The failed response's body was not JSON. Sim answers every API call in JSON, so a proxy,
26+
* VPN, or WAF in front of it most likely answered instead, and its status says nothing about
27+
* the credential.
28+
*/
29+
nonJsonBody = false
2430
constructor(
2531
message: string,
2632
readonly status: number,
@@ -179,7 +185,7 @@ function toNonJsonError(
179185

180186
const text = raw.trim()
181187
const keepSnippet = !isMarkup && text.length > 0 && text.length <= 200
182-
return new SimApiError(
188+
const error = new SimApiError(
183189
`${url} returned ${kind}, not JSON (HTTP ${status}) — check your endpoint.${
184190
keepSnippet ? ` Response: ${truncate(text, 200, '…')}` : ''
185191
}`,
@@ -189,6 +195,8 @@ function toNonJsonError(
189195
1,
190196
requestId
191197
)
198+
error.nonJsonBody = true
199+
return error
192200
}
193201

194202
/**
@@ -419,6 +427,7 @@ function rateLimitedError(error: SimApiError, resends: number): SimApiError {
419427
error.requestId
420428
)
421429
refusal.retryAfterMs = error.retryAfterMs
430+
refusal.nonJsonBody = error.nonJsonBody
422431
return refusal
423432
}
424433

@@ -809,17 +818,18 @@ export class SimClient {
809818
if (!response.ok) {
810819
const raw = await readResponseText(response)
811820
const refused = toApiError(url, response, raw)
812-
const error =
813-
response.status === 401
814-
? new SimApiError(
815-
`${refused.message} — ${this.credentialRemedy()}`,
816-
refused.status,
817-
refused.code ?? AUTH_REQUIRED_CODE,
818-
refused.details,
819-
AUTH_REQUIRED_EXIT_CODE,
820-
refused.requestId
821-
)
822-
: refused
821+
let error = refused
822+
if (response.status === 401) {
823+
error = new SimApiError(
824+
`${refused.message} — ${this.credentialRemedy()}`,
825+
refused.status,
826+
refused.code ?? AUTH_REQUIRED_CODE,
827+
refused.details,
828+
AUTH_REQUIRED_EXIT_CODE,
829+
refused.requestId
830+
)
831+
error.nonJsonBody = refused.nonJsonBody
832+
}
823833
error.retryAfterMs = parseRetryAfter(response.headers.get('retry-after'), 300_000)
824834
if (namesKeyScopeRefusal(error)) {
825835
error.message = `${error.message} — this operation does not support workspace API keys; use an OAuth login or personal API key: ${this.credentialRemedy()}`

0 commit comments

Comments
 (0)