Skip to content

Commit 9f0c6b2

Browse files
authored
fix(den): fail the build when the service can't load its workspace imports in production (#6232)
* fix(den): load deployment capabilities in production, and check runtime imports at build den-api crashed at startup on Render with ERR_MODULE_NOT_FOUND: the @openwork/types/den/deployment-capabilities export is served to Node from TypeScript source, and it imports ./service-readiness without a file extension, which Node's type stripping can't resolve (added in #6219). Build that export to dist with tsup (like den/gateway, which also imports a sibling) and point its production default there; development and Bun keep the source. den-api's build now loads every source-served workspace export the compiled service imports in a plain Node process, so an import like this fails the build (old version stays live) instead of the deploy. Signed-off-by: OmarMcAdam <gh@mcadam.io> * fix(den): give the build's import check no environment, and refresh the audit matrix The import check runs workspace modules' top-level code; it now gets only PATH, so nothing it loads can read build secrets such as the Sentry upload token. COVERAGE.md was stale on dev (tenant_read 145 -> 146 after #6221). Signed-off-by: OmarMcAdam <gh@mcadam.io> * fix(den): run the import check where no build secrets are mounted Source-map upload builds have the Sentry token in the environment or under /run/secrets for the whole build step, and the check runs workspace modules' code. Skip it during those builds and run it as its own step instead (check:runtime-imports; a separate Dockerfile.den RUN with no secret mounts). Render's den-api build doesn't upload source maps, so the check runs there. Signed-off-by: OmarMcAdam <gh@mcadam.io> * fix(den): keep deployment capabilities served from source (fixed by #6231) Signed-off-by: OmarMcAdam <gh@mcadam.io> #6231 resolved the readiness schema through the package export, so the dist build for den/deployment-capabilities is no longer needed. This PR keeps only the build-time runtime import check. --------- Signed-off-by: OmarMcAdam <gh@mcadam.io>
1 parent f9caa94 commit 9f0c6b2

5 files changed

Lines changed: 170 additions & 1 deletion

File tree

‎ee/apps/den-api/package.json‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
"dev": "pnpm run build:workspace-dependencies && OPENWORK_DEV_MODE=1 OPENWORK_DEN_DEVELOPMENT_CONDITIONS_REEXEC=1 NODE_OPTIONS=\"${NODE_OPTIONS:-} --conditions=development\" tsx watch src/main.ts",
99
"dev:local": "pnpm run build:workspace-dependencies && OPENWORK_DEV_MODE=1 OPENWORK_DEN_DEVELOPMENT_CONDITIONS_REEXEC=1 NODE_OPTIONS=\"${NODE_OPTIONS:-} --conditions=development\" PORT=${DEN_API_PORT:-8790} tsx watch src/main.ts",
1010
"build": "node ./scripts/build.mjs",
11+
"check:runtime-imports": "node ./scripts/check-runtime-imports.mjs",
1112
"build:workspace-dependencies": "node ../../../scripts/build-workspace-dependencies.mjs @openwork-ee/den-api",
1213
"build:den-db": "pnpm --filter @openwork-ee/den-db build",
1314
"build:mcp-apps": "pnpm --filter @openwork/mcp-apps build",

‎ee/apps/den-api/scripts/build.mjs‎

Lines changed: 75 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
import { spawnSync } from "node:child_process"
2-
import { existsSync, mkdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"
2+
import { existsSync, mkdirSync, readdirSync, readFileSync, rmSync, writeFileSync } from "node:fs"
33
import path from "node:path"
44
import { fileURLToPath } from "node:url"
55

@@ -166,6 +166,75 @@ export function missingProductionWorkspaceTypes(packageDir = serviceDir) {
166166
})
167167
}
168168

169+
function filesUnder(directory) {
170+
if (!existsSync(directory)) return []
171+
return readdirSync(directory, { withFileTypes: true }).flatMap((entry) => {
172+
const entryPath = path.join(directory, entry.name)
173+
return entry.isDirectory() ? filesUnder(entryPath) : [entryPath]
174+
})
175+
}
176+
177+
/** Workspace package specifiers (`@openwork/…`, `@openwork-ee/…`) the compiled service imports. */
178+
export function workspaceSpecifiersIn(directory) {
179+
const specifiers = new Set()
180+
for (const file of filesUnder(directory)) {
181+
if (!file.endsWith(".js")) continue
182+
const source = readFileSync(file, "utf8")
183+
for (const match of source.matchAll(/(?:from|import)\s*\(?\s*["'](@openwork(?:-ee)?\/[^"']+)["']/g)) specifiers.add(match[1])
184+
}
185+
return [...specifiers].sort()
186+
}
187+
188+
/** The export's production target, when Node loads it straight from TypeScript source (type stripping). */
189+
function sourceServedTarget(specifier, packageDir = serviceDir) {
190+
const parts = specifier.split("/")
191+
const name = parts.slice(0, 2).join("/")
192+
const subpath = parts.length > 2 ? `./${parts.slice(2).join("/")}` : "."
193+
const packageJsonPath = path.join(packageDir, "node_modules", name, "package.json")
194+
if (!existsSync(packageJsonPath)) return undefined
195+
const exports = JSON.parse(readFileSync(packageJsonPath, "utf8")).exports
196+
const value = exports && typeof exports === "object" && !Array.isArray(exports) && subpath in exports ? exports[subpath] : subpath === "." ? exports : undefined
197+
const target = productionExportTarget(value)
198+
return /\.(c|m)?tsx?$/.test(target ?? "") ? target : undefined
199+
}
200+
201+
/** The whole environment of the import check's child process: no secrets, no NODE_OPTIONS, only PATH (and Windows' SystemRoot). */
202+
export function sourceExportCheckEnv(env = process.env) {
203+
const allowed = process.platform === "win32" ? ["PATH", "Path", "SystemRoot"] : ["PATH"]
204+
return Object.fromEntries(allowed.flatMap((key) => (typeof env[key] === "string" ? [[key, env[key]]] : [])))
205+
}
206+
207+
/**
208+
* Loads every source-served workspace export the compiled service imports, in a plain Node process (no development
209+
* condition), the way production starts. A relative import Node can't resolve from source (for example one without a
210+
* file extension) only fails at runtime otherwise, after the deploy.
211+
*/
212+
export function unloadableSourceExports(specifiers, packageDir = serviceDir) {
213+
const failures = []
214+
for (const specifier of specifiers) {
215+
if (!sourceServedTarget(specifier, packageDir)) continue
216+
const result = spawnSync(process.execPath, ["--input-type=module", "-e", `await import(${JSON.stringify(specifier)})`], {
217+
cwd: packageDir,
218+
encoding: "utf8",
219+
// Importing runs the modules' top-level code: give it nothing from the build's environment (Sentry upload
220+
// token, registry credentials, …), only what Node needs to start.
221+
env: sourceExportCheckEnv(),
222+
})
223+
if (result.status !== 0) {
224+
const reason = /^\w*Error(?: \[[A-Z_]+\])?: [^\n]+/m.exec(result.stderr ?? "")?.[0] ?? `exit ${result.status}`
225+
failures.push(`${specifier}: ${reason}`)
226+
}
227+
}
228+
return failures
229+
}
230+
231+
export function verifySourceExportsLoad() {
232+
const failures = unloadableSourceExports(workspaceSpecifiersIn(distDir))
233+
if (failures.length > 0) {
234+
throw new Error(`Workspace exports the service imports fail to load in production:\n${failures.map((entry) => `- ${entry}`).join("\n")}`)
235+
}
236+
}
237+
169238
function verifyProductionWorkspaceExports() {
170239
const missing = [...missingProductionWorkspaceExports(), ...missingProductionWorkspaceTypes()]
171240
if (missing.length > 0) {
@@ -206,6 +275,11 @@ function main() {
206275
run(pnpmCommand, ["run", "build:workspace-dependencies"])
207276
verifyProductionWorkspaceExports()
208277
run(pnpmCommand, ["exec", "tsc", "-p", "tsconfig.build.json"], tscBuildEnv())
278+
// The check runs the imported modules' code. A build that uploads source maps has the Sentry token on hand
279+
// (environment or /run/secrets), so there it runs as its own step instead (`check:runtime-imports`, a separate
280+
// Dockerfile.den step with no secrets mounted).
281+
if (shouldUploadSentrySourcemaps()) console.log("Skipping the runtime import check during a source-map upload build; run check:runtime-imports separately.")
282+
else verifySourceExportsLoad()
209283
maybeUploadSentrySourcemaps()
210284
}
211285

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
// Loads every source-served workspace export the built service imports, the way production starts (see
2+
// verifySourceExportsLoad in build.mjs). Run after `build`, in a step with no build secrets.
3+
import { verifySourceExportsLoad } from "./build.mjs"
4+
5+
verifySourceExportsLoad()
6+
console.log("Workspace exports the service imports load in production.")
Lines changed: 84 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,84 @@
1+
import assert from "node:assert/strict"
2+
import { mkdirSync, mkdtempSync, rmSync, symlinkSync, writeFileSync } from "node:fs"
3+
import { tmpdir } from "node:os"
4+
import path from "node:path"
5+
import test from "node:test"
6+
import { sourceExportCheckEnv, unloadableSourceExports, workspaceSpecifiersIn } from "../scripts/build.mjs"
7+
8+
/**
9+
* A service with one workspace package served from TypeScript source, like @openwork/types: `broken` imports a
10+
* sibling without a file extension (what Node can't resolve at runtime), `fine` imports one with its real extension
11+
* only as a type, and `built` is served from dist. The package lives outside node_modules and is linked in, as pnpm
12+
* links workspace packages (Node refuses to strip types under a real node_modules path).
13+
*/
14+
function fixture() {
15+
const root = mkdtempSync(path.join(tmpdir(), "den-build-exports-"))
16+
const pkg = path.join(root, "packages", "fixture")
17+
mkdirSync(path.join(pkg, "src"), { recursive: true })
18+
mkdirSync(path.join(root, "node_modules", "@openwork"), { recursive: true })
19+
symlinkSync(pkg, path.join(root, "node_modules", "@openwork", "fixture"), "dir")
20+
mkdirSync(path.join(pkg, "dist"), { recursive: true })
21+
writeFileSync(
22+
path.join(pkg, "package.json"),
23+
JSON.stringify({
24+
name: "@openwork/fixture",
25+
type: "module",
26+
exports: {
27+
"./broken": { development: "./src/broken.ts", default: "./src/broken.ts" },
28+
"./fine": { development: "./src/fine.ts", default: "./src/fine.ts" },
29+
"./built": { development: "./src/broken.ts", default: "./dist/built.js" },
30+
"./env-probe": { development: "./src/env-probe.ts", default: "./src/env-probe.ts" },
31+
},
32+
}),
33+
)
34+
writeFileSync(path.join(pkg, "src", "sibling.ts"), "export const sibling: number = 1\n")
35+
writeFileSync(path.join(pkg, "src", "broken.ts"), 'import { sibling } from "./sibling"\nexport const broken: number = sibling\n')
36+
writeFileSync(path.join(pkg, "src", "fine.ts"), 'import type { Sibling } from "./types"\nexport const fine: Sibling = 1\n')
37+
writeFileSync(path.join(pkg, "src", "types.ts"), "export type Sibling = number\n")
38+
writeFileSync(path.join(pkg, "dist", "built.js"), "export const built = 1\n")
39+
// Top-level code that would leak a build secret: it fails to load if it can see one.
40+
writeFileSync(
41+
path.join(pkg, "src", "env-probe.ts"),
42+
'if (process.env.SENTRY_AUTH_TOKEN !== undefined) throw new Error("SENTRY_AUTH_TOKEN visible")\nexport const probe = true\n',
43+
)
44+
const dist = path.join(root, "dist")
45+
mkdirSync(path.join(dist, "routes"), { recursive: true })
46+
writeFileSync(path.join(dist, "main.js"), 'import { broken } from "@openwork/fixture/broken"\nimport { fine } from "@openwork/fixture/fine"\n')
47+
writeFileSync(path.join(dist, "routes", "lazy.js"), 'const built = await import("@openwork/fixture/built")\nimport { probe } from "@openwork/fixture/env-probe"\n')
48+
return { root, dist }
49+
}
50+
51+
test("the build finds every workspace import in the compiled service, including dynamic ones", () => {
52+
const { root, dist } = fixture()
53+
try {
54+
assert.deepEqual(workspaceSpecifiersIn(dist), ["@openwork/fixture/broken", "@openwork/fixture/built", "@openwork/fixture/env-probe", "@openwork/fixture/fine"])
55+
} finally {
56+
rmSync(root, { recursive: true, force: true })
57+
}
58+
})
59+
60+
test("a source-served export with an import Node can't resolve fails the build; working and dist-served ones pass", () => {
61+
const { root, dist } = fixture()
62+
try {
63+
const failures = unloadableSourceExports(workspaceSpecifiersIn(dist), root)
64+
assert.equal(failures.length, 1, failures.join("\n"))
65+
assert.match(failures[0] ?? "", /^@openwork\/fixture\/broken: Error \[ERR_MODULE_NOT_FOUND\]: Cannot find module .*sibling'/)
66+
} finally {
67+
rmSync(root, { recursive: true, force: true })
68+
}
69+
})
70+
71+
test("the checked modules see none of the build's environment, so they can't read its secrets", () => {
72+
assert.deepEqual(sourceExportCheckEnv({ PATH: "/usr/bin", SENTRY_AUTH_TOKEN: "secret", NODE_OPTIONS: "--require x", HOME: "/root" }), process.platform === "win32" ? {} : { PATH: "/usr/bin" })
73+
const { root, dist } = fixture()
74+
const previous = process.env.SENTRY_AUTH_TOKEN
75+
process.env.SENTRY_AUTH_TOKEN = "sntrys_fixture_not_a_real_token"
76+
try {
77+
const failures = unloadableSourceExports(workspaceSpecifiersIn(dist), root)
78+
assert.ok(!failures.some((entry) => entry.startsWith("@openwork/fixture/env-probe")), failures.join("\n"))
79+
} finally {
80+
if (previous === undefined) delete process.env.SENTRY_AUTH_TOKEN
81+
else process.env.SENTRY_AUTH_TOKEN = previous
82+
rmSync(root, { recursive: true, force: true })
83+
}
84+
})

‎packaging/docker/Dockerfile.den‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,6 +109,10 @@ RUN --mount=type=secret,id=sentry_auth_token,required=false \
109109
fi; \
110110
pnpm --dir /app/ee/apps/den-api run build
111111

112+
# Load the workspace exports the built service imports, the way production starts. Its own step: it runs those
113+
# modules' code, so no build secrets are mounted here.
114+
RUN pnpm --dir /app/ee/apps/den-api run check:runtime-imports
115+
112116
EXPOSE 8788
113117

114118
HEALTHCHECK --interval=30s --timeout=5s --start-period=20s --retries=3 CMD node -e "fetch('http://127.0.0.1:' + (process.env.PORT || '8788') + '/health').then((res) => process.exit(res.ok ? 0 : 1)).catch(() => process.exit(1))"

0 commit comments

Comments
 (0)