Skip to content

Commit 71e3dd9

Browse files
committed
fix(self-hosting): fail-closed self-check, every database endpoint, and keep helm test pods for their logs
1 parent d5763dd commit 71e3dd9

18 files changed

Lines changed: 339 additions & 62 deletions

‎.github/workflows/helm.yml‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -193,8 +193,8 @@ jobs:
193193
run: helm test sim --namespace sim --timeout 5m
194194

195195
# After the test, so it also explains a failed probe, not only a failed
196-
# install. A failed test pod is kept (the hook deletes it only on success),
197-
# so its log says which URL refused.
196+
# install. The test pods are kept until the next helm test, so their logs
197+
# say which URL refused.
198198
- name: Diagnostics on failure
199199
if: failure()
200200
run: |

‎.github/workflows/sandbox.yml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -75,6 +75,7 @@ on:
7575
- 'apps/sim/scripts/test-sandbox-kubernetes-app-e2e.ts'
7676
# The self-check e2e-app runs through `helm test`, and its test pods.
7777
- 'apps/sim/lib/self-check/**'
78+
- 'apps/sim/lib/api/contracts/self-check.ts'
7879
- 'apps/sim/app/api/cron/self-check/**'
7980
- 'helm/sim/templates/tests/**'
8081
# The sandbox images' recipes, content-addressed tags, and verification.
@@ -217,6 +218,7 @@ jobs:
217218
- 'apps/sim/lib/execution/remote-sandbox/agent/**'
218219
- 'apps/sim/scripts/test-sandbox-kubernetes-app-e2e.ts'
219220
- 'apps/sim/lib/self-check/**'
221+
- 'apps/sim/lib/api/contracts/self-check.ts'
220222
- 'apps/sim/app/api/cron/self-check/**'
221223
- 'helm/sim/templates/tests/**'
222224
- 'apps/sandbox-agent/**'

‎apps/sim/lib/execution/remote-sandbox/kubernetes/confinement-probe.ts‎

Lines changed: 47 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,49 @@ import { SIM_RESULT_PREFIX } from '@/lib/execution/remote-sandbox'
44

55
const METADATA_ADDRESS = '169.254.169.254'
66

7+
/**
8+
* Endpoints that would hand user code node identity or cloud credentials. `headers` is a Python
9+
* expression: `aws` is the IMDSv2 token header the probe fetches first.
10+
*/
11+
const METADATA_REQUESTS = [
12+
{
13+
name: 'aws instance-id',
14+
url: `http://${METADATA_ADDRESS}/latest/meta-data/instance-id`,
15+
headers: 'aws',
16+
},
17+
{ name: 'aws user-data', url: `http://${METADATA_ADDRESS}/latest/user-data`, headers: 'aws' },
18+
{
19+
name: 'aws iam credentials',
20+
url: `http://${METADATA_ADDRESS}/latest/meta-data/iam/security-credentials/`,
21+
headers: 'aws',
22+
},
23+
{ name: 'eks pod identity', url: 'http://169.254.170.23/v1/credentials', headers: 'None' },
24+
{ name: 'ecs task credentials', url: 'http://169.254.170.2/v2/credentials', headers: 'None' },
25+
{
26+
name: 'gcp instance id',
27+
url: `http://${METADATA_ADDRESS}/computeMetadata/v1/instance/id`,
28+
headers: "{'Metadata-Flavor': 'Google'}",
29+
},
30+
{
31+
name: 'azure instance',
32+
url: `http://${METADATA_ADDRESS}/metadata/instance?api-version=2021-02-01`,
33+
headers: "{'Metadata': 'true'}",
34+
},
35+
{
36+
name: 'gcp service account token',
37+
url: `http://${METADATA_ADDRESS}/computeMetadata/v1/instance/service-accounts/default/token`,
38+
headers: "{'Metadata-Flavor': 'Google'}",
39+
},
40+
{
41+
name: 'azure managed identity token',
42+
url: `http://${METADATA_ADDRESS}/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/`,
43+
headers: "{'Metadata': 'true'}",
44+
},
45+
] as const
46+
47+
/** The metadata endpoints every probe result reports on, by name. */
48+
export const METADATA_ENDPOINT_NAMES: readonly string[] = METADATA_REQUESTS.map(({ name }) => name)
49+
750
type Target = [host: string, port: number]
851

952
interface ConfinementProbeTargets {
@@ -122,15 +165,10 @@ with ThreadPoolExecutor(max_workers=32) as pool:
122165
# runtime may answer on these addresses from inside the guest (Nitro's IMDSv2 surrogate
123166
# serves region and zone only), so these, not reachability, are the boundary.
124167
metadata_requests = {
125-
'aws instance-id': ('http://${METADATA_ADDRESS}/latest/meta-data/instance-id', aws),
126-
'aws user-data': ('http://${METADATA_ADDRESS}/latest/user-data', aws),
127-
'aws iam credentials': ('http://${METADATA_ADDRESS}/latest/meta-data/iam/security-credentials/', aws),
128-
'eks pod identity': ('http://169.254.170.23/v1/credentials', None),
129-
'ecs task credentials': ('http://169.254.170.2/v2/credentials', None),
130-
'gcp instance id': ('http://${METADATA_ADDRESS}/computeMetadata/v1/instance/id', {'Metadata-Flavor': 'Google'}),
131-
'azure instance': ('http://${METADATA_ADDRESS}/metadata/instance?api-version=2021-02-01', {'Metadata': 'true'}),
132-
'gcp service account token': ('http://${METADATA_ADDRESS}/computeMetadata/v1/instance/service-accounts/default/token', {'Metadata-Flavor': 'Google'}),
133-
'azure managed identity token': ('http://${METADATA_ADDRESS}/metadata/identity/oauth2/token?api-version=2018-02-01&resource=https://management.azure.com/', {'Metadata': 'true'}),
168+
${METADATA_REQUESTS.map(
169+
({ name, url, headers }) =>
170+
` ${JSON.stringify(name)}: (${JSON.stringify(url)}, ${headers}),`
171+
).join('\n')}
134172
}
135173
metadata_futures = {name: pool.submit(http_status, url, headers) for name, (url, headers) in metadata_requests.items()}
136174
metadata_reach = pool.submit(reach, '${METADATA_ADDRESS}', 80)

‎apps/sim/lib/self-check/confinement.test.ts‎

Lines changed: 25 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,8 @@
11
import { describe, expect, it } from 'vitest'
2-
import type { ConfinementFacts } from '@/lib/execution/remote-sandbox/kubernetes/confinement-probe'
2+
import {
3+
type ConfinementFacts,
4+
METADATA_ENDPOINT_NAMES,
5+
} from '@/lib/execution/remote-sandbox/kubernetes/confinement-probe'
36
import {
47
type ConfinementPlan,
58
evaluateConfinement,
@@ -19,6 +22,7 @@ const plan: ConfinementPlan = {
1922
{ key: REDIS, kind: 'redis' },
2023
],
2124
neighbor: NEIGHBOR,
25+
apiTargets: ['kubernetes.default.svc:443', '10.43.0.1:443'],
2226
resolveNames: ['kubernetes.default.svc', 'example.com'],
2327
}
2428

@@ -41,7 +45,9 @@ function confinedFacts(overrides: Partial<ConfinementFacts> = {}): ConfinementFa
4145
agentWithForgedToken: 401,
4246
api: { 'kubernetes.default.svc:443': 'unreachable', '10.43.0.1:443': 'unreachable' },
4347
metadata: false,
44-
metadataSecrets: { 'aws iam credentials': 'unreachable', 'gcp instance id': 'unreachable' },
48+
metadataSecrets: Object.fromEntries(
49+
METADATA_ENDPOINT_NAMES.map((name) => [name, 'unreachable'])
50+
),
4551
denied: { [APP]: false, [DATABASE]: false, [REDIS]: false, [NEIGHBOR]: false },
4652
deniedPrivate: { [APP]: true, [DATABASE]: true, [REDIS]: false, [NEIGHBOR]: true },
4753
allowed: {},
@@ -190,6 +196,23 @@ describe('judgeProbeResult', () => {
190196
})
191197
})
192198

199+
describe('judgeProbeResult fails closed', () => {
200+
it.each([
201+
['a planned lateral target', 'denied', APP],
202+
["a planned lateral target's address class", 'deniedPrivate', DATABASE],
203+
['the neighbor', 'denied', NEIGHBOR],
204+
['a planned API target', 'api', 'kubernetes.default.svc:443'],
205+
['a metadata endpoint', 'metadataSecrets', 'aws iam credentials'],
206+
['a resolved name', 'resolved', 'example.com'],
207+
] as const)('fails the sandbox check when the result omits %s', (_, field, key) => {
208+
const facts = confinedFacts()
209+
const { [key]: _omitted, ...rest } = facts[field] as Record<string, unknown>
210+
const judged = judgeProbeResult({ ...facts, [field]: rest }, plan)
211+
expect(judged.execution.status).toBe('fail')
212+
expect(judged.outcomes).toBeNull()
213+
})
214+
})
215+
193216
describe('isProbeTargetAddress', () => {
194217
it.each(['127.0.0.1', '::1', '169.254.169.254', 'fe80::1', '::ffff:127.0.0.1', '0.0.0.0'])(
195218
'drops %s, which reaches the app pod itself or its sidecar rather than a peer',

‎apps/sim/lib/self-check/confinement.ts‎

Lines changed: 23 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { isIP } from 'node:net'
22
import {
33
type ConfinementFacts,
44
isConfinementFacts,
5+
METADATA_ENDPOINT_NAMES,
56
} from '@/lib/execution/remote-sandbox/kubernetes/confinement-probe'
67
import type { CheckOutcome } from '@/lib/self-check/outcome'
78

@@ -19,6 +20,8 @@ export interface ConfinementPlan {
1920
lateral: Array<{ key: string; kind: LateralTargetKind }>
2021
/** The sibling sandbox's agent address; the app reaching it is the positive control. */
2122
neighbor: string
23+
/** The Kubernetes API endpoints the probe tried, keyed as in {@link ConfinementFacts.api}. */
24+
apiTargets: string[]
2225
/**
2326
* Names the probe resolves to show its network works, so unreachable means refused. The first
2427
* is the cluster's own; any one resolving is enough, since an operator may point sandbox DNS
@@ -129,6 +132,20 @@ export function evaluateConfinement(
129132
}
130133
}
131134

135+
/**
136+
* Whether the result reports on everything the plan asked for. The rules read a missing entry as
137+
* unreachable or unserved, so a probe that skipped a target would otherwise pass it.
138+
*/
139+
function coversPlan(facts: ConfinementFacts, plan: ConfinementPlan): boolean {
140+
const deniedKeys = [...plan.lateral.map(({ key }) => key), plan.neighbor]
141+
return (
142+
deniedKeys.every((key) => key in facts.denied && key in facts.deniedPrivate) &&
143+
plan.apiTargets.every((key) => key in facts.api) &&
144+
plan.resolveNames.every((name) => name in facts.resolved) &&
145+
METADATA_ENDPOINT_NAMES.every((name) => name in facts.metadataSecrets)
146+
)
147+
}
148+
132149
/**
133150
* Judges the probe's raw result. A result that is not the full set of facts the rules read fails
134151
* the sandbox check instead of throwing, so a changed or truncated probe never turns the
@@ -141,6 +158,12 @@ export function judgeProbeResult(
141158
if (!isConfinementFacts(value)) {
142159
return { execution: { status: 'fail', detail: 'the probe returned no result' }, outcomes: null }
143160
}
161+
if (!coversPlan(value, plan)) {
162+
return {
163+
execution: { status: 'fail', detail: 'the probe result omits a planned target' },
164+
outcomes: null,
165+
}
166+
}
144167
try {
145168
return {
146169
execution: { status: 'pass', detail: 'ran user code' },
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
import { resetEnvMock, setEnv } from '@sim/testing/mocks/env.mock'
2+
import { resetUrlsMock, urlsMockFns } from '@sim/testing/mocks/urls.mock'
3+
import { afterEach, describe, expect, it, vi } from 'vitest'
4+
import { checkRealtime, checkRedis } from '@/lib/self-check/infrastructure'
5+
6+
afterEach(() => {
7+
resetEnvMock()
8+
resetUrlsMock()
9+
})
10+
11+
describe('checkRedis', () => {
12+
it('fails when REDIS_URL is unset, since the app requires Redis', async () => {
13+
setEnv({ REDIS_URL: undefined })
14+
expect(await checkRedis()).toMatchObject({ name: 'redis', status: 'fail' })
15+
})
16+
})
17+
18+
describe('checkRealtime', () => {
19+
it('asks a SOCKET_SERVER_URL with a trailing slash for /health, not //health', async () => {
20+
urlsMockFns.mockGetSocketServerUrl.mockReturnValueOnce('http://sim-realtime:3002//')
21+
const fetch = vi.fn(async (url: string) =>
22+
url === 'http://sim-realtime:3002/health'
23+
? new Response('ok', { status: 200 })
24+
: new Response('not found', { status: 404 })
25+
)
26+
vi.stubGlobal('fetch', fetch)
27+
expect(await checkRealtime()).toMatchObject({ name: 'realtime', status: 'pass' })
28+
})
29+
})

‎apps/sim/lib/self-check/infrastructure.ts‎

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -52,15 +52,16 @@ export function checkMigrations(): Promise<SelfCheckResult> {
5252

5353
export function checkRedis(): Promise<SelfCheckResult> {
5454
return timed('redis', async () => {
55-
if (!env.REDIS_URL) return { status: 'skip', detail: 'REDIS_URL is not set' }
55+
// Redis is required: the app refuses to start without it, so an unset URL is a failure.
56+
if (!env.REDIS_URL) return { status: 'fail', detail: 'REDIS_URL is not set' }
5657
await withTimeout(getRedisClient().ping(), REDIS_TIMEOUT_MS)
5758
return { status: 'pass', detail: 'ping answered' }
5859
})
5960
}
6061

6162
export function checkRealtime(): Promise<SelfCheckResult> {
6263
return timed('realtime', async () => {
63-
const response = await fetch(`${getSocketServerUrl()}/health`, {
64+
const response = await fetch(`${getSocketServerUrl().replace(/\/+$/, '')}/health`, {
6465
signal: AbortSignal.timeout(REALTIME_TIMEOUT_MS),
6566
})
6667
await response.body?.cancel()

‎apps/sim/lib/self-check/sandbox.ts‎

Lines changed: 31 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -2,7 +2,7 @@ import { lookup } from 'node:dns/promises'
22
import { isIP } from 'node:net'
33
import { networkInterfaces } from 'node:os'
44
import { SANDBOX_AGENT_PORT } from '@sim/sandbox-agent-protocol'
5-
import { env } from '@/lib/core/config/env'
5+
import { env, envNumber } from '@/lib/core/config/env'
66
import { getSelectedSandboxProviderId } from '@/lib/core/config/env-capabilities.server'
77
import { CodeLanguage } from '@/lib/execution/languages'
88
import { executeInSandbox } from '@/lib/execution/remote-sandbox'
@@ -18,6 +18,7 @@ import {
1818
type LateralTargetKind,
1919
} from '@/lib/self-check/confinement'
2020
import { type CheckOutcome, errorCode } from '@/lib/self-check/outcome'
21+
import { DATABASE_URL_NAMES, dataStoreEndpoints } from '@/lib/self-check/targets'
2122
import type { SelfCheckName, SelfCheckResult } from '@/lib/self-check/types'
2223

2324
/** Two sandbox starts and one probe, inside the route's `maxDuration`. */
@@ -65,23 +66,32 @@ function appAddresses(): string[] {
6566
.filter(isProbeTargetAddress)
6667
}
6768

68-
/** The data store's addresses as the app resolves them, since user code runs in another namespace. */
69-
async function dataStoreTargets(url: string | undefined, defaultPort: number): Promise<Target[]> {
70-
if (!url) return []
71-
let parsed: URL
72-
try {
73-
parsed = new URL(url)
74-
} catch {
75-
return []
76-
}
77-
const host = parsed.hostname.replace(/^\[|\]$/g, '')
78-
const port = Number(parsed.port) || defaultPort
79-
if (!host) return []
80-
const addresses = isIP(host)
81-
? [host]
82-
: (await lookup(host, { all: true }).catch(() => [])).map(({ address }) => address)
83-
// A loopback or link-local address is a sidecar proxy in the app pod, not the data store.
84-
return addresses.filter(isProbeTargetAddress).map((address): Target => [address, port])
69+
/**
70+
* Every database and Redis address the app is configured with, resolved as the app resolves them
71+
* (user code runs in another namespace, where short Service names do not resolve), each once.
72+
*/
73+
async function dataStoreTargets(): Promise<Array<{ target: Target; kind: LateralTargetKind }>> {
74+
const endpoints = dataStoreEndpoints({
75+
...Object.fromEntries(DATABASE_URL_NAMES.map((name) => [name, env[name]])),
76+
REDIS_URL: env.REDIS_URL,
77+
})
78+
const resolved = await Promise.all(
79+
endpoints.map(async ({ kind, host, port }) => {
80+
const addresses = isIP(host)
81+
? [host]
82+
: (await lookup(host, { all: true }).catch(() => [])).map(({ address }) => address)
83+
// A loopback or link-local address is a sidecar proxy in the app pod, not the data store.
84+
return addresses
85+
.filter(isProbeTargetAddress)
86+
.map((address) => ({ target: [address, port] as Target, kind }))
87+
})
88+
)
89+
const seen = new Set<string>()
90+
return resolved.flat().filter(({ target }) => {
91+
if (seen.has(key(target))) return false
92+
seen.add(key(target))
93+
return true
94+
})
8595
}
8696

8797
/**
@@ -179,17 +189,10 @@ async function probe(
179189
signal: AbortSignal,
180190
elapsed: () => number
181191
): Promise<SelfCheckResult[]> {
182-
const appPort = Number(env.PORT) || DEFAULT_APP_PORT
192+
const appPort = envNumber(env.PORT, DEFAULT_APP_PORT, { min: 1, integer: true })
183193
const lateral: Array<{ target: Target; kind: LateralTargetKind }> = [
184194
...appAddresses().map((host) => ({ target: [host, appPort] as Target, kind: 'app' as const })),
185-
...(await dataStoreTargets(env.DATABASE_URL, 5432)).map((target) => ({
186-
target,
187-
kind: 'database' as const,
188-
})),
189-
...(await dataStoreTargets(env.REDIS_URL, 6379)).map((target) => ({
190-
target,
191-
kind: 'redis' as const,
192-
})),
195+
...(await dataStoreTargets()),
193196
]
194197
const neighborTarget: Target = [neighborAddress, SANDBOX_AGENT_PORT]
195198
const apiTargets: Target[] = [[CLUSTER_API_NAME, 443]]
@@ -216,6 +219,7 @@ async function probe(
216219
const plan: ConfinementPlan = {
217220
lateral: lateral.map(({ target, kind }) => ({ key: key(target), kind })),
218221
neighbor: key(neighborTarget),
222+
apiTargets: apiTargets.map(key),
219223
resolveNames: RESOLVE_NAMES,
220224
}
221225
const judged = judgeProbeResult(execution.result, plan)
Lines changed: 36 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,36 @@
1+
import { describe, expect, it } from 'vitest'
2+
import { dataStoreEndpoints } from '@/lib/self-check/targets'
3+
4+
describe('dataStoreEndpoints', () => {
5+
it('lists every database endpoint the app may use: primary, per-role, and replicas', () => {
6+
expect(
7+
dataStoreEndpoints({
8+
DATABASE_URL: 'postgresql://u:p@primary.internal:5432/sim',
9+
DATABASE_URL_AUTH: 'postgresql://u:p@pgbouncer.internal:6432/sim',
10+
DATABASE_REPLICA_URL: 'postgresql://u:p@replica.internal/sim',
11+
DATABASE_REPLICA_URL_TRIGGER: 'postgresql://u:p@[fd00::7]:5433/sim',
12+
REDIS_URL: 'rediss://cache.internal:6380',
13+
})
14+
).toEqual([
15+
{ kind: 'database', host: 'primary.internal', port: 5432 },
16+
{ kind: 'database', host: 'replica.internal', port: 5432 },
17+
{ kind: 'database', host: 'pgbouncer.internal', port: 6432 },
18+
{ kind: 'database', host: 'fd00::7', port: 5433 },
19+
{ kind: 'redis', host: 'cache.internal', port: 6380 },
20+
])
21+
})
22+
23+
it('lists an endpoint shared by several variables once', () => {
24+
expect(
25+
dataStoreEndpoints({
26+
DATABASE_URL: 'postgresql://u:p@db.internal:5432/sim',
27+
DATABASE_URL_WEB: 'postgresql://other:p@db.internal/sim_web',
28+
DATABASE_REPLICA_URL: 'postgresql://u:p@db.internal:5432/sim',
29+
})
30+
).toEqual([{ kind: 'database', host: 'db.internal', port: 5432 }])
31+
})
32+
33+
it('skips unset and unparsable values', () => {
34+
expect(dataStoreEndpoints({ DATABASE_URL: 'not a url', REDIS_URL: undefined })).toEqual([])
35+
})
36+
})

0 commit comments

Comments
 (0)