feat(local): plan secret config reconciliation

This commit is contained in:
whyour
2026-08-23 16:13:47 +08:00
parent dbd219bedc
commit fbb67ff5c8
10 changed files with 1035 additions and 92 deletions
@@ -232,6 +232,31 @@ function selectSql(schema: ReadonlySet<string>): string {
ORDER BY ${pinned} DESC, ${position} DESC, ${createdAt} ASC, "id" ASC`;
}
function* iterateRows(
client: DatabaseSync,
schema: ReadonlySet<string>,
): Iterable<LegacyRow> {
let iterator: Iterator<Record<string, unknown>>;
try {
iterator = client
.prepare(selectSql(schema))
.iterate()
[Symbol.iterator]() as Iterator<Record<string, unknown>>;
} catch (error) {
throw new LegacyEnvironmentInspectionError('rows are unavailable', error);
}
for (;;) {
let next: IteratorResult<Record<string, unknown>>;
try {
next = iterator.next();
} catch (error) {
throw new LegacyEnvironmentInspectionError('rows cannot be read', error);
}
if (next.done) return;
yield next.value as LegacyRow;
}
}
function reasons(row: LegacyRow): readonly LegacyEnvironmentRowReason[] {
const selected: LegacyEnvironmentRowReason[] = [];
if (!Number.isSafeInteger(row.id) || (row.id as number) < 1) {
@@ -361,86 +386,76 @@ export function visitLegacyEnvironmentAdoption(
let preservationReadyCount = 0;
let activeValueBytes = 0;
try {
for (const raw of client
.prepare(selectSql(schema))
.iterate() as Iterable<LegacyRow>) {
rowOrdinal += 1;
const digestValue = sourceDigest(raw);
const rowReasons = reasons(raw);
let disposition: LegacyEnvironmentRowDisposition = 'manual_required';
if (rowReasons.length === 0 && raw.status === 0) {
disposition = 'active_member';
activeRowCount += 1;
} else if (rowReasons.length === 0 && raw.status === 1) {
disposition = 'preserve_disabled';
disabledRowCount += 1;
preservationReadyCount += 1;
} else {
manualRowCount += 1;
if (raw.status === 0) activeRowCount += 1;
if (raw.status === 1) disabledRowCount += 1;
}
const inspection = Object.freeze({
rowOrdinal,
sourceDigest: digestValue,
disposition,
reasons: rowReasons,
});
options.visitRow?.(inspection);
inventoryHash.update('\0row\0').update(JSON.stringify(inspection));
for (const raw of iterateRows(client, schema)) {
rowOrdinal += 1;
const digestValue = sourceDigest(raw);
const rowReasons = reasons(raw);
let disposition: LegacyEnvironmentRowDisposition = 'manual_required';
if (rowReasons.length === 0 && raw.status === 0) {
disposition = 'active_member';
activeRowCount += 1;
} else if (rowReasons.length === 0 && raw.status === 1) {
disposition = 'preserve_disabled';
disabledRowCount += 1;
preservationReadyCount += 1;
} else {
manualRowCount += 1;
if (raw.status === 0) activeRowCount += 1;
if (raw.status === 1) disabledRowCount += 1;
}
const inspection = Object.freeze({
rowOrdinal,
sourceDigest: digestValue,
disposition,
reasons: rowReasons,
});
options.visitRow?.(inspection);
inventoryHash.update('\0row\0').update(JSON.stringify(inspection));
if (raw.status !== 0) continue;
if (
typeof raw.name !== 'string' ||
!ENVIRONMENT_NAME.test(raw.name) ||
raw.name.startsWith('QL3_')
) {
invalidActiveGroupDigests.add(
digest(
'qinglong3.legacy-environment-invalid-name.v1',
scalarEvidence(raw.name),
),
);
continue;
}
let group = groups.get(raw.name);
if (!group) {
group = {
name: raw.name,
rowDigests: [],
values: [],
valueBytes: 0,
valid: true,
};
groups.set(raw.name, group);
}
group.rowDigests.push(digestValue);
if (rowReasons.length > 0 || typeof raw.value !== 'string') {
group.valid = false;
group.values.length = 0;
continue;
}
const valueBytes = Buffer.byteLength(raw.value, 'utf8');
const separatorBytes = group.values.length === 0 ? 0 : 1;
group.valueBytes += valueBytes + separatorBytes;
activeValueBytes += valueBytes + separatorBytes;
if (
group.valueBytes > MAX_LEGACY_ENVIRONMENT_VALUE_BYTES ||
activeValueBytes > MAX_LEGACY_ENVIRONMENT_EFFECTIVE_BYTES
) {
group.valid = false;
group.values.length = 0;
} else if (group.valid) {
group.values.push(raw.value);
}
if (raw.status !== 0) continue;
if (
typeof raw.name !== 'string' ||
!ENVIRONMENT_NAME.test(raw.name) ||
raw.name.startsWith('QL3_')
) {
invalidActiveGroupDigests.add(
digest(
'qinglong3.legacy-environment-invalid-name.v1',
scalarEvidence(raw.name),
),
);
continue;
}
let group = groups.get(raw.name);
if (!group) {
group = {
name: raw.name,
rowDigests: [],
values: [],
valueBytes: 0,
valid: true,
};
groups.set(raw.name, group);
}
group.rowDigests.push(digestValue);
if (rowReasons.length > 0 || typeof raw.value !== 'string') {
group.valid = false;
group.values.length = 0;
continue;
}
const valueBytes = Buffer.byteLength(raw.value, 'utf8');
const separatorBytes = group.values.length === 0 ? 0 : 1;
group.valueBytes += valueBytes + separatorBytes;
activeValueBytes += valueBytes + separatorBytes;
if (
group.valueBytes > MAX_LEGACY_ENVIRONMENT_VALUE_BYTES ||
activeValueBytes > MAX_LEGACY_ENVIRONMENT_EFFECTIVE_BYTES
) {
group.valid = false;
group.values.length = 0;
} else if (group.valid) {
group.values.push(raw.value);
}
} catch (error) {
if (error instanceof LegacyEnvironmentInspectionError) throw error;
throw new LegacyEnvironmentInspectionError(
'rows cannot be inspected',
error,
);
}
if (rowOrdinal !== count) {
throw new LegacyEnvironmentInspectionError('row count drifted');
@@ -488,9 +503,7 @@ export function visitLegacyEnvironmentAdoption(
if (!globalBudgetExceeded && preservationReadyCount > 0) {
rowOrdinal = 0;
for (const raw of client
.prepare(selectSql(schema))
.iterate() as Iterable<LegacyRow>) {
for (const raw of iterateRows(client, schema)) {
rowOrdinal += 1;
if (raw.status !== 1 || reasons(raw).length !== 0) continue;
const digestValue = sourceDigest(raw);
@@ -212,3 +212,34 @@ test('rejects unsupported schemas and over-budget Edge tables without scanning r
overBudget.close();
}
});
test('preserves a visitor failure instead of disguising it as a SQLite read error', () => {
const database = memoryDatabase(`
CREATE TABLE "Envs" (
id INTEGER PRIMARY KEY,
name TEXT,
value TEXT,
status INTEGER,
position REAL,
"isPinned" INTEGER,
"createdAt" TEXT
);
INSERT INTO "Envs" VALUES
(1, 'TOKEN', 'private-value', 0, 1, 0, '2026-01-01');
`);
const expected = new Error('caller byte budget exceeded');
try {
assert.throws(
() =>
visitLegacyEnvironmentAdoption(database, {
profile: 'edge',
visitRow() {
throw expected;
},
}),
(error) => error === expected,
);
} finally {
database.close();
}
});
@@ -0,0 +1,597 @@
import { createHash } from 'node:crypto';
import fs from 'node:fs';
import type { DatabaseSync } from 'node:sqlite';
import {
visitLegacyEnvironmentAdoption,
type LegacyEnvironmentCandidate,
type LegacyEnvironmentInventory,
type LegacyEnvironmentRowInspection,
} from '@qinglong/local-admin/reconciliation-secret-and-config-inspection';
import { LocalDeploymentConfigurationError } from '../../../foundation/error';
import { cutoverDigest } from '../../../cutover/targetEvidence';
const HEADER_KIND = 'qinglong3-local-reconciliation-secret-config-plan-header';
const ROW_KIND = 'qinglong3-local-reconciliation-secret-config-plan-row';
const CANDIDATE_KIND =
'qinglong3-local-reconciliation-secret-config-plan-candidate';
const FOOTER_KIND = 'qinglong3-local-reconciliation-secret-config-plan-footer';
const RECEIPT_SCHEMA =
'qinglong3-local-reconciliation-secret-config-plan-receipt';
const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
const UUID_V4_PATTERN =
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
const MAX_LINE_BYTES = 64 * 1024;
const HASH_BUFFER_BYTES = 64 * 1024;
export const MAX_EDGE_LOCAL_RECONCILIATION_SECRET_CONFIG_PLAN_BYTES =
8 * 1024 * 1024;
export const MAX_STANDALONE_LOCAL_RECONCILIATION_SECRET_CONFIG_PLAN_BYTES =
32 * 1024 * 1024;
export interface LocalReconciliationSecretConfigPlanHeader {
readonly schemaVersion: 1;
readonly kind: typeof HEADER_KIND;
readonly secretConfigId: string;
readonly applicationId: string;
readonly applicationPlanDigest: string;
readonly reviewDigest: string;
readonly reviewAuthorizationDigest: string;
readonly reviewDecisionSetDigest: string;
readonly reviewDecisionFileDigest: string;
readonly bundleDigest: string;
readonly bundleFingerprintDigest: string;
readonly profile: 'edge' | 'standalone';
readonly projectId: string;
readonly tableDisposition: 'adopt_legacy' | 'retain_both';
readonly preparedHeadDigest: string;
readonly preparedAtMs: number;
readonly headerDigest: string;
}
export interface LocalReconciliationSecretConfigPlanRow {
readonly schemaVersion: 1;
readonly kind: typeof ROW_KIND;
readonly rowOrdinal: number;
readonly sourceDigest: string;
readonly disposition: LegacyEnvironmentRowInspection['disposition'];
readonly reasons: LegacyEnvironmentRowInspection['reasons'];
readonly rowPlanDigest: string;
}
export type LocalReconciliationSecretConfigCandidateRequirement =
| 'review_apply_binding'
| 'review_preserve_disabled'
| 'review_skip_conflict';
export type LocalReconciliationSecretConfigTarget =
| Readonly<{ state: 'absent' }>
| Readonly<{
state: 'occupied';
version: number;
contentDigest: string;
}>;
export interface LocalReconciliationSecretConfigPlanCandidate {
readonly schemaVersion: 1;
readonly kind: typeof CANDIDATE_KIND;
readonly candidateOrdinal: number;
readonly candidateType: LegacyEnvironmentCandidate['kind'];
readonly candidateDigest: string;
readonly sourceRowCount: number;
readonly sourceSetDigest: string;
readonly proposedSecretName: string;
readonly target: LocalReconciliationSecretConfigTarget;
readonly requirement: LocalReconciliationSecretConfigCandidateRequirement;
readonly candidatePlanDigest: string;
}
export interface LocalReconciliationSecretConfigPlanSummary {
readonly tableState: LegacyEnvironmentInventory['tableState'];
readonly rowCount: number;
readonly activeRowCount: number;
readonly disabledRowCount: number;
readonly manualRowCount: number;
readonly activeGroupCount: number;
readonly bindingReadyCount: number;
readonly preservationReadyCount: number;
readonly manualGroupCount: number;
readonly eligibleBindingCount: number;
readonly eligiblePreservationCount: number;
readonly targetConflictCount: number;
readonly outcome: 'ready' | 'manual_required' | 'no_effect';
}
export interface LocalReconciliationSecretConfigPlanFooter
extends LocalReconciliationSecretConfigPlanSummary {
readonly schemaVersion: 1;
readonly kind: typeof FOOTER_KIND;
readonly secretConfigId: string;
readonly legacyInventoryDigest: string;
readonly rowSetDigest: string;
readonly candidateSetDigest: string;
readonly secretConfigPlanDigest: string;
}
export interface LocalReconciliationSecretConfigPlanReceipt
extends LocalReconciliationSecretConfigPlanSummary {
readonly schema: typeof RECEIPT_SCHEMA;
readonly schemaVersion: 1;
readonly state: 'reconciliation_secret_config_planned';
readonly secretConfigId: string;
readonly applicationId: string;
readonly applicationPlanDigest: string;
readonly preparedHeadDigest: string;
readonly legacyInventoryDigest: string;
readonly rowSetDigest: string;
readonly candidateSetDigest: string;
readonly secretConfigPlanDigest: string;
readonly planFileBytes: number;
readonly planFileDigest: string;
readonly preparedAtMs: number;
readonly receiptDigest: string;
}
export interface WriteLocalReconciliationSecretConfigPlanOptions {
readonly descriptor: number;
readonly maxBytes: number;
readonly header: Omit<
LocalReconciliationSecretConfigPlanHeader,
'headerDigest'
>;
readonly legacy: DatabaseSync;
readonly target: DatabaseSync;
}
function fail(message: string, cause?: unknown): never {
throw new LocalDeploymentConfigurationError(
`reconciliation secret config row plan ${message}`,
{ cause },
);
}
function exact(
value: unknown,
keys: readonly string[],
label: string,
): Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value)) {
fail(`${label} must be an object`);
}
const record = value as Record<string, unknown>;
const actual = Object.keys(record).sort();
const expected = [...keys].sort();
if (
actual.length !== expected.length ||
actual.some((key, index) => key !== expected[index])
) {
fail(`${label} shape is invalid`);
}
return record;
}
function line(value: unknown): Buffer {
const bytes = Buffer.from(`${JSON.stringify(value)}\n`, 'utf8');
if (bytes.byteLength < 3 || bytes.byteLength > MAX_LINE_BYTES + 1) {
bytes.fill(0);
fail('record exceeds its line bound');
}
return bytes;
}
function writeAll(descriptor: number, bytes: Buffer): void {
let offset = 0;
while (offset < bytes.byteLength) {
const written = fs.writeSync(
descriptor,
bytes,
offset,
bytes.byteLength - offset,
);
if (written < 1) fail('write stalled');
offset += written;
}
}
function bytesDigest(value: unknown, length: number, label: string): string {
if (!(value instanceof Uint8Array) || value.byteLength !== length) {
fail(`target ${label} is invalid`);
}
return createHash('sha256').update(value).digest('hex');
}
function targetSecret(
target: DatabaseSync,
projectId: string,
secretName: string,
): LocalReconciliationSecretConfigTarget {
let row: Readonly<Record<string, unknown>> | undefined;
try {
row = target
.prepare(
`SELECT "version", "mutation_id" AS "mutationId",
"key_id" AS "keyId", "algorithm", "nonce", "ciphertext",
"auth_tag" AS "authTag", "created_at_ms" AS "createdAtMs"
FROM "QingLong3LocalSecretEnvelopes"
WHERE "project_id" = ? AND "secret_name" = ?
ORDER BY "version" DESC LIMIT 1`,
)
.get(projectId, secretName) as
| Readonly<Record<string, unknown>>
| undefined;
} catch (error) {
return fail('target Secret projection is unavailable', error);
}
if (!row) return Object.freeze({ state: 'absent' as const });
if (
!Number.isSafeInteger(row.version) ||
(row.version as number) < 1 ||
typeof row.mutationId !== 'string' ||
row.mutationId.length < 1 ||
row.mutationId.length > 64 ||
typeof row.keyId !== 'string' ||
row.keyId.length < 1 ||
row.keyId.length > 128 ||
row.algorithm !== 'aes-256-gcm' ||
!Number.isSafeInteger(row.createdAtMs) ||
(row.createdAtMs as number) < 0
) {
fail('target Secret projection drifted');
}
if (
!(row.ciphertext instanceof Uint8Array) ||
row.ciphertext.byteLength > 16 * 1024
) {
fail('target ciphertext is invalid');
}
const contentDigest = cutoverDigest({
projectId,
secretName,
version: row.version,
mutationId: row.mutationId,
keyId: row.keyId,
algorithm: row.algorithm,
nonceDigest: bytesDigest(row.nonce, 12, 'nonce'),
ciphertextDigest: bytesDigest(
row.ciphertext,
row.ciphertext.byteLength,
'ciphertext',
),
authTagDigest: bytesDigest(row.authTag, 16, 'auth tag'),
createdAtMs: row.createdAtMs,
});
return Object.freeze({
state: 'occupied' as const,
version: row.version as number,
contentDigest,
});
}
function secretName(candidate: Readonly<LegacyEnvironmentCandidate>): string {
const source =
candidate.kind === 'active_binding'
? candidate.environmentName
: `${candidate.environmentName}\0${candidate.sourceDigest}`;
const suffix = createHash('sha256').update(source).digest('hex').slice(0, 32);
return candidate.kind === 'active_binding'
? `legacy-db-env-${suffix}`
: `legacy-db-env-disabled-${suffix}`;
}
function planRow(
value: Readonly<LegacyEnvironmentRowInspection>,
): Readonly<LocalReconciliationSecretConfigPlanRow> {
const payload = Object.freeze({
schemaVersion: 1 as const,
kind: ROW_KIND,
rowOrdinal: value.rowOrdinal,
sourceDigest: value.sourceDigest,
disposition: value.disposition,
reasons: value.reasons,
});
return Object.freeze({ ...payload, rowPlanDigest: cutoverDigest(payload) });
}
function planCandidate(
value: Readonly<LegacyEnvironmentCandidate>,
candidateOrdinal: number,
target: DatabaseSync,
projectId: string,
): Readonly<LocalReconciliationSecretConfigPlanCandidate> {
const proposedSecretName = secretName(value);
const selectedTarget = targetSecret(target, projectId, proposedSecretName);
const sourceRowCount =
value.kind === 'active_binding' ? value.sourceRowCount : 1;
const sourceSetDigest =
value.kind === 'active_binding'
? value.sourceSetDigest
: value.sourceDigest;
const requirement: LocalReconciliationSecretConfigCandidateRequirement =
selectedTarget.state === 'occupied'
? 'review_skip_conflict'
: value.kind === 'active_binding'
? 'review_apply_binding'
: 'review_preserve_disabled';
const payload = Object.freeze({
schemaVersion: 1 as const,
kind: CANDIDATE_KIND,
candidateOrdinal,
candidateType: value.kind,
candidateDigest: value.candidateDigest,
sourceRowCount,
sourceSetDigest,
proposedSecretName,
target: selectedTarget,
requirement,
});
return Object.freeze({
...payload,
candidatePlanDigest: cutoverDigest(payload),
});
}
export function writeLocalReconciliationSecretConfigPlan(
options: Readonly<WriteLocalReconciliationSecretConfigPlanOptions>,
): Readonly<{
header: Readonly<LocalReconciliationSecretConfigPlanHeader>;
footer: Readonly<LocalReconciliationSecretConfigPlanFooter>;
fileBytes: number;
fileDigest: string;
}> {
if (
!Number.isSafeInteger(options.maxBytes) ||
options.maxBytes < MAX_LINE_BYTES
) {
fail('byte budget is invalid');
}
const header = Object.freeze({
...options.header,
headerDigest: cutoverDigest(options.header),
});
const fileHash = createHash('sha256');
const rowHash = createHash('sha256').update(
'qinglong3.local-reconciliation-secret-config-row-set.v1\0',
);
const candidateHash = createHash('sha256').update(
'qinglong3.local-reconciliation-secret-config-candidate-set.v1\0',
);
let fileBytes = 0;
const append = (
value: unknown,
set: 'none' | 'row' | 'candidate' = 'none',
): void => {
const bytes = line(value);
try {
if (fileBytes + bytes.byteLength > options.maxBytes) {
fail('exceeds profile byte budget');
}
writeAll(options.descriptor, bytes);
fileHash.update(bytes);
if (set === 'row') rowHash.update(bytes);
if (set === 'candidate') candidateHash.update(bytes);
fileBytes += bytes.byteLength;
} finally {
bytes.fill(0);
}
};
append(header);
let candidateOrdinal = 0;
let eligibleBindingCount = 0;
let eligiblePreservationCount = 0;
let targetConflictCount = 0;
const inventory = visitLegacyEnvironmentAdoption(options.legacy, {
profile: header.profile,
visitRow(value) {
append(planRow(value), 'row');
},
visitCandidate(value) {
candidateOrdinal += 1;
const candidate = planCandidate(
value,
candidateOrdinal,
options.target,
header.projectId,
);
if (candidate.requirement === 'review_apply_binding') {
eligibleBindingCount += 1;
} else if (candidate.requirement === 'review_preserve_disabled') {
eligiblePreservationCount += 1;
} else {
targetConflictCount += 1;
}
append(candidate, 'candidate');
},
});
const summary: LocalReconciliationSecretConfigPlanSummary = Object.freeze({
tableState: inventory.tableState,
rowCount: inventory.rowCount,
activeRowCount: inventory.activeRowCount,
disabledRowCount: inventory.disabledRowCount,
manualRowCount: inventory.manualRowCount,
activeGroupCount: inventory.activeGroupCount,
bindingReadyCount: inventory.bindingReadyCount,
preservationReadyCount: inventory.preservationReadyCount,
manualGroupCount: inventory.manualGroupCount,
eligibleBindingCount,
eligiblePreservationCount,
targetConflictCount,
outcome:
inventory.tableState === 'absent' || inventory.rowCount === 0
? ('no_effect' as const)
: !inventory.mutationReady || targetConflictCount > 0
? ('manual_required' as const)
: ('ready' as const),
});
const footerPayload = Object.freeze({
schemaVersion: 1 as const,
kind: FOOTER_KIND,
secretConfigId: header.secretConfigId,
...summary,
legacyInventoryDigest: inventory.inventoryDigest,
rowSetDigest: rowHash.digest('hex'),
candidateSetDigest: candidateHash.digest('hex'),
});
const footer = Object.freeze({
...footerPayload,
secretConfigPlanDigest: cutoverDigest({
headerDigest: header.headerDigest,
...footerPayload,
}),
});
append(footer);
return Object.freeze({
header,
footer,
fileBytes,
fileDigest: fileHash.digest('hex'),
});
}
export function buildLocalReconciliationSecretConfigPlanReceipt(
header: Readonly<LocalReconciliationSecretConfigPlanHeader>,
footer: Readonly<LocalReconciliationSecretConfigPlanFooter>,
planFileBytes: number,
planFileDigest: string,
): Readonly<LocalReconciliationSecretConfigPlanReceipt> {
const payload = Object.freeze({
schema: RECEIPT_SCHEMA,
schemaVersion: 1 as const,
state: 'reconciliation_secret_config_planned' as const,
secretConfigId: header.secretConfigId,
applicationId: header.applicationId,
applicationPlanDigest: header.applicationPlanDigest,
preparedHeadDigest: header.preparedHeadDigest,
legacyInventoryDigest: footer.legacyInventoryDigest,
rowSetDigest: footer.rowSetDigest,
candidateSetDigest: footer.candidateSetDigest,
secretConfigPlanDigest: footer.secretConfigPlanDigest,
planFileBytes,
planFileDigest,
tableState: footer.tableState,
rowCount: footer.rowCount,
activeRowCount: footer.activeRowCount,
disabledRowCount: footer.disabledRowCount,
manualRowCount: footer.manualRowCount,
activeGroupCount: footer.activeGroupCount,
bindingReadyCount: footer.bindingReadyCount,
preservationReadyCount: footer.preservationReadyCount,
manualGroupCount: footer.manualGroupCount,
eligibleBindingCount: footer.eligibleBindingCount,
eligiblePreservationCount: footer.eligiblePreservationCount,
targetConflictCount: footer.targetConflictCount,
outcome: footer.outcome,
preparedAtMs: header.preparedAtMs,
});
return Object.freeze({ ...payload, receiptDigest: cutoverDigest(payload) });
}
export function normalizeLocalReconciliationSecretConfigPlanReceipt(
value: unknown,
): Readonly<LocalReconciliationSecretConfigPlanReceipt> {
const receipt = exact(
value,
[
'activeGroupCount',
'activeRowCount',
'applicationId',
'applicationPlanDigest',
'bindingReadyCount',
'candidateSetDigest',
'disabledRowCount',
'eligibleBindingCount',
'eligiblePreservationCount',
'legacyInventoryDigest',
'manualGroupCount',
'manualRowCount',
'outcome',
'planFileBytes',
'planFileDigest',
'preparedAtMs',
'preparedHeadDigest',
'preservationReadyCount',
'receiptDigest',
'rowCount',
'rowSetDigest',
'schema',
'schemaVersion',
'secretConfigId',
'secretConfigPlanDigest',
'state',
'tableState',
'targetConflictCount',
],
'receipt',
);
const { receiptDigest, ...payload } = receipt;
if (
receipt.schema !== RECEIPT_SCHEMA ||
receipt.schemaVersion !== 1 ||
receipt.state !== 'reconciliation_secret_config_planned' ||
typeof receipt.secretConfigId !== 'string' ||
!UUID_V4_PATTERN.test(receipt.secretConfigId) ||
typeof receipt.applicationId !== 'string' ||
!UUID_V4_PATTERN.test(receipt.applicationId) ||
![
receipt.applicationPlanDigest,
receipt.preparedHeadDigest,
receipt.legacyInventoryDigest,
receipt.rowSetDigest,
receipt.candidateSetDigest,
receipt.secretConfigPlanDigest,
receipt.planFileDigest,
receiptDigest,
].every(
(candidate) =>
typeof candidate === 'string' && DIGEST_PATTERN.test(candidate),
) ||
![
receipt.rowCount,
receipt.activeRowCount,
receipt.disabledRowCount,
receipt.manualRowCount,
receipt.activeGroupCount,
receipt.bindingReadyCount,
receipt.preservationReadyCount,
receipt.manualGroupCount,
receipt.eligibleBindingCount,
receipt.eligiblePreservationCount,
receipt.targetConflictCount,
receipt.planFileBytes,
receipt.preparedAtMs,
].every((count) => Number.isSafeInteger(count) && (count as number) >= 0) ||
!['absent', 'supported', 'unsupported_schema', 'budget_exceeded'].includes(
receipt.tableState as string,
) ||
!['ready', 'manual_required', 'no_effect'].includes(
receipt.outcome as string,
) ||
cutoverDigest(payload) !== receiptDigest
) {
fail('receipt drifted');
}
return Object.freeze(
receipt,
) as unknown as Readonly<LocalReconciliationSecretConfigPlanReceipt>;
}
export function hashLocalReconciliationSecretConfigPlanFile(
descriptor: number,
expectedBytes: number,
): string {
const hash = createHash('sha256');
const buffer = Buffer.allocUnsafe(HASH_BUFFER_BYTES);
let offset = 0;
while (offset < expectedBytes) {
const count = fs.readSync(
descriptor,
buffer,
0,
Math.min(buffer.byteLength, expectedBytes - offset),
offset,
);
if (count < 1) fail('plan file read stalled');
hash.update(buffer.subarray(0, count));
offset += count;
}
return hash.digest('hex');
}
@@ -0,0 +1,253 @@
const assert = require('node:assert/strict');
const fs = require('node:fs');
const os = require('node:os');
const path = require('node:path');
const { DatabaseSync } = require('node:sqlite');
const { test } = require('node:test');
const {
buildLocalReconciliationSecretConfigPlanReceipt,
hashLocalReconciliationSecretConfigPlanFile,
normalizeLocalReconciliationSecretConfigPlanReceipt,
writeLocalReconciliationSecretConfigPlan,
} = require('../dist/deployment/reconciliation/application/secret-and-config/rowPlan');
const DIGEST = 'a'.repeat(64);
const HEADER = Object.freeze({
schemaVersion: 1,
kind: 'qinglong3-local-reconciliation-secret-config-plan-header',
secretConfigId: '10000000-0000-4000-8000-000000000001',
applicationId: '20000000-0000-4000-8000-000000000002',
applicationPlanDigest: DIGEST,
reviewDigest: 'b'.repeat(64),
reviewAuthorizationDigest: 'c'.repeat(64),
reviewDecisionSetDigest: 'd'.repeat(64),
reviewDecisionFileDigest: 'e'.repeat(64),
bundleDigest: 'f'.repeat(64),
bundleFingerprintDigest: '1'.repeat(64),
profile: 'edge',
projectId: 'project-1',
tableDisposition: 'adopt_legacy',
preparedHeadDigest: '2'.repeat(64),
preparedAtMs: 1_780_000_000_000,
});
function databases() {
const legacy = new DatabaseSync(':memory:');
legacy.exec(`
CREATE TABLE "Envs" (
id INTEGER PRIMARY KEY,
name TEXT,
value TEXT,
status INTEGER,
position REAL,
"isPinned" INTEGER,
"createdAt" TEXT
);
`);
const target = new DatabaseSync(':memory:');
target.exec(`
CREATE TABLE "QingLong3LocalSecretEnvelopes" (
project_id TEXT NOT NULL,
secret_name TEXT NOT NULL,
version INTEGER NOT NULL,
mutation_id TEXT NOT NULL,
key_id TEXT NOT NULL,
algorithm TEXT NOT NULL,
nonce BLOB NOT NULL,
ciphertext BLOB NOT NULL,
auth_tag BLOB NOT NULL,
created_at_ms INTEGER NOT NULL,
PRIMARY KEY (project_id, secret_name, version)
);
`);
return { legacy, target };
}
function writePlan(t, legacy, target, maxBytes = 8 * 1024 * 1024) {
const directory = fs.mkdtempSync(path.join(os.tmpdir(), 'ql3-secret-plan-'));
t.after(() => fs.rmSync(directory, { recursive: true, force: true }));
const filePath = path.join(directory, 'plan.ndjson');
const descriptor = fs.openSync(filePath, 'w+', 0o600);
let result;
try {
result = writeLocalReconciliationSecretConfigPlan({
descriptor,
maxBytes,
header: HEADER,
legacy,
target,
});
fs.fsyncSync(descriptor);
assert.equal(
hashLocalReconciliationSecretConfigPlanFile(descriptor, result.fileBytes),
result.fileDigest,
);
} finally {
fs.closeSync(descriptor);
}
return {
result,
serialized: fs.readFileSync(filePath, 'utf8'),
records: fs
.readFileSync(filePath, 'utf8')
.trimEnd()
.split('\n')
.map((line) => JSON.parse(line)),
};
}
test('writes a content-free Env plan with separate active and disabled candidates', (t) => {
const { legacy, target } = databases();
t.after(() => legacy.close());
t.after(() => target.close());
legacy.exec(`
INSERT INTO "Envs" VALUES
(1, 'TOKEN', 'later-secret', 0, 10, 0, '2026-01-01'),
(2, 'TOKEN', 'pinned-secret', 0, 1, 1, '2026-01-02'),
(3, 'DISABLED_TOKEN', 'disabled-secret', 1, 0, 0, '2026-01-03');
`);
const { result, records, serialized } = writePlan(t, legacy, target);
assert.equal(result.footer.outcome, 'ready');
assert.equal(result.footer.rowCount, 3);
assert.equal(result.footer.eligibleBindingCount, 1);
assert.equal(result.footer.eligiblePreservationCount, 1);
assert.equal(result.footer.targetConflictCount, 0);
const candidates = records.filter((record) =>
record.kind.endsWith('-candidate'),
);
assert.deepEqual(
candidates.map(({ candidateType, requirement, proposedSecretName }) => ({
candidateType,
requirement,
prefix: proposedSecretName.replace(/[0-9a-f]{32}$/, ''),
})),
[
{
candidateType: 'active_binding',
requirement: 'review_apply_binding',
prefix: 'legacy-db-env-',
},
{
candidateType: 'disabled_preservation',
requirement: 'review_preserve_disabled',
prefix: 'legacy-db-env-disabled-',
},
],
);
for (const privateValue of [
'TOKEN',
'DISABLED_TOKEN',
'later-secret',
'pinned-secret',
'disabled-secret',
]) {
assert.equal(serialized.includes(privateValue), false);
}
const receipt = buildLocalReconciliationSecretConfigPlanReceipt(
result.header,
result.footer,
result.fileBytes,
result.fileDigest,
);
assert.deepEqual(
normalizeLocalReconciliationSecretConfigPlanReceipt(receipt),
receipt,
);
assert.throws(
() =>
normalizeLocalReconciliationSecretConfigPlanReceipt({
...receipt,
eligibleBindingCount: 2,
}),
/receipt drifted/,
);
});
test('captures a target Secret collision without reading plaintext', (t) => {
const { legacy, target } = databases();
t.after(() => legacy.close());
t.after(() => target.close());
legacy.exec(
`INSERT INTO "Envs" VALUES
(1, 'TOKEN', 'private-value', 0, 1, 0, '2026-01-01')`,
);
const initial = writePlan(t, legacy, target);
const candidate = initial.records.find((record) =>
record.kind.endsWith('-candidate'),
);
target
.prepare(
`INSERT INTO "QingLong3LocalSecretEnvelopes" VALUES
(?, ?, 1, ?, ?, 'aes-256-gcm', ?, ?, ?, ?)`,
)
.run(
HEADER.projectId,
candidate.proposedSecretName,
'30000000-0000-4000-8000-000000000003',
'qlsk-test',
Buffer.alloc(12, 1),
Buffer.from('ciphertext'),
Buffer.alloc(16, 2),
HEADER.preparedAtMs,
);
const conflicted = writePlan(t, legacy, target);
assert.equal(conflicted.result.footer.outcome, 'manual_required');
assert.equal(conflicted.result.footer.eligibleBindingCount, 0);
assert.equal(conflicted.result.footer.targetConflictCount, 1);
const occupied = conflicted.records.find((record) =>
record.kind.endsWith('-candidate'),
);
assert.equal(occupied.requirement, 'review_skip_conflict');
assert.equal(occupied.target.state, 'occupied');
assert.equal(occupied.target.version, 1);
assert.match(occupied.target.contentDigest, /^[0-9a-f]{64}$/);
assert.equal(conflicted.serialized.includes('private-value'), false);
assert.equal(conflicted.serialized.includes('ciphertext'), false);
assert.equal(conflicted.serialized.includes('qlsk-test'), false);
});
test('makes absent Envs no-effect and malformed Env manual', (t) => {
const noEnvs = new DatabaseSync(':memory:');
const { target } = databases();
t.after(() => noEnvs.close());
t.after(() => target.close());
const empty = writePlan(t, noEnvs, target);
assert.equal(empty.result.footer.outcome, 'no_effect');
assert.equal(empty.result.footer.tableState, 'absent');
const { legacy, target: secondTarget } = databases();
t.after(() => legacy.close());
t.after(() => secondTarget.close());
legacy.exec(
`INSERT INTO "Envs" VALUES
(1, 'QL3_RESERVED', 'private-value', 0, 1, 0, '2026-01-01')`,
);
const manual = writePlan(t, legacy, secondTarget);
assert.equal(manual.result.footer.outcome, 'manual_required');
assert.equal(manual.result.footer.manualRowCount, 1);
assert.equal(manual.result.footer.eligibleBindingCount, 0);
assert.equal(manual.serialized.includes('QL3_RESERVED'), false);
assert.equal(manual.serialized.includes('private-value'), false);
});
test('fails closed before exceeding the plan byte budget', (t) => {
const { legacy, target } = databases();
t.after(() => legacy.close());
t.after(() => target.close());
legacy.exec(`
WITH RECURSIVE rows(id) AS (
SELECT 1 UNION ALL SELECT id + 1 FROM rows WHERE id < 400
)
INSERT INTO "Envs"
SELECT id, 'TOKEN_' || id, 'private-value', 0, id, 0, '2026-01-01'
FROM rows
`);
assert.throws(
() => writePlan(t, legacy, target, 64 * 1024),
/exceeds profile byte budget/,
);
});