fix(bootstrap): 금지된 설정 키로 멈춘 부팅 오류에 그 키 이름을 싣는다
문제: 런타임 설정에 비밀처럼 보이는 키(`CLIENT_SECRET` 등)가 있으면 부팅이 CONFIG_SECRET_NAME_REJECTED로 멈추지만, 안전한 부팅 오류에는 buildId만 있고 어느 키인지가 없다. assertSafeConfigNames가 던진 오류의 message에는 키 이름이 있었지만 loadRuntimeConfig가 그 오류를 버렸다. 같은 파일의 스키마 실패는 키 이름을 invalidKeys로 싣는다. 고른 방법: assertSafeConfigNames가 UnsafeConfigNameError를 던지고 그 `key`에 거절한 키의 점 경로(`CAPABILITY_OVERRIDES.AUTH_TOKEN`, `FEATURE_OVERRIDES.<id>.CLIENT_SECRET`)를 싣는다. 로더는 그 경로를 스키마 실패와 같은 SAFE_KEY_PATTERN으로 거른 뒤 invalidKeys에 넣는다. 오류 화면은 이미 invalidKeys를 "잘못된 설정 키"로 보인다. 값은 어디에도 싣지 않는다. 버린 대안: message에서 키를 정규식으로 다시 읽는 것. message 문구가 바뀌면 조용히 빠진다. 위험·한계: 키 이름은 거절된 문서에서 온다. 그래서 길이·문자를 제한하고, 그 밖의 이름은 빼고 코드만 남긴다. 첫 번째로 걸린 키 하나만 싣는다 (검사가 첫 키에서 멈추는 동작은 그대로). assertSafeConfigNames의 시그니처와 message는 바꾸지 않았다. UnsafeConfigNameError는 src/contracts/env.ts에 새로 더한 export다(추가만). 검증: desktop batch에서 확인. node scripts/run-vitest.ts run tests/runtime-schema/runtime-config.test.ts Refs: 1103/07-04
This commit is contained in:
@@ -110,7 +110,7 @@ release admission refused for staging:
|
||||
- 실시간 갱신: 짝 백엔드의 실시간 출구(STOMP·NDJSON)와 프론트 realtime 어댑터(SSE·`realtime.v1` WebSocket)는 그대로 연결되지 않는다. 지금 되는 경로는 bounded polling이다. 대응표: [realtime 설계 0.1절](../architecture/realtime-events-web-push-and-bounded-polling.md#01-짝-백엔드-템플릿과의-대응-110304-02).
|
||||
- `src/contracts/product-contracts.ts`: 제품 인증 프로필이나 제품 런타임 설정 키가 필요할 때.
|
||||
- 템플릿 파일 `src/contracts/rest-profiles.ts`는 고치지 않는다.
|
||||
- 설정 키 이름에 `TOKEN`·`COOKIE`·`SECRET`·`PASSWORD` 같은 조각(`src/contracts/env.ts`의 `FORBIDDEN_CONFIG_NAME_FRAGMENTS`, 대소문자 무관)을 넣지 않는다. 부팅이 `CONFIG_SECRET_NAME_REJECTED`로 멈춘다. `test:unit`의 `env-registry-coverage`가 먼저 `Forbidden client configuration key: <키>`로 실패한다.
|
||||
- 설정 키 이름에 `TOKEN`·`COOKIE`·`SECRET`·`PASSWORD` 같은 조각(`src/contracts/env.ts`의 `FORBIDDEN_CONFIG_NAME_FRAGMENTS`, 대소문자 무관)을 넣지 않는다. 부팅이 `CONFIG_SECRET_NAME_REJECTED`로 멈추고, 오류 화면의 "잘못된 설정 키"에 그 키 이름(값은 아님. 중첩 키는 `CAPABILITY_OVERRIDES.AUTH_TOKEN`처럼 경로)이 나온다. `test:unit`의 `env-registry-coverage`가 먼저 `Forbidden client configuration key: <키>`로 실패한다.
|
||||
- FE-REG-ENV 행의 `required`·`defaultValue`는 zod 필드가 키가 없을 때 하는 것과 같게 적는다. 기본값이 없으면 `defaultValue: null`이다. 같은 테스트가 대조한다.
|
||||
- `config/runtime/<profile>.json`: 환경별로 기능을 끄고 싶을 때(`FEATURE_OVERRIDES`).
|
||||
- `src/features/product-capabilities.ts`의 선택 런타임(`PRODUCT_RUNTIME_CAPABILITY_SELECTION`): Service Worker를 켤 때. 아래 "SW 켜기"를 본다.
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { assertSafeConfigNames, getBuildConfig } from "../contracts/env.ts";
|
||||
import {
|
||||
assertSafeConfigNames,
|
||||
getBuildConfig,
|
||||
UnsafeConfigNameError,
|
||||
} from "../contracts/env.ts";
|
||||
import { checkReleaseCoherence } from "../platform/release/release-coherence.ts";
|
||||
import {
|
||||
BOOT_JSON_POLICIES,
|
||||
@@ -21,7 +25,10 @@ export type BootConfigSafe = Readonly<{
|
||||
buildId: string;
|
||||
configSchemaVersion?: string;
|
||||
releaseId?: string;
|
||||
/** 09-04. Names of rejected keys (never their values), bounded. */
|
||||
/**
|
||||
* 09-04. Names of rejected keys (never their values), bounded: the keys the
|
||||
* schema rejected, or (1103/07-04) the secret-looking key's dotted path.
|
||||
*/
|
||||
invalidKeys?: readonly string[];
|
||||
supportReference: string;
|
||||
}>;
|
||||
@@ -117,9 +124,16 @@ export async function loadRuntimeConfig(
|
||||
|
||||
try {
|
||||
assertSafeConfigNames(rawConfig);
|
||||
} catch {
|
||||
} catch (error) {
|
||||
// 1103/07-04. The rejected key's name, never its value, tells an operator
|
||||
// what to remove. It comes from the rejected document, so it is bounded
|
||||
// like the schema failure's keys below.
|
||||
const key = error instanceof UnsafeConfigNameError ? error.key : undefined;
|
||||
throw new BootConfigError("CONFIG_SECRET_NAME_REJECTED", {
|
||||
buildId: buildConfig.buildId,
|
||||
...(key !== undefined && SAFE_KEY_PATTERN.test(key)
|
||||
? { invalidKeys: Object.freeze([key]) }
|
||||
: {}),
|
||||
});
|
||||
}
|
||||
|
||||
|
||||
+36
-5
@@ -116,25 +116,56 @@ function runtime(
|
||||
return Object.freeze({ phase: "runtime", classification, required, defaultValue });
|
||||
}
|
||||
|
||||
/**
|
||||
* 1103/07-04. What `assertSafeConfigNames` throws. `key` is the rejected
|
||||
* key's dotted path from where the check started
|
||||
* (`CAPABILITY_OVERRIDES.AUTH_TOKEN`), so the boot error can name it without
|
||||
* its value. It is absent when the document nests too deep.
|
||||
*/
|
||||
export class UnsafeConfigNameError extends Error {
|
||||
readonly key: string | undefined;
|
||||
|
||||
constructor(message: string, key?: string) {
|
||||
super(message);
|
||||
this.name = "UnsafeConfigNameError";
|
||||
this.key = key;
|
||||
}
|
||||
}
|
||||
|
||||
export function assertSafeConfigNames(
|
||||
config: Readonly<Record<string, unknown>>,
|
||||
depth = 0,
|
||||
): void {
|
||||
assertSafeConfigNamesAt(config, depth, []);
|
||||
}
|
||||
|
||||
function assertSafeConfigNamesAt(
|
||||
config: Readonly<Record<string, unknown>>,
|
||||
depth: number,
|
||||
path: readonly string[],
|
||||
): void {
|
||||
if (depth > 4) {
|
||||
throw new Error("Client configuration nesting exceeds its bound");
|
||||
throw new UnsafeConfigNameError(
|
||||
"Client configuration nesting exceeds its bound",
|
||||
);
|
||||
}
|
||||
for (const [name, value] of Object.entries(config)) {
|
||||
const allowlisted = depth === 0 && SEMANTIC_KEY_ALLOWLIST.has(name);
|
||||
if (!allowlisted && isForbiddenConfigName(name)) {
|
||||
throw new Error(`Forbidden client configuration key: ${name}`);
|
||||
throw new UnsafeConfigNameError(
|
||||
`Forbidden client configuration key: ${name}`,
|
||||
[...path, name].join("."),
|
||||
);
|
||||
}
|
||||
if (!isPlainNested(value)) continue;
|
||||
if (depth === 0 && FEATURE_ID_KEYED_MAPS.has(name)) {
|
||||
for (const entry of Object.values(value)) {
|
||||
if (isPlainNested(entry)) assertSafeConfigNames(entry, depth + 2);
|
||||
for (const [featureId, entry] of Object.entries(value)) {
|
||||
if (isPlainNested(entry)) {
|
||||
assertSafeConfigNamesAt(entry, depth + 2, [...path, name, featureId]);
|
||||
}
|
||||
}
|
||||
} else {
|
||||
assertSafeConfigNames(value, depth + 1);
|
||||
assertSafeConfigNamesAt(value, depth + 1, [...path, name]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
@@ -294,6 +294,44 @@ describe("runtime configuration boundary", () => {
|
||||
expect(JSON.stringify(safe)).not.toContain("value-probe");
|
||||
});
|
||||
|
||||
// 1103/07-04. A secret-looking key stops boot before the schema runs. The
|
||||
// boot error names that key, with its path below a nested map, and never
|
||||
// its value. A key name that is not safe to show is left out.
|
||||
it.each<[Record<string, unknown>, readonly string[] | undefined]>([
|
||||
[{ CLIENT_SECRET: "value-probe" }, ["CLIENT_SECRET"]],
|
||||
[
|
||||
{ CAPABILITY_OVERRIDES: { AUTH_TOKEN: "value-probe" } },
|
||||
["CAPABILITY_OVERRIDES.AUTH_TOKEN"],
|
||||
],
|
||||
[
|
||||
{ FEATURE_OVERRIDES: { alpha: { CLIENT_SECRET: "value-probe" } } },
|
||||
["FEATURE_OVERRIDES.alpha.CLIENT_SECRET"],
|
||||
],
|
||||
[{ "<b>CLIENT_SECRET": "value-probe" }, undefined],
|
||||
])(
|
||||
"names the forbidden key of %o as %o, never its value (1103/07-04)",
|
||||
async (extra, invalidKeys) => {
|
||||
const failure = await loadRuntimeConfig({
|
||||
buildConfig: {
|
||||
buildId: "build-a",
|
||||
commitSha: "local",
|
||||
routerBasePath: "/",
|
||||
runtimeConfigUrl: "/config.json",
|
||||
},
|
||||
fetcher: async () =>
|
||||
new Response(JSON.stringify({ ...validConfig, ...extra }), {
|
||||
headers: { "content-type": "application/json" },
|
||||
}),
|
||||
}).catch((error: unknown) => error);
|
||||
|
||||
expect(failure).toBeInstanceOf(BootConfigError);
|
||||
const safe = (failure as BootConfigError).safe;
|
||||
expect(safe.code).toBe("CONFIG_SECRET_NAME_REJECTED");
|
||||
expect(safe.invalidKeys).toEqual(invalidKeys);
|
||||
expect(JSON.stringify(safe)).not.toContain("value-probe");
|
||||
},
|
||||
);
|
||||
|
||||
it("returns only safe boot fields on failure", async () => {
|
||||
await expect(
|
||||
loadRuntimeConfig({
|
||||
|
||||
Reference in New Issue
Block a user