fix(hosting): FE-GATE-019가 후보의 설정·entry와 HTTP/2·압축 전제를 대조한다
문제: (1) live probe는 배포된 release-manifest.json의 buildId·releaseId만 후보와 비교했다. 두 값은 CI run 번호로 만든 이름이라, 같은 run에서 로컬 프로필로 다시 빌드한 release(APP_ENV=local, AUTH_MODE=demo, loopback API)를 올려도 PASS(live)였다(리뷰 실험 E-2c). 공개 대상 승인 (FE-GATE-027)을 받은 것은 후보의 config.json인데, 호스트가 내주는 config.json은 헤더만 보았다. entry script도 호스트의 두 응답끼리만 비교했다. (2) 템플릿은 HTTP/2와 압축을 전제로 초기 청크를 나누고 gzip 바이트로 예산을 재는데, 그 전제가 호스팅 계약에 없고 probe도 보지 않았다. 템플릿 nginx 예시는 http2도 gzip도 켜지 않았다. 고른 방법: - 받은 /config.json을 후보 dist/config.json과 비교한다. 비상 스위치 두 개(CAPABILITY_OVERRIDES, FEATURE_OVERRIDES) 밖의 필드가 다르거나 읽을 수 없으면 FAIL. 규칙은 check-release-admission과 같은 함수 (scripts/lib/runtime-config-switches.ts)로 옮겨 같이 쓴다. - 받은 index.html의 entry script를 후보 index.html의 것과 비교한다. - cache-policy.json에 transport.alpnProtocols(["h2"])와 hashedAsset.contentEncodings(br, gzip, zstd)를 선언한다. probe는 TLS handshake의 ALPN(node:tls, h2와 http/1.1을 제안)과 entry script 응답의 Content-Encoding을 본다. Node fetch는 h2를 지원하는 서버에도 HTTP/1.1로 붙어서 프로토콜은 따로 확인해야 한다. - nginx 예시에 http2 on과 gzip·gzip_types를 넣고, static-delivery.md와 release-cache-rollback.md에 두 전제와 실패 조건을 적었다. 두 수정은 같은 probe 함수와 테스트를 고쳐 한 커밋에 넣었다. 버린 대안: archive SHA를 호스트에 올려 대조하기(호스트에 새 파일 규약이 생기고 일부 파일만 다른 배포는 못 잡는다). HTTP/2를 기록만 하기 (아무도 읽지 않는 경고는 청크를 묶는 결정을 부르지 못한다. 선언을 바꾸면 제품이 끌 수 있다). 위험·한계: HTTP/1.1만 되는 호스트는 이제 FE-GATE-019에서 FAIL한다. 그 제품은 cache-policy.json 선언을 바꾸고 초기 청크를 묶는다. 실제 nginx와 Gitea runner에서는 돌리지 않았다. 슬롯이 후보를 받도록 강제하는 계약 규칙은 다음 커밋(제품 overlay)에 있다. 검증: hosting-probe.test.ts에 같은 이름·다른 config.json → FAIL, 비상 스위치만 다름 → PASS, 읽을 수 없는 config.json → FAIL, 다른 entry → FAIL, ALPN http/1.1·없음 → FAIL, 압축 없는 entry → FAIL, 정책 선언 확인을 더했다(고치기 전 실패). 33건 통과. 로컬 자체 서명 TLS 서버 실험: http2.createSecureServer → "h2", https.createServer → "http/1.1", 인증서 이름 불일치 → ERR_TLS_CERT_ALTNAME_INVALID. verify:hosting-headers(fixture) UNVERIFIED exit 3, deployment-admission 통과. Refs: docs/reviews/2026-11-03-maturity-review/13-build-release-supply-chain.md 13-01, 13-02
This commit is contained in:
@@ -1,5 +1,8 @@
|
||||
{
|
||||
"schemaVersion": 1,
|
||||
"transport": {
|
||||
"alpnProtocols": ["h2"]
|
||||
},
|
||||
"surfaces": {
|
||||
"index": {
|
||||
"path": "/",
|
||||
@@ -23,6 +26,7 @@
|
||||
"pathPattern": "/assets/*",
|
||||
"cacheControl": "public, max-age=31536000, immutable",
|
||||
"contentTypes": ["text/javascript", "application/javascript"],
|
||||
"contentEncodings": ["br", "gzip", "zstd"],
|
||||
"securityHeaders": false
|
||||
},
|
||||
"sourceMap": {
|
||||
|
||||
@@ -33,7 +33,8 @@
|
||||
},
|
||||
"hashedAsset": {
|
||||
"cache-control": "public, max-age=31536000, immutable",
|
||||
"content-type": "text/javascript; charset=utf-8"
|
||||
"content-type": "text/javascript; charset=utf-8",
|
||||
"content-encoding": "gzip"
|
||||
},
|
||||
"appRoute": {
|
||||
"cache-control": "no-cache",
|
||||
|
||||
@@ -51,3 +51,12 @@ HTTP/1.1 groups its initial chunks in `vite.config.ts` and measures again
|
||||
whenever the shell changes ("초기 청크 수와 HTTP/1.1" in
|
||||
[`performance-evidence.md`](../operations/performance-evidence.md), review
|
||||
1101/14.4).
|
||||
|
||||
Serve JavaScript compressed (gzip, brotli or zstd). The bundle budget counts
|
||||
gzip bytes; uncompressed, the initial JavaScript is about three times larger.
|
||||
Both premises are declared in `config/hosting/cache-policy.json`
|
||||
(`transport.alpnProtocols`, `hashedAsset.contentEncodings`), and the live probe
|
||||
of FE-GATE-019 fails a host that does not meet them (review 1103/13-02). The
|
||||
nginx example in
|
||||
[`release-cache-rollback.md`](../operations/release-cache-rollback.md) turns
|
||||
both on.
|
||||
|
||||
@@ -335,7 +335,10 @@ contract rejects a production gate command that builds or omits the release root
|
||||
The hosting gate FE-GATE-019 also reads `.release/promoted-release`: it checks
|
||||
that archive's `dist` and requires the live host to serve a
|
||||
`release-manifest.json` with the candidate's `buildId` and `releaseId`, so a
|
||||
host still serving an earlier release fails (1101/13-01). The workflow deploys
|
||||
host still serving an earlier release fails (1101/13-01). Because a rebuild in
|
||||
the same run shares those names, the served `config.json` must also equal the
|
||||
candidate's outside the two emergency switches and the served `index.html` must
|
||||
name the candidate's entry script (1103/13-01). The workflow deploys
|
||||
nothing itself. Between `promotion` and `production_gate` sits the `deployment`
|
||||
job, the project's deployment slot. It is empty by default: it reports
|
||||
`deployed=false`, FE-GATE-019 does not probe the host and ends `UNVERIFIED`
|
||||
|
||||
@@ -80,6 +80,24 @@ evidence for this one (review 1101/13-01). That release is
|
||||
`<release-root>/dist` with `-- --release-root <extracted archive>` (FE-GATE-019
|
||||
passes the promoted archive), otherwise the local `dist`.
|
||||
|
||||
Those two names come from the CI run, so a release rebuilt in the same run
|
||||
carries them as well. The served `config.json` must therefore equal the
|
||||
release's `dist/config.json`, the document release admission (FE-GATE-027)
|
||||
admitted, in every field except the two emergency switches
|
||||
`CAPABILITY_OVERRIDES` and `FEATURE_OVERRIDES` (FE-RB-001), and the served
|
||||
`index.html` must name the release's entry script (review 1103/13-01).
|
||||
|
||||
The probe also checks the two serving premises the bundle budget and the split
|
||||
initial chunks rest on (review 1103/13-02): the entry script arrives with a
|
||||
`Content-Encoding` from `hashedAsset.contentEncodings` (the budget counts gzip
|
||||
bytes; uncompressed, the initial JavaScript is about three times larger), and
|
||||
the TLS handshake negotiates a protocol from `transport.alpnProtocols` (`h2`;
|
||||
over HTTP/1.1 the initial files queue for six connections). A host that cannot
|
||||
meet them fails FE-GATE-019; a product that has to serve that way changes the
|
||||
declaration in `config/hosting/cache-policy.json` in the same change that
|
||||
groups its initial chunks ("초기 청크 수와 HTTP/1.1" in
|
||||
[`performance-evidence.md`](performance-evidence.md)).
|
||||
|
||||
### Example: nginx on a single server
|
||||
|
||||
Written by hand for the default base path `/`; nothing in CI runs it. The live
|
||||
@@ -100,9 +118,18 @@ add_header Permissions-Policy "camera=(), microphone=(), geolocation=()" always;
|
||||
```nginx
|
||||
server {
|
||||
listen 443 ssl;
|
||||
# nginx 1.25.1 and later; before it, `listen 443 ssl http2;`.
|
||||
http2 on;
|
||||
server_name app.example.com;
|
||||
# ssl_certificate / ssl_certificate_key ...
|
||||
|
||||
# The bundle budget counts gzip bytes, and FE-GATE-019 fails an
|
||||
# uncompressed entry script (cache-policy.json `hashedAsset`). nginx
|
||||
# compresses only text/html unless gzip_types names the rest.
|
||||
gzip on;
|
||||
gzip_vary on;
|
||||
gzip_types text/javascript application/javascript application/json text/css image/svg+xml;
|
||||
|
||||
# The active release directory. Switch it with an atomic symlink rename.
|
||||
root /srv/frontend/current;
|
||||
|
||||
|
||||
@@ -12,6 +12,10 @@ import { unknownProductFeatureOverrides } from "../src/contracts/product-feature
|
||||
import { parseRuntimeConfigArtifact } from "../src/contracts/release-artifacts.ts";
|
||||
import { EXPECTED_CONTRACT_SET_PACKAGES } from "../src/features/installed-contract-contributions.ts";
|
||||
import { COMPILED_PRODUCT_FEATURE_IDS } from "../src/features/installed-product-manifest.ts";
|
||||
import {
|
||||
changedRuntimeConfigBuildFields,
|
||||
RUNTIME_CONFIG_EMERGENCY_SWITCHES,
|
||||
} from "./lib/runtime-config-switches.ts";
|
||||
|
||||
/**
|
||||
* §6.4 / FE-GATE-027. Refuses to admit an artifact to an environment it was not
|
||||
@@ -30,17 +34,7 @@ import { COMPILED_PRODUCT_FEATURE_IDS } from "../src/features/installed-product-
|
||||
|
||||
const RUNTIME_CONFIG_PATH = "dist/config.json";
|
||||
const RECORD_PATH = "artifacts/release/deployment-admission.json";
|
||||
|
||||
/**
|
||||
* 1101/13-05. The only fields an operator may change in a deployed config.json
|
||||
* without a rebuild (docs/runbooks/FE-RB-001.md). Every other field belongs to
|
||||
* the build: BUILD_ID and RELEASE_ID must still match the deployed HTML and
|
||||
* release manifest, or every boot stops with CONFIG_BUILD_MISMATCH.
|
||||
*/
|
||||
const EMERGENCY_SWITCHES: ReadonlySet<string> = new Set([
|
||||
"CAPABILITY_OVERRIDES",
|
||||
"FEATURE_OVERRIDES",
|
||||
]);
|
||||
const EMERGENCY_SWITCHES = RUNTIME_CONFIG_EMERGENCY_SWITCHES;
|
||||
|
||||
function refuse(reason: string): void {
|
||||
process.stderr.write(`release admission refused: ${reason}\n`);
|
||||
@@ -67,18 +61,6 @@ async function readRuntimeConfig(file: string): Promise<AdmissionInput | null> {
|
||||
}
|
||||
}
|
||||
|
||||
function changedBuildFields(original: object, edited: object): string[] {
|
||||
const before = new Map(Object.entries(original));
|
||||
const after = new Map(Object.entries(edited));
|
||||
return [...new Set([...before.keys(), ...after.keys()])]
|
||||
.filter(
|
||||
(field) =>
|
||||
!EMERGENCY_SWITCHES.has(field) &&
|
||||
JSON.stringify(before.get(field)) !== JSON.stringify(after.get(field)),
|
||||
)
|
||||
.sort();
|
||||
}
|
||||
|
||||
async function main(): Promise<void> {
|
||||
// `pnpm check:release-admission -- --config …` may pass the separator through.
|
||||
const argv = process.argv.slice(2);
|
||||
@@ -127,7 +109,7 @@ async function main(): Promise<void> {
|
||||
if (options.original !== undefined) {
|
||||
const original = await readRuntimeConfig(options.original);
|
||||
if (original === null) return;
|
||||
const changed = changedBuildFields(original, config);
|
||||
const changed = changedRuntimeConfigBuildFields(original, config);
|
||||
if (changed.length > 0) {
|
||||
refuse(
|
||||
`${configPath} changes ${changed.join(", ")}; without a rebuild only ` +
|
||||
|
||||
@@ -1,4 +1,8 @@
|
||||
import { isIP } from "node:net";
|
||||
import { connect } from "node:tls";
|
||||
|
||||
import type { InstalledServiceWorkerSelection } from "../../src/contracts/service-worker.ts";
|
||||
import { changedRuntimeConfigBuildFields } from "./runtime-config-switches.ts";
|
||||
|
||||
const LOOPBACK_IPV4 = /^127(?:\.\d{1,3}){3}$/;
|
||||
|
||||
@@ -39,6 +43,49 @@ export type ProbeResult = Readonly<{
|
||||
export type ResponseHeaders = Record<string, Record<string, string>>;
|
||||
export type HostingFetcher = (url: URL) => Promise<Response>;
|
||||
export type ReleaseIdentity = Readonly<{ buildId: string; releaseId: string }>;
|
||||
/** The promoted candidate: its manifest names and the texts of its dist/config.json and dist/index.html. */
|
||||
export type CandidateRelease = ReleaseIdentity & Readonly<{ runtimeConfig: string; indexHtml: string }>;
|
||||
export type ProbeTransport = Readonly<{
|
||||
fetcher?: HostingFetcher;
|
||||
/** The ALPN protocol the host negotiates over TLS, or null when none. */
|
||||
negotiateAlpn?: (base: URL) => Promise<string | null>;
|
||||
/** Accepted protocols (`transport.alpnProtocols` in config/hosting/cache-policy.json); empty skips the check. */
|
||||
alpnProtocols?: readonly string[];
|
||||
}>;
|
||||
|
||||
/**
|
||||
* 1103/13-02. Node's fetch speaks HTTP/1.1 even to a host that offers h2, so
|
||||
* the protocol a browser gets is read from the TLS handshake instead: the
|
||||
* client offers h2 and http/1.1 and the host picks one. The certificate is
|
||||
* verified as fetch verifies it.
|
||||
*/
|
||||
export function negotiatedAlpnProtocol(base: URL, timeoutMs = 10_000): Promise<string | null> {
|
||||
return new Promise((resolve, reject) => {
|
||||
const host = base.hostname.replace(/^\[|\]$/gu, "");
|
||||
const socket = connect({
|
||||
host,
|
||||
port: Number(base.port || 443),
|
||||
...(isIP(host) === 0 ? { servername: host } : {}),
|
||||
ALPNProtocols: ["h2", "http/1.1"],
|
||||
});
|
||||
socket.setTimeout(timeoutMs, () => socket.destroy(new Error("TLS handshake timed out")));
|
||||
socket.once("secureConnect", () => {
|
||||
const protocol = socket.alpnProtocol;
|
||||
socket.end();
|
||||
resolve(typeof protocol === "string" ? protocol : null);
|
||||
});
|
||||
socket.once("error", reject);
|
||||
});
|
||||
}
|
||||
|
||||
function parsedJsonObject(text: string | null): object | null {
|
||||
try {
|
||||
const value: unknown = JSON.parse(text ?? "");
|
||||
return value !== null && typeof value === "object" && !Array.isArray(value) ? value : null;
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/** `buildId` and `releaseId` of a release-manifest.json text, or null. */
|
||||
export function releaseIdentity(manifest: string | null): ReleaseIdentity | null {
|
||||
@@ -64,13 +111,24 @@ export function releaseIdentity(manifest: string | null): ReleaseIdentity | null
|
||||
*
|
||||
* 1101/13-01. The served release manifest must name the candidate's build and
|
||||
* release. Correct headers on an earlier release are not evidence for this one.
|
||||
*
|
||||
* 1103/13-01. Those names come from the CI run, so a release rebuilt in the
|
||||
* same run (say with the local profile) carries them too. The served
|
||||
* config.json must equal the candidate's, the one release admission
|
||||
* (FE-GATE-027) admitted, except for the two emergency switches FE-RB-001 may
|
||||
* change; and the served index.html must name the candidate's entry script.
|
||||
*
|
||||
* 1103/13-02. The host must negotiate a declared protocol (HTTP/2): the
|
||||
* template splits its initial chunks on that premise.
|
||||
*/
|
||||
export async function probeLiveRelease(
|
||||
base: URL,
|
||||
paths: Readonly<Record<string, string>>,
|
||||
candidate: ReleaseIdentity,
|
||||
fetcher: HostingFetcher = (url) => fetch(url, { redirect: "follow" }),
|
||||
candidate: CandidateRelease,
|
||||
transport: ProbeTransport = {},
|
||||
): Promise<{ responses: ResponseHeaders; results: ProbeResult[] }> {
|
||||
const fetcher = transport.fetcher ?? ((url: URL) => fetch(url, { redirect: "follow" }));
|
||||
const negotiateAlpn = transport.negotiateAlpn ?? negotiatedAlpnProtocol;
|
||||
const responses: ResponseHeaders = {};
|
||||
const results: ProbeResult[] = [];
|
||||
const probe = async (surface: string, pathname: string): Promise<string | null> => {
|
||||
@@ -145,6 +203,50 @@ export async function probeLiveRelease(
|
||||
passed: entryScript !== null && observed === entryScript,
|
||||
});
|
||||
}
|
||||
const candidateEntryScript = servedEntryScript(candidate.indexHtml);
|
||||
results.push({
|
||||
surface: "index",
|
||||
header: "candidate-entry-script",
|
||||
expected: candidateEntryScript,
|
||||
observed: entryScript,
|
||||
passed: candidateEntryScript !== null && entryScript === candidateEntryScript,
|
||||
});
|
||||
if ("runtimeConfig" in paths) {
|
||||
const served = parsedJsonObject(bodies["runtimeConfig"] ?? null);
|
||||
const admitted = parsedJsonObject(candidate.runtimeConfig);
|
||||
const changed = served && admitted ? changedRuntimeConfigBuildFields(admitted, served) : null;
|
||||
results.push({
|
||||
surface: "runtimeConfig",
|
||||
header: "build-fields",
|
||||
expected: [],
|
||||
observed: changed ?? "unreadable",
|
||||
...(changed === null
|
||||
? { reason: "the served or the candidate config.json is not a JSON object" }
|
||||
: changed.length > 0
|
||||
? { reason: "differs from the candidate's config.json beyond the emergency switches" }
|
||||
: {}),
|
||||
passed: changed !== null && changed.length === 0,
|
||||
});
|
||||
}
|
||||
const alpnProtocols = transport.alpnProtocols ?? [];
|
||||
if (alpnProtocols.length > 0) {
|
||||
let observed: string | null;
|
||||
try {
|
||||
observed = await negotiateAlpn(base);
|
||||
} catch (error: unknown) {
|
||||
observed = error instanceof Error ? error.name : "UnknownError";
|
||||
}
|
||||
results.push({
|
||||
surface: "transport",
|
||||
header: "alpn",
|
||||
expected: alpnProtocols,
|
||||
observed,
|
||||
...(observed !== null && alpnProtocols.includes(observed)
|
||||
? {}
|
||||
: { reason: "the split initial chunks assume HTTP/2 (docs/architecture/static-delivery.md)" }),
|
||||
passed: observed !== null && alpnProtocols.includes(observed),
|
||||
});
|
||||
}
|
||||
return { responses, results };
|
||||
}
|
||||
|
||||
|
||||
@@ -0,0 +1,27 @@
|
||||
/**
|
||||
* 1101/13-05. The only fields an operator may change in a deployed config.json
|
||||
* without a rebuild (docs/runbooks/FE-RB-001.md). Every other field belongs to
|
||||
* the build: BUILD_ID and RELEASE_ID must still match the deployed HTML and
|
||||
* release manifest, or every boot stops with CONFIG_BUILD_MISMATCH.
|
||||
*
|
||||
* 1103/13-01. The live hosting probe (FE-GATE-019) compares the served
|
||||
* config.json with the promoted candidate's by the same rule, so the release
|
||||
* admission and the probe agree on what an edited document may change.
|
||||
*/
|
||||
export const RUNTIME_CONFIG_EMERGENCY_SWITCHES: ReadonlySet<string> = new Set([
|
||||
"CAPABILITY_OVERRIDES",
|
||||
"FEATURE_OVERRIDES",
|
||||
]);
|
||||
|
||||
/** Fields other than the emergency switches whose values differ, sorted. */
|
||||
export function changedRuntimeConfigBuildFields(original: object, edited: object): string[] {
|
||||
const before = new Map(Object.entries(original));
|
||||
const after = new Map(Object.entries(edited));
|
||||
return [...new Set([...before.keys(), ...after.keys()])]
|
||||
.filter(
|
||||
(field) =>
|
||||
!RUNTIME_CONFIG_EMERGENCY_SWITCHES.has(field) &&
|
||||
JSON.stringify(before.get(field)) !== JSON.stringify(after.get(field)),
|
||||
)
|
||||
.sort();
|
||||
}
|
||||
@@ -99,11 +99,20 @@ if (liveTarget?.passed && !slotEmpty) {
|
||||
),
|
||||
);
|
||||
const candidateManifest = await readFile(path.join(distRoot, "release-manifest.json"), "utf8").catch(() => null);
|
||||
const candidate = releaseIdentity(candidateManifest);
|
||||
if (!candidate) {
|
||||
const identity = releaseIdentity(candidateManifest);
|
||||
if (!identity) {
|
||||
throw new Error(`${distRoot}/release-manifest.json does not name a buildId and releaseId`);
|
||||
}
|
||||
const probed = await probeLiveRelease(liveTarget.url, paths, candidate);
|
||||
// 1103/13-01. The served config.json and index.html are compared with the
|
||||
// candidate's, not only the manifest names a rebuild in the same run shares.
|
||||
const candidate = {
|
||||
...identity,
|
||||
runtimeConfig: await readFile(path.join(distRoot, "config.json"), "utf8"),
|
||||
indexHtml: await readFile(path.join(distRoot, "index.html"), "utf8"),
|
||||
};
|
||||
const probed = await probeLiveRelease(liveTarget.url, paths, candidate, {
|
||||
alpnProtocols: strings(recordValue(cachePolicy.transport).alpnProtocols),
|
||||
});
|
||||
responses = probed.responses;
|
||||
probeResults.push(...probed.results);
|
||||
} else if (liveTarget && !liveTarget.passed) {
|
||||
@@ -148,6 +157,19 @@ for (const [surface, policy] of requiredSurfaces) {
|
||||
observed: observedContentType,
|
||||
passed: observedMime !== undefined && contentTypes.includes(observedMime),
|
||||
});
|
||||
// 1103/13-02. The bundle budget counts gzip bytes. The probe's fetch offers
|
||||
// br and gzip, so an uncompressed answer is the host's choice.
|
||||
const contentEncodings = strings(policy.contentEncodings);
|
||||
if (contentEncodings.length > 0) {
|
||||
const observedEncoding = responses[surface]?.["content-encoding"];
|
||||
results.push({
|
||||
surface,
|
||||
header: "content-encoding",
|
||||
expected: contentEncodings,
|
||||
observed: observedEncoding,
|
||||
passed: observedEncoding !== undefined && contentEncodings.includes(observedEncoding.trim().toLowerCase()),
|
||||
});
|
||||
}
|
||||
if (policy.securityHeaders === true) {
|
||||
for (const [header, expected] of Object.entries(securityHeaders)) {
|
||||
const observedSecurity = responses[surface]?.[header.toLowerCase()];
|
||||
|
||||
@@ -150,11 +150,21 @@ describe("SPA fallback and worker script surfaces (1101/13-04)", () => {
|
||||
releaseManifest: "/release-manifest.json",
|
||||
appRoute: "/__probe/deep-link",
|
||||
};
|
||||
const CANDIDATE = { buildId: "gitea-42-1", releaseId: "refs/tags/v1.2.0-42-1" };
|
||||
const IDENTITY = { buildId: "gitea-42-1", releaseId: "refs/tags/v1.2.0-42-1" };
|
||||
const CONFIG = JSON.stringify({
|
||||
APP_ENV: "production",
|
||||
AUTH_MODE: "external",
|
||||
API_BASE_URL: "https://api.frontend.example.test/",
|
||||
BUILD_ID: IDENTITY.buildId,
|
||||
RELEASE_ID: IDENTITY.releaseId,
|
||||
CAPABILITY_OVERRIDES: {},
|
||||
FEATURE_OVERRIDES: {},
|
||||
});
|
||||
const CANDIDATE = { ...IDENTITY, runtimeConfig: CONFIG, indexHtml: INDEX };
|
||||
const RELEASE: Record<string, [number, string]> = {
|
||||
"/": [200, INDEX],
|
||||
"/config.json": [200, "{}"],
|
||||
"/release-manifest.json": [200, JSON.stringify({ schemaVersion: 2, ...CANDIDATE })],
|
||||
"/config.json": [200, CONFIG],
|
||||
"/release-manifest.json": [200, JSON.stringify({ schemaVersion: 2, ...IDENTITY })],
|
||||
"/assets/index-A1.js": [200, ""],
|
||||
};
|
||||
const host = (routes: Record<string, [number, string]>) => async (url: URL) => {
|
||||
@@ -164,8 +174,14 @@ describe("SPA fallback and worker script surfaces (1101/13-04)", () => {
|
||||
return response;
|
||||
};
|
||||
const base = new URL("https://frontend.example.test/");
|
||||
const failed = async (routes: Record<string, [number, string]>) =>
|
||||
(await probeLiveRelease(base, PATHS, CANDIDATE, host(routes))).results
|
||||
const probe = (routes: Record<string, [number, string]>, alpn: string | null = "h2") =>
|
||||
probeLiveRelease(base, PATHS, CANDIDATE, {
|
||||
fetcher: host(routes),
|
||||
negotiateAlpn: async () => alpn,
|
||||
alpnProtocols: ["h2"],
|
||||
});
|
||||
const failed = async (routes: Record<string, [number, string]>, alpn?: string | null) =>
|
||||
(await probe(routes, alpn)).results
|
||||
.filter((result) => !result.passed)
|
||||
.map((result) => `${result.surface} ${result.header}`);
|
||||
|
||||
@@ -196,6 +212,72 @@ describe("SPA fallback and worker script surfaces (1101/13-04)", () => {
|
||||
).toEqual(["releaseManifest build-id", "releaseManifest release-id"]);
|
||||
});
|
||||
|
||||
// 1103/13-01. The manifest names come from the CI run, so a release rebuilt
|
||||
// in the same run with the local profile (APP_ENV=local, AUTH_MODE=demo, a
|
||||
// loopback API) passed. The candidate's config.json is the one release
|
||||
// admission (FE-GATE-027) admitted, so the served one must equal it.
|
||||
it("fails a host whose config.json is not the candidate's", async () => {
|
||||
const local = JSON.stringify({
|
||||
...JSON.parse(CONFIG),
|
||||
APP_ENV: "local",
|
||||
AUTH_MODE: "demo",
|
||||
API_BASE_URL: "http://localhost:8080/",
|
||||
});
|
||||
const { results } = await probe({
|
||||
...RELEASE,
|
||||
"/__probe/deep-link": [200, INDEX],
|
||||
"/config.json": [200, local],
|
||||
});
|
||||
expect(results.filter(({ passed }) => !passed)).toEqual([
|
||||
expect.objectContaining({
|
||||
surface: "runtimeConfig",
|
||||
header: "build-fields",
|
||||
observed: ["API_BASE_URL", "APP_ENV", "AUTH_MODE"],
|
||||
}),
|
||||
]);
|
||||
});
|
||||
|
||||
// FE-RB-001 changes the two emergency switches without a rebuild; the
|
||||
// probe after it must still pass.
|
||||
it("passes a host whose config.json differs only in the emergency switches", async () => {
|
||||
const switched = JSON.stringify({
|
||||
...JSON.parse(CONFIG),
|
||||
CAPABILITY_OVERRIDES: { realtime: "DISABLED" },
|
||||
FEATURE_OVERRIDES: { "reference-feature": false },
|
||||
});
|
||||
expect(
|
||||
await failed({ ...RELEASE, "/__probe/deep-link": [200, INDEX], "/config.json": [200, switched] }),
|
||||
).toEqual([]);
|
||||
});
|
||||
|
||||
it("fails a host whose config.json is unreadable", async () => {
|
||||
expect(
|
||||
await failed({ ...RELEASE, "/__probe/deep-link": [200, INDEX], "/config.json": [200, "<html>"] }),
|
||||
).toEqual(["runtimeConfig build-fields"]);
|
||||
});
|
||||
|
||||
// 1103/13-01. A build of other sources under the same run names serves its
|
||||
// own entry script; the fallback check compared the host only with itself.
|
||||
it("fails a host whose index.html names another entry script than the candidate's", async () => {
|
||||
const other = '<script type="module" src="/assets/index-B2.js"></script>';
|
||||
expect(
|
||||
await failed({
|
||||
...RELEASE,
|
||||
"/": [200, other],
|
||||
"/__probe/deep-link": [200, other],
|
||||
"/assets/index-B2.js": [200, ""],
|
||||
}),
|
||||
).toEqual(["index candidate-entry-script"]);
|
||||
});
|
||||
|
||||
// 1103/13-02. The split initial chunks assume HTTP/2
|
||||
// (docs/architecture/static-delivery.md); over HTTP/1.1 they queue.
|
||||
it("fails a host that does not negotiate a declared protocol", async () => {
|
||||
const release: Record<string, [number, string]> = { ...RELEASE, "/__probe/deep-link": [200, INDEX] };
|
||||
expect(await failed(release, "http/1.1")).toEqual(["transport alpn"]);
|
||||
expect(await failed(release, null)).toEqual(["transport alpn"]);
|
||||
});
|
||||
|
||||
it("fails when the served release manifest is unreadable", async () => {
|
||||
expect(
|
||||
await failed({
|
||||
@@ -213,6 +295,7 @@ describe("verify-hosting-headers on a promoted release root (1101/13-01)", () =>
|
||||
async function verify(
|
||||
distFiles: Readonly<Record<string, string>>,
|
||||
env: Readonly<Record<string, string>> = {},
|
||||
editFixture?: (responses: Record<string, Record<string, string>>) => void,
|
||||
) {
|
||||
const root = await mkdtemp(path.join(tmpdir(), "hosting-release-root-"));
|
||||
try {
|
||||
@@ -220,6 +303,14 @@ describe("verify-hosting-headers on a promoted release root (1101/13-01)", () =>
|
||||
for (const file of ["cache-policy.json", "security-headers.json", "response-headers.fixture.json"]) {
|
||||
await copyFile(`config/hosting/${file}`, path.join(root, "config/hosting", file));
|
||||
}
|
||||
if (editFixture) {
|
||||
const fixturePath = path.join(root, "config/hosting/response-headers.fixture.json");
|
||||
const fixture = JSON.parse(await readFile(fixturePath, "utf8")) as {
|
||||
responses: Record<string, Record<string, string>>;
|
||||
};
|
||||
editFixture(fixture.responses);
|
||||
await writeFile(fixturePath, JSON.stringify(fixture));
|
||||
}
|
||||
for (const [file, content] of Object.entries(distFiles)) {
|
||||
await mkdir(path.dirname(path.join(root, "candidate/dist", file)), { recursive: true });
|
||||
await writeFile(path.join(root, "candidate/dist", file), content);
|
||||
@@ -269,4 +360,25 @@ describe("verify-hosting-headers on a promoted release root (1101/13-01)", () =>
|
||||
expect(result.status).toBe(3);
|
||||
expect(result.stderr).toContain("deployment slot");
|
||||
});
|
||||
|
||||
// 1103/13-02. The bundle budget counts gzip bytes; an uncompressed entry
|
||||
// script means about three times as many bytes on the wire.
|
||||
it("declares compression for hashed assets and HTTP/2 for the host", async () => {
|
||||
const policy = JSON.parse(await readFile("config/hosting/cache-policy.json", "utf8")) as {
|
||||
transport?: { alpnProtocols?: string[] };
|
||||
surfaces: Record<string, { contentEncodings?: string[] }>;
|
||||
};
|
||||
expect(policy.transport?.alpnProtocols).toEqual(["h2"]);
|
||||
expect(policy.surfaces["hashedAsset"]?.contentEncodings).toEqual(
|
||||
expect.arrayContaining(["br", "gzip"]),
|
||||
);
|
||||
});
|
||||
|
||||
it("fails a hashed asset served without a declared content encoding", async () => {
|
||||
const result = await verify(DIST, {}, (responses) => {
|
||||
delete responses["hashedAsset"]?.["content-encoding"];
|
||||
});
|
||||
expect(result.failed, result.stderr).toEqual(["hashedAsset content-encoding"]);
|
||||
expect(result.status).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
Reference in New Issue
Block a user