mirror of
https://github.com/whyour/qinglong.git
synced 2026-12-01 09:45:36 +08:00
feat(ql3): establish 3.0 incubation baseline
This commit is contained in:
1 parent
4bf92dcfeb
commit
c699c32461
2817 files changed
+779642
-653
No files matched your search
+73
@@ -0,0 +1,73 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/** Offline Prompt Output external recovery verification CLI boundary. */
|
||||
import {
|
||||
disposeClusterPromptOutputExternalRecoveryInput,
|
||||
readClusterPromptOutputExternalRecoveryCommand,
|
||||
readClusterPromptOutputExternalRecoveryInput,
|
||||
type ClusterPromptOutputExternalRecoveryInput,
|
||||
} from './promptOutputExternalRecoveryInput';
|
||||
import { runClusterPromptOutputExternalRecoveryVerifier } from './promptOutputExternalRecoveryVerifier';
|
||||
|
||||
const USAGE =
|
||||
'Usage: ql3-prompt-output-key-recovery-verify run --command-file /absolute/recovery.json';
|
||||
|
||||
async function main(argv: readonly string[]): Promise<void> {
|
||||
if (argv.length === 1 && (argv[0] === '--help' || argv[0] === '-h')) {
|
||||
process.stdout.write(`${USAGE}\n`);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
argv.length !== 3 ||
|
||||
argv[0] !== 'run' ||
|
||||
argv[1] !== '--command-file' ||
|
||||
!argv[2]
|
||||
) {
|
||||
process.stderr.write(
|
||||
`${JSON.stringify({
|
||||
code: 'QL3_PROMPT_OUTPUT_EXTERNAL_RECOVERY_CLI_USAGE_INVALID',
|
||||
message: USAGE,
|
||||
})}\n`,
|
||||
);
|
||||
process.exitCode = 64;
|
||||
return;
|
||||
}
|
||||
let input: Readonly<ClusterPromptOutputExternalRecoveryInput> | undefined;
|
||||
try {
|
||||
const command = readClusterPromptOutputExternalRecoveryCommand(argv[2]);
|
||||
input = readClusterPromptOutputExternalRecoveryInput(command);
|
||||
const proof = runClusterPromptOutputExternalRecoveryVerifier(input);
|
||||
process.stdout.write(
|
||||
`${JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
component: 'qinglong3-prompt-output-external-recovery-verifier',
|
||||
event: 'recovery_verified',
|
||||
...proof,
|
||||
})}\n`,
|
||||
);
|
||||
} catch (error) {
|
||||
const candidate = error as {
|
||||
readonly code?: unknown;
|
||||
readonly name?: unknown;
|
||||
};
|
||||
process.stderr.write(
|
||||
`${JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
component: 'qinglong3-prompt-output-external-recovery-verifier',
|
||||
event: 'recovery_rejected',
|
||||
name:
|
||||
typeof candidate.name === 'string'
|
||||
? candidate.name.slice(0, 128)
|
||||
: 'Error',
|
||||
...(typeof candidate.code === 'string'
|
||||
? { code: candidate.code.slice(0, 128) }
|
||||
: {}),
|
||||
})}\n`,
|
||||
);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
if (input) disposeClusterPromptOutputExternalRecoveryInput(input);
|
||||
}
|
||||
}
|
||||
|
||||
void main(process.argv.slice(2));
|
||||
+325
@@ -0,0 +1,325 @@
|
||||
/** Private Prompt Output external recovery input authority boundary. */
|
||||
import {
|
||||
constants,
|
||||
closeSync,
|
||||
fstatSync,
|
||||
openSync,
|
||||
readFileSync,
|
||||
} from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import type { PluginPackagePromptOutputArtifact } from '@qinglong/ai/plugin-package-prompt-output-artifact';
|
||||
import type {
|
||||
PluginPackagePromptOutputDurableKeyFact,
|
||||
PluginPackagePromptOutputExternalCustodyReceipt,
|
||||
} from '@qinglong/ai/plugin-package-prompt-output-external-custody';
|
||||
import {
|
||||
openPluginPackagePromptOutputExternalCustodyBundle,
|
||||
type OpenPluginPackagePromptOutputExternalCustodyBundle,
|
||||
type PluginPackagePromptOutputExternalCustodyBundle,
|
||||
} from '@qinglong/ai/plugin-package-prompt-output-external-custody-bundle';
|
||||
import type { PluginPackagePromptOutputExternalRecoveryAuthorization } from '@qinglong/ai/plugin-package-prompt-output-external-recovery-authorization';
|
||||
|
||||
const MAX_COMMAND_FILE_BYTES = 16 * 1024;
|
||||
const MAX_JSON_INPUT_BYTES = 2 * 1024 * 1024;
|
||||
const MAX_CUSTODY_BUNDLE_BYTES = 128 * 1024;
|
||||
const MAX_PUBLIC_KEY_BYTES = 8 * 1024;
|
||||
const ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:@/-]{0,127}$/;
|
||||
|
||||
export interface ClusterPromptOutputExternalRecoveryCommand {
|
||||
readonly schemaVersion: 1;
|
||||
readonly operation: 'cluster.prompt-output-key.verify-recovery';
|
||||
readonly authorizationFile: string;
|
||||
readonly custodyBundleFile: string;
|
||||
readonly recoveredMaterialFile: string;
|
||||
readonly durableKeyFactFile: string;
|
||||
readonly artifactFile: string;
|
||||
readonly custodyPublicKeyFile: string;
|
||||
readonly approverPublicKeyFiles: readonly [
|
||||
Readonly<{ userId: string; filePath: string }>,
|
||||
Readonly<{ userId: string; filePath: string }>,
|
||||
];
|
||||
}
|
||||
|
||||
export interface ClusterPromptOutputExternalRecoveryInput {
|
||||
readonly authorization: PluginPackagePromptOutputExternalRecoveryAuthorization;
|
||||
readonly receipt: PluginPackagePromptOutputExternalCustodyReceipt;
|
||||
readonly wrappedMaterial: Buffer;
|
||||
readonly material: Buffer;
|
||||
readonly durableKeyFact: Readonly<PluginPackagePromptOutputDurableKeyFact>;
|
||||
readonly artifact: PluginPackagePromptOutputArtifact;
|
||||
readonly custodyPublicKey: Buffer;
|
||||
readonly approverPublicKeys: readonly [
|
||||
Readonly<{ userId: string; publicKey: Buffer }>,
|
||||
Readonly<{ userId: string; publicKey: Buffer }>,
|
||||
];
|
||||
}
|
||||
|
||||
function exactKeys(value: object, expected: readonly string[]): boolean {
|
||||
const keys = Object.keys(value).sort();
|
||||
const canonical = [...expected].sort();
|
||||
return (
|
||||
keys.length === canonical.length &&
|
||||
keys.every((key, index) => key === canonical[index])
|
||||
);
|
||||
}
|
||||
|
||||
function absolutePath(value: unknown, label: string): string {
|
||||
if (
|
||||
typeof value !== 'string' ||
|
||||
!path.isAbsolute(value) ||
|
||||
path.normalize(value) !== value ||
|
||||
value.includes('\0') ||
|
||||
Buffer.byteLength(value, 'utf8') > 4096
|
||||
) {
|
||||
throw new TypeError(`${label} is invalid`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function stableReadOnlyFile(
|
||||
filePathValue: string,
|
||||
options: Readonly<{
|
||||
label: string;
|
||||
minimumBytes: number;
|
||||
maximumBytes: number;
|
||||
privateFile: boolean;
|
||||
}>,
|
||||
): Buffer {
|
||||
const filePath = absolutePath(filePathValue, `${options.label} path`);
|
||||
let descriptor: number | undefined;
|
||||
try {
|
||||
descriptor = openSync(
|
||||
filePath,
|
||||
constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0),
|
||||
);
|
||||
const before = fstatSync(descriptor);
|
||||
if (
|
||||
!before.isFile() ||
|
||||
before.nlink !== 1 ||
|
||||
before.size < options.minimumBytes ||
|
||||
before.size > options.maximumBytes ||
|
||||
(before.mode & 0o222) !== 0 ||
|
||||
(before.mode & 0o111) !== 0 ||
|
||||
(before.mode & 0o440) === 0 ||
|
||||
(options.privateFile && (before.mode & 0o007) !== 0)
|
||||
) {
|
||||
throw new TypeError(`${options.label} is unavailable`);
|
||||
}
|
||||
const value = readFileSync(descriptor);
|
||||
const after = fstatSync(descriptor);
|
||||
if (
|
||||
value.byteLength !== before.size ||
|
||||
after.dev !== before.dev ||
|
||||
after.ino !== before.ino ||
|
||||
after.size !== before.size ||
|
||||
after.mtimeMs !== before.mtimeMs
|
||||
) {
|
||||
value.fill(0);
|
||||
throw new TypeError(`${options.label} changed during read`);
|
||||
}
|
||||
return value;
|
||||
} finally {
|
||||
if (descriptor !== undefined) closeSync(descriptor);
|
||||
}
|
||||
}
|
||||
|
||||
function jsonFile(filePath: string, label: string): unknown {
|
||||
const bytes = stableReadOnlyFile(filePath, {
|
||||
label,
|
||||
minimumBytes: 2,
|
||||
maximumBytes: MAX_JSON_INPUT_BYTES,
|
||||
privateFile: true,
|
||||
});
|
||||
try {
|
||||
return JSON.parse(bytes.toString('utf8')) as unknown;
|
||||
} finally {
|
||||
bytes.fill(0);
|
||||
}
|
||||
}
|
||||
|
||||
export function readClusterPromptOutputExternalRecoveryCommand(
|
||||
filePathValue: string,
|
||||
): Readonly<ClusterPromptOutputExternalRecoveryCommand> {
|
||||
const bytes = stableReadOnlyFile(filePathValue, {
|
||||
label: 'Recovery command file',
|
||||
minimumBytes: 2,
|
||||
maximumBytes: MAX_COMMAND_FILE_BYTES,
|
||||
privateFile: false,
|
||||
});
|
||||
try {
|
||||
const value = JSON.parse(bytes.toString('utf8')) as unknown;
|
||||
if (
|
||||
!value ||
|
||||
typeof value !== 'object' ||
|
||||
Array.isArray(value) ||
|
||||
!exactKeys(value, [
|
||||
'approverPublicKeyFiles',
|
||||
'artifactFile',
|
||||
'authorizationFile',
|
||||
'custodyBundleFile',
|
||||
'custodyPublicKeyFile',
|
||||
'durableKeyFactFile',
|
||||
'operation',
|
||||
'recoveredMaterialFile',
|
||||
'schemaVersion',
|
||||
])
|
||||
) {
|
||||
throw new TypeError('Recovery command shape is invalid');
|
||||
}
|
||||
const candidate = value as Record<string, unknown>;
|
||||
if (
|
||||
candidate.schemaVersion !== 1 ||
|
||||
candidate.operation !== 'cluster.prompt-output-key.verify-recovery' ||
|
||||
!Array.isArray(candidate.approverPublicKeyFiles) ||
|
||||
candidate.approverPublicKeyFiles.length !== 2
|
||||
) {
|
||||
throw new TypeError('Recovery command value is invalid');
|
||||
}
|
||||
const approvers = candidate.approverPublicKeyFiles
|
||||
.map((entry, index) => {
|
||||
if (
|
||||
!entry ||
|
||||
typeof entry !== 'object' ||
|
||||
Array.isArray(entry) ||
|
||||
!exactKeys(entry, ['filePath', 'userId'])
|
||||
) {
|
||||
throw new TypeError(`Approver public key ${index} is invalid`);
|
||||
}
|
||||
const item = entry as Record<string, unknown>;
|
||||
if (typeof item.userId !== 'string' || !ID_PATTERN.test(item.userId)) {
|
||||
throw new TypeError(`Approver public key ${index} user is invalid`);
|
||||
}
|
||||
return Object.freeze({
|
||||
userId: item.userId,
|
||||
filePath: absolutePath(
|
||||
item.filePath,
|
||||
`Approver public key ${index} file`,
|
||||
),
|
||||
});
|
||||
})
|
||||
.sort((left, right) => left.userId.localeCompare(right.userId));
|
||||
if (approvers[0]!.userId === approvers[1]!.userId) {
|
||||
throw new TypeError('Approver public key users must be distinct');
|
||||
}
|
||||
return Object.freeze({
|
||||
schemaVersion: 1,
|
||||
operation: 'cluster.prompt-output-key.verify-recovery',
|
||||
authorizationFile: absolutePath(
|
||||
candidate.authorizationFile,
|
||||
'Authorization file',
|
||||
),
|
||||
custodyBundleFile: absolutePath(
|
||||
candidate.custodyBundleFile,
|
||||
'Custody bundle file',
|
||||
),
|
||||
recoveredMaterialFile: absolutePath(
|
||||
candidate.recoveredMaterialFile,
|
||||
'Recovered material file',
|
||||
),
|
||||
durableKeyFactFile: absolutePath(
|
||||
candidate.durableKeyFactFile,
|
||||
'Durable key fact file',
|
||||
),
|
||||
artifactFile: absolutePath(candidate.artifactFile, 'Artifact file'),
|
||||
custodyPublicKeyFile: absolutePath(
|
||||
candidate.custodyPublicKeyFile,
|
||||
'Custody public key file',
|
||||
),
|
||||
approverPublicKeyFiles: approvers as unknown as readonly [
|
||||
Readonly<{ userId: string; filePath: string }>,
|
||||
Readonly<{ userId: string; filePath: string }>,
|
||||
],
|
||||
});
|
||||
} finally {
|
||||
bytes.fill(0);
|
||||
}
|
||||
}
|
||||
|
||||
export function readClusterPromptOutputExternalRecoveryInput(
|
||||
command: Readonly<ClusterPromptOutputExternalRecoveryCommand>,
|
||||
): Readonly<ClusterPromptOutputExternalRecoveryInput> {
|
||||
let custodyBundle:
|
||||
| Readonly<OpenPluginPackagePromptOutputExternalCustodyBundle>
|
||||
| undefined;
|
||||
let material: Buffer | undefined;
|
||||
let custodyPublicKey: Buffer | undefined;
|
||||
const approverPublicKeys: Buffer[] = [];
|
||||
try {
|
||||
material = stableReadOnlyFile(command.recoveredMaterialFile, {
|
||||
label: 'Recovered material',
|
||||
minimumBytes: 32,
|
||||
maximumBytes: 32,
|
||||
privateFile: true,
|
||||
});
|
||||
custodyPublicKey = stableReadOnlyFile(command.custodyPublicKeyFile, {
|
||||
label: 'Custody public key',
|
||||
minimumBytes: 32,
|
||||
maximumBytes: MAX_PUBLIC_KEY_BYTES,
|
||||
privateFile: true,
|
||||
});
|
||||
const custodyBundleBytes = stableReadOnlyFile(command.custodyBundleFile, {
|
||||
label: 'Custody bundle',
|
||||
minimumBytes: 2,
|
||||
maximumBytes: MAX_CUSTODY_BUNDLE_BYTES,
|
||||
privateFile: true,
|
||||
});
|
||||
try {
|
||||
custodyBundle = openPluginPackagePromptOutputExternalCustodyBundle(
|
||||
JSON.parse(
|
||||
custodyBundleBytes.toString('utf8'),
|
||||
) as PluginPackagePromptOutputExternalCustodyBundle,
|
||||
custodyPublicKey,
|
||||
);
|
||||
} finally {
|
||||
custodyBundleBytes.fill(0);
|
||||
}
|
||||
const approvers = command.approverPublicKeyFiles.map((entry) => {
|
||||
const publicKey = stableReadOnlyFile(entry.filePath, {
|
||||
label: `Approver ${entry.userId} public key`,
|
||||
minimumBytes: 32,
|
||||
maximumBytes: MAX_PUBLIC_KEY_BYTES,
|
||||
privateFile: true,
|
||||
});
|
||||
approverPublicKeys.push(publicKey);
|
||||
return Object.freeze({ userId: entry.userId, publicKey });
|
||||
}) as unknown as readonly [
|
||||
Readonly<{ userId: string; publicKey: Buffer }>,
|
||||
Readonly<{ userId: string; publicKey: Buffer }>,
|
||||
];
|
||||
return Object.freeze({
|
||||
authorization: jsonFile(
|
||||
command.authorizationFile,
|
||||
'Recovery authorization',
|
||||
) as PluginPackagePromptOutputExternalRecoveryAuthorization,
|
||||
receipt: custodyBundle.receipt,
|
||||
wrappedMaterial: custodyBundle.wrappedMaterial,
|
||||
material,
|
||||
durableKeyFact: jsonFile(
|
||||
command.durableKeyFactFile,
|
||||
'Durable key fact',
|
||||
) as PluginPackagePromptOutputDurableKeyFact,
|
||||
artifact: jsonFile(
|
||||
command.artifactFile,
|
||||
'Prompt output Artifact',
|
||||
) as PluginPackagePromptOutputArtifact,
|
||||
custodyPublicKey,
|
||||
approverPublicKeys: approvers,
|
||||
});
|
||||
} catch (cause) {
|
||||
custodyBundle?.wrappedMaterial.fill(0);
|
||||
material?.fill(0);
|
||||
custodyPublicKey?.fill(0);
|
||||
approverPublicKeys.forEach((publicKey) => publicKey.fill(0));
|
||||
throw cause;
|
||||
}
|
||||
}
|
||||
|
||||
export function disposeClusterPromptOutputExternalRecoveryInput(
|
||||
value: Readonly<ClusterPromptOutputExternalRecoveryInput>,
|
||||
): void {
|
||||
value.wrappedMaterial.fill(0);
|
||||
value.material.fill(0);
|
||||
value.custodyPublicKey.fill(0);
|
||||
value.approverPublicKeys.forEach(({ publicKey }) => publicKey.fill(0));
|
||||
}
|
||||
+47
@@ -0,0 +1,47 @@
|
||||
/** Content-free Prompt Output external recovery verifier boundary. */
|
||||
import {
|
||||
verifyAuthorizedPluginPackagePromptOutputRecoveredMaterial,
|
||||
type PluginPackagePromptOutputAuthorizedExternalRecoveryProof,
|
||||
} from '@qinglong/ai/plugin-package-prompt-output-external-recovery-authorization';
|
||||
|
||||
import type { ClusterPromptOutputExternalRecoveryInput } from './promptOutputExternalRecoveryInput';
|
||||
|
||||
export class ClusterPromptOutputExternalRecoveryVerifierConfigError extends TypeError {
|
||||
readonly code = 'QL3_PROMPT_OUTPUT_EXTERNAL_RECOVERY_VERIFIER_CONFIG_INVALID';
|
||||
|
||||
constructor(message: string, readonly cause?: unknown) {
|
||||
super(
|
||||
`Prompt output external recovery verifier configuration is invalid: ${message}`,
|
||||
);
|
||||
this.name = 'ClusterPromptOutputExternalRecoveryVerifierConfigError';
|
||||
}
|
||||
}
|
||||
|
||||
export function runClusterPromptOutputExternalRecoveryVerifier(
|
||||
input: Readonly<ClusterPromptOutputExternalRecoveryInput>,
|
||||
verifiedAtMs = Date.now(),
|
||||
): Readonly<PluginPackagePromptOutputAuthorizedExternalRecoveryProof> {
|
||||
if (!Number.isSafeInteger(verifiedAtMs) || verifiedAtMs < 0) {
|
||||
throw new ClusterPromptOutputExternalRecoveryVerifierConfigError(
|
||||
'verification time is invalid',
|
||||
);
|
||||
}
|
||||
try {
|
||||
return verifyAuthorizedPluginPackagePromptOutputRecoveredMaterial({
|
||||
authorization: input.authorization,
|
||||
trustedApprovers: input.approverPublicKeys,
|
||||
receipt: input.receipt,
|
||||
trustedCustodyPublicKey: input.custodyPublicKey,
|
||||
wrappedMaterial: input.wrappedMaterial,
|
||||
durableKeyFact: input.durableKeyFact,
|
||||
material: input.material,
|
||||
artifact: input.artifact,
|
||||
verifiedAtMs,
|
||||
});
|
||||
} catch (cause) {
|
||||
throw new ClusterPromptOutputExternalRecoveryVerifierConfigError(
|
||||
'recovery evidence is untrusted',
|
||||
cause,
|
||||
);
|
||||
}
|
||||
}
|
||||
+185
@@ -0,0 +1,185 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/** One-shot Prompt Output key retirement CLI boundary. */
|
||||
import {
|
||||
constants,
|
||||
closeSync,
|
||||
fstatSync,
|
||||
openSync,
|
||||
readFileSync,
|
||||
} from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import { type ClusterPromptOutputKubernetesSecretKeyringOptions } from './promptOutputKubernetesSecretKeyring';
|
||||
import { openPromptOutputKubernetesSecretAuthority } from './promptOutputKubernetesSecretAuthority';
|
||||
import { runClusterPromptOutputKeyRetirementProcess } from './promptOutputKeyRetirementProcess';
|
||||
import { loadPromptOutputPostgresMaintenanceConnection } from './promptOutputPostgresMaintenanceConnection';
|
||||
|
||||
const USAGE =
|
||||
'Usage: ql3-prompt-output-key-retire run --command-file /absolute/retirement.json';
|
||||
const MAX_COMMAND_FILE_BYTES = 16 * 1024;
|
||||
|
||||
interface RetirementCommand {
|
||||
readonly schemaVersion: 1;
|
||||
readonly operation: 'cluster.prompt-output-key.retire';
|
||||
readonly kubernetes: ClusterPromptOutputKubernetesSecretKeyringOptions;
|
||||
readonly request: Readonly<{
|
||||
keyId: string;
|
||||
retirementId: string;
|
||||
requestId: string;
|
||||
mutationId: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
function exactKeys(value: object, expected: readonly string[]): boolean {
|
||||
const actual = Object.keys(value).sort();
|
||||
const canonical = [...expected].sort();
|
||||
return (
|
||||
actual.length === canonical.length &&
|
||||
actual.every((key, index) => key === canonical[index])
|
||||
);
|
||||
}
|
||||
|
||||
function commandFile(filePath: string): RetirementCommand {
|
||||
if (
|
||||
typeof filePath !== 'string' ||
|
||||
!path.isAbsolute(filePath) ||
|
||||
filePath.includes('\0') ||
|
||||
Buffer.byteLength(filePath, 'utf8') > 4096
|
||||
) {
|
||||
throw new TypeError('Retirement command file path is invalid');
|
||||
}
|
||||
let descriptor: number | undefined;
|
||||
try {
|
||||
descriptor = openSync(
|
||||
filePath,
|
||||
constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0),
|
||||
);
|
||||
const stat = fstatSync(descriptor);
|
||||
if (!stat.isFile() || stat.size < 1 || stat.size > MAX_COMMAND_FILE_BYTES) {
|
||||
throw new TypeError('Retirement command file is invalid');
|
||||
}
|
||||
const parsed = JSON.parse(readFileSync(descriptor, 'utf8')) as unknown;
|
||||
if (
|
||||
!parsed ||
|
||||
typeof parsed !== 'object' ||
|
||||
Array.isArray(parsed) ||
|
||||
!exactKeys(parsed, [
|
||||
'kubernetes',
|
||||
'operation',
|
||||
'request',
|
||||
'schemaVersion',
|
||||
])
|
||||
) {
|
||||
throw new TypeError('Retirement command shape is invalid');
|
||||
}
|
||||
const candidate = parsed as Record<string, unknown>;
|
||||
if (
|
||||
candidate.schemaVersion !== 1 ||
|
||||
candidate.operation !== 'cluster.prompt-output-key.retire' ||
|
||||
!candidate.kubernetes ||
|
||||
typeof candidate.kubernetes !== 'object' ||
|
||||
Array.isArray(candidate.kubernetes) ||
|
||||
!candidate.request ||
|
||||
typeof candidate.request !== 'object' ||
|
||||
Array.isArray(candidate.request)
|
||||
) {
|
||||
throw new TypeError('Retirement command value is invalid');
|
||||
}
|
||||
const kubernetes = candidate.kubernetes as Record<string, unknown>;
|
||||
const request = candidate.request as Record<string, unknown>;
|
||||
if (
|
||||
!exactKeys(kubernetes, [
|
||||
'dataKey',
|
||||
'expectedSecretUid',
|
||||
'namespace',
|
||||
'secretName',
|
||||
]) ||
|
||||
!exactKeys(request, ['keyId', 'mutationId', 'requestId', 'retirementId'])
|
||||
) {
|
||||
throw new TypeError('Retirement command nested shape is invalid');
|
||||
}
|
||||
return Object.freeze(parsed as RetirementCommand);
|
||||
} finally {
|
||||
if (descriptor !== undefined) closeSync(descriptor);
|
||||
}
|
||||
}
|
||||
|
||||
async function main(argv: readonly string[]): Promise<void> {
|
||||
if (argv.length === 1 && (argv[0] === '--help' || argv[0] === '-h')) {
|
||||
process.stdout.write(`${USAGE}\n`);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
argv.length !== 3 ||
|
||||
argv[0] !== 'run' ||
|
||||
argv[1] !== '--command-file' ||
|
||||
!argv[2]
|
||||
) {
|
||||
process.stderr.write(
|
||||
`${JSON.stringify({
|
||||
code: 'QL3_PROMPT_OUTPUT_KEY_RETIREMENT_CLI_USAGE_INVALID',
|
||||
message: USAGE,
|
||||
})}\n`,
|
||||
);
|
||||
process.exitCode = 64;
|
||||
return;
|
||||
}
|
||||
let authority:
|
||||
| Awaited<ReturnType<typeof openPromptOutputKubernetesSecretAuthority>>
|
||||
| undefined;
|
||||
try {
|
||||
const command = commandFile(argv[2]);
|
||||
authority = await openPromptOutputKubernetesSecretAuthority(
|
||||
command.kubernetes,
|
||||
);
|
||||
const result = await runClusterPromptOutputKeyRetirementProcess({
|
||||
database: {
|
||||
connection: loadPromptOutputPostgresMaintenanceConnection(process.env),
|
||||
pool: {
|
||||
applicationName: 'qinglong3-prompt-output-key-retirement',
|
||||
maxConnections: 1,
|
||||
},
|
||||
},
|
||||
request: command.request,
|
||||
materials: authority.materials,
|
||||
});
|
||||
process.stdout.write(
|
||||
`${JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
component: 'qinglong3-prompt-output-key-retirement',
|
||||
event: 'key_retirement_completed',
|
||||
status: result.status,
|
||||
keyId: result.keyId,
|
||||
retirementId: result.retirementId,
|
||||
preparationDigest: result.preparationDigest,
|
||||
completionDigest: result.completionDigest,
|
||||
completedAtMs: result.completedAtMs,
|
||||
})}\n`,
|
||||
);
|
||||
} catch (error) {
|
||||
const candidate = error as {
|
||||
readonly code?: unknown;
|
||||
readonly name?: unknown;
|
||||
};
|
||||
process.stderr.write(
|
||||
`${JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
component: 'qinglong3-prompt-output-key-retirement',
|
||||
event: 'key_retirement_failed',
|
||||
name:
|
||||
typeof candidate.name === 'string'
|
||||
? candidate.name.slice(0, 128)
|
||||
: 'Error',
|
||||
...(typeof candidate.code === 'string'
|
||||
? { code: candidate.code.slice(0, 128) }
|
||||
: {}),
|
||||
})}\n`,
|
||||
);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
authority?.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
void main(process.argv.slice(2));
|
||||
+137
@@ -0,0 +1,137 @@
|
||||
/** Prompt Output key retirement transaction composition boundary. */
|
||||
import type { OpenPostgresDatabase } from '@qinglong/runtime-core';
|
||||
import {
|
||||
createPostgresDatabaseOpener,
|
||||
type PostgresConnectionOptions,
|
||||
type PostgresPoolOptions,
|
||||
} from '@qinglong/cluster-postgres/ai-maintenance';
|
||||
import {
|
||||
PluginPackagePromptOutputKeyRetirementCoordinator,
|
||||
normalizePluginPackagePromptOutputKeyRetirementRequest,
|
||||
type PluginPackagePromptOutputKeyRetirementMaterialAuthority,
|
||||
} from '@qinglong/ai/plugin-package-prompt-output-key-retirement';
|
||||
import { PostgresPluginPackagePromptOutputKeyRetirementRepository } from '@qinglong/ai/postgres-plugin-package-prompt-output-key-retirement-storage';
|
||||
import {
|
||||
assertPostgresPluginPackagePromptOutputMaintenanceReady,
|
||||
type PostgresPluginPackagePromptOutputMaintenanceReadinessReport,
|
||||
} from '@qinglong/ai/postgres-plugin-package-prompt-output-retention-storage';
|
||||
|
||||
export interface RunClusterPromptOutputKeyRetirementProcessOptions {
|
||||
readonly database: Readonly<{
|
||||
readonly connection: PostgresConnectionOptions;
|
||||
readonly pool?: PostgresPoolOptions;
|
||||
}>;
|
||||
readonly request: Readonly<{
|
||||
readonly keyId: string;
|
||||
readonly retirementId: string;
|
||||
readonly requestId: string;
|
||||
readonly mutationId: string;
|
||||
}>;
|
||||
readonly materials: PluginPackagePromptOutputKeyRetirementMaterialAuthority;
|
||||
readonly openDatabase?: OpenPostgresDatabase;
|
||||
}
|
||||
|
||||
export interface ClusterPromptOutputKeyRetirementProcessResult {
|
||||
readonly readiness: PostgresPluginPackagePromptOutputMaintenanceReadinessReport;
|
||||
readonly status: 'completed' | 'existing';
|
||||
readonly keyId: string;
|
||||
readonly retirementId: string;
|
||||
readonly preparationDigest: string;
|
||||
readonly completionDigest: string;
|
||||
readonly completedAtMs: number;
|
||||
}
|
||||
|
||||
export class ClusterPromptOutputKeyRetirementProcessConfigError extends TypeError {
|
||||
readonly code = 'QL3_PROMPT_OUTPUT_KEY_RETIREMENT_PROCESS_CONFIG_INVALID';
|
||||
|
||||
constructor(message: string, readonly cause?: unknown) {
|
||||
super(
|
||||
`Prompt output key retirement process configuration is invalid: ${message}`,
|
||||
);
|
||||
this.name = 'ClusterPromptOutputKeyRetirementProcessConfigError';
|
||||
}
|
||||
}
|
||||
|
||||
export async function runClusterPromptOutputKeyRetirementProcess(
|
||||
options: RunClusterPromptOutputKeyRetirementProcessOptions,
|
||||
): Promise<Readonly<ClusterPromptOutputKeyRetirementProcessResult>> {
|
||||
if (
|
||||
!options ||
|
||||
typeof options !== 'object' ||
|
||||
Array.isArray(options) ||
|
||||
!options.database ||
|
||||
typeof options.database !== 'object' ||
|
||||
Array.isArray(options.database) ||
|
||||
!options.materials ||
|
||||
typeof options.materials !== 'object' ||
|
||||
typeof options.materials.inspect !== 'function' ||
|
||||
typeof options.materials.retire !== 'function'
|
||||
) {
|
||||
throw new ClusterPromptOutputKeyRetirementProcessConfigError(
|
||||
'options are invalid',
|
||||
);
|
||||
}
|
||||
let request;
|
||||
try {
|
||||
request = normalizePluginPackagePromptOutputKeyRetirementRequest(
|
||||
options.request,
|
||||
);
|
||||
} catch (cause) {
|
||||
throw new ClusterPromptOutputKeyRetirementProcessConfigError(
|
||||
'request is invalid',
|
||||
cause,
|
||||
);
|
||||
}
|
||||
let poolError: Error | undefined;
|
||||
const openDatabase =
|
||||
options.openDatabase ??
|
||||
createPostgresDatabaseOpener({
|
||||
role: 'ai-maintenance',
|
||||
connection: options.database.connection,
|
||||
...(options.database.pool === undefined
|
||||
? {}
|
||||
: { pool: options.database.pool }),
|
||||
onPoolError(error) {
|
||||
poolError ??= error;
|
||||
},
|
||||
});
|
||||
const database = await openDatabase();
|
||||
let failure: unknown;
|
||||
try {
|
||||
const readiness =
|
||||
await assertPostgresPluginPackagePromptOutputMaintenanceReady(
|
||||
database.pool,
|
||||
);
|
||||
const result = await new PluginPackagePromptOutputKeyRetirementCoordinator({
|
||||
repository: new PostgresPluginPackagePromptOutputKeyRetirementRepository({
|
||||
pool: database.pool,
|
||||
}),
|
||||
materials: options.materials,
|
||||
}).retire(request);
|
||||
if (poolError) throw poolError;
|
||||
return Object.freeze({
|
||||
readiness,
|
||||
status: result.status,
|
||||
keyId: result.preparation.keyId,
|
||||
retirementId: result.preparation.retirementId,
|
||||
preparationDigest: result.preparation.preparationDigest,
|
||||
completionDigest: result.completion.completionDigest,
|
||||
completedAtMs: result.completion.completedAtMs,
|
||||
});
|
||||
} catch (cause) {
|
||||
failure = cause;
|
||||
throw cause;
|
||||
} finally {
|
||||
try {
|
||||
await database.close();
|
||||
} catch (closeError) {
|
||||
if (failure !== undefined) {
|
||||
throw new AggregateError(
|
||||
[failure, closeError],
|
||||
'Prompt output key retirement failed and PostgreSQL did not close',
|
||||
);
|
||||
}
|
||||
throw closeError;
|
||||
}
|
||||
}
|
||||
}
|
||||
+107
@@ -0,0 +1,107 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/** One-shot Prompt Output key rotation CLI boundary. */
|
||||
import { openPromptOutputKubernetesSecretAuthority } from './promptOutputKubernetesSecretAuthority';
|
||||
import { runClusterPromptOutputKeyRotationProcess } from './promptOutputKeyRotationProcess';
|
||||
import {
|
||||
readClusterPromptOutputKeyRotationCommand,
|
||||
readClusterPromptOutputKeyRotationMaterial,
|
||||
} from './promptOutputKeyRotationInput';
|
||||
import { loadPromptOutputPostgresMaintenanceConnection } from './promptOutputPostgresMaintenanceConnection';
|
||||
|
||||
const USAGE =
|
||||
'Usage: ql3-prompt-output-key-rotate run --command-file /absolute/rotation.json';
|
||||
|
||||
async function main(argv: readonly string[]): Promise<void> {
|
||||
if (argv.length === 1 && (argv[0] === '--help' || argv[0] === '-h')) {
|
||||
process.stdout.write(`${USAGE}\n`);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
argv.length !== 3 ||
|
||||
argv[0] !== 'run' ||
|
||||
argv[1] !== '--command-file' ||
|
||||
!argv[2]
|
||||
) {
|
||||
process.stderr.write(
|
||||
`${JSON.stringify({
|
||||
code: 'QL3_PROMPT_OUTPUT_KEY_ROTATION_CLI_USAGE_INVALID',
|
||||
message: USAGE,
|
||||
})}\n`,
|
||||
);
|
||||
process.exitCode = 64;
|
||||
return;
|
||||
}
|
||||
let authority:
|
||||
| Awaited<ReturnType<typeof openPromptOutputKubernetesSecretAuthority>>
|
||||
| undefined;
|
||||
let material: Buffer | undefined;
|
||||
try {
|
||||
const command = readClusterPromptOutputKeyRotationCommand(argv[2]);
|
||||
authority = await openPromptOutputKubernetesSecretAuthority(
|
||||
command.kubernetes,
|
||||
);
|
||||
material = readClusterPromptOutputKeyRotationMaterial(
|
||||
command.stagedMaterialFile,
|
||||
);
|
||||
const result = await runClusterPromptOutputKeyRotationProcess({
|
||||
database: {
|
||||
connection: loadPromptOutputPostgresMaintenanceConnection(process.env),
|
||||
pool: {
|
||||
applicationName: 'qinglong3-prompt-output-key-rotation',
|
||||
maxConnections: 1,
|
||||
},
|
||||
},
|
||||
request: {
|
||||
...command.request,
|
||||
expectedSecretUid: command.kubernetes.expectedSecretUid,
|
||||
},
|
||||
material,
|
||||
materials: authority.materials,
|
||||
});
|
||||
process.stdout.write(
|
||||
`${JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
component: 'qinglong3-prompt-output-key-rotation',
|
||||
event: 'key_rotation_completed',
|
||||
status: result.status,
|
||||
rotationId: result.rotationId,
|
||||
requestId: result.requestId,
|
||||
mutationId: result.mutationId,
|
||||
preparationDigest: result.preparationDigest,
|
||||
completionDigest: result.completionDigest,
|
||||
generation: result.generation,
|
||||
previousActiveKeyId: result.previousActiveKeyId,
|
||||
activeKeyId: result.activeKeyId,
|
||||
catalogDigest: result.catalogDigest,
|
||||
materialProof: result.materialProof,
|
||||
completedAtMs: result.completedAtMs,
|
||||
})}\n`,
|
||||
);
|
||||
} catch (error) {
|
||||
const candidate = error as {
|
||||
readonly code?: unknown;
|
||||
readonly name?: unknown;
|
||||
};
|
||||
process.stderr.write(
|
||||
`${JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
component: 'qinglong3-prompt-output-key-rotation',
|
||||
event: 'key_rotation_failed',
|
||||
name:
|
||||
typeof candidate.name === 'string'
|
||||
? candidate.name.slice(0, 128)
|
||||
: 'Error',
|
||||
...(typeof candidate.code === 'string'
|
||||
? { code: candidate.code.slice(0, 128) }
|
||||
: {}),
|
||||
})}\n`,
|
||||
);
|
||||
process.exitCode = 1;
|
||||
} finally {
|
||||
material?.fill(0);
|
||||
authority?.dispose();
|
||||
}
|
||||
}
|
||||
|
||||
void main(process.argv.slice(2));
|
||||
+179
@@ -0,0 +1,179 @@
|
||||
/** Private staged Prompt Output key rotation input authority boundary. */
|
||||
import {
|
||||
constants,
|
||||
closeSync,
|
||||
fstatSync,
|
||||
openSync,
|
||||
readFileSync,
|
||||
} from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import type { ClusterPromptOutputKubernetesSecretKeyringOptions } from './promptOutputKubernetesSecretKeyring';
|
||||
|
||||
const MAX_COMMAND_FILE_BYTES = 16 * 1024;
|
||||
const ID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
||||
const DIGEST = /^[0-9a-f]{64}$/;
|
||||
|
||||
export interface ClusterPromptOutputKeyRotationCommand {
|
||||
readonly schemaVersion: 1;
|
||||
readonly operation: 'cluster.prompt-output-key.rotate';
|
||||
readonly kubernetes: ClusterPromptOutputKubernetesSecretKeyringOptions;
|
||||
readonly stagedMaterialFile: string;
|
||||
readonly request: Readonly<{
|
||||
rotationId: string;
|
||||
requestId: string;
|
||||
mutationId: string;
|
||||
expectedActiveKeyId: string;
|
||||
expectedCatalogDigest: string;
|
||||
newKeyId: string;
|
||||
}>;
|
||||
}
|
||||
|
||||
function exactKeys(value: object, expected: readonly string[]): boolean {
|
||||
const actual = Object.keys(value).sort();
|
||||
const canonical = [...expected].sort();
|
||||
return (
|
||||
actual.length === canonical.length &&
|
||||
actual.every((key, index) => key === canonical[index])
|
||||
);
|
||||
}
|
||||
|
||||
function absoluteFilePath(value: unknown, label: string): string {
|
||||
if (
|
||||
typeof value !== 'string' ||
|
||||
!path.isAbsolute(value) ||
|
||||
path.normalize(value) !== value ||
|
||||
value.includes('\0') ||
|
||||
Buffer.byteLength(value, 'utf8') > 4096
|
||||
) {
|
||||
throw new TypeError(`${label} is invalid`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
export function readClusterPromptOutputKeyRotationCommand(
|
||||
filePathValue: string,
|
||||
): Readonly<ClusterPromptOutputKeyRotationCommand> {
|
||||
const filePath = absoluteFilePath(
|
||||
filePathValue,
|
||||
'Rotation command file path',
|
||||
);
|
||||
let descriptor: number | undefined;
|
||||
try {
|
||||
descriptor = openSync(
|
||||
filePath,
|
||||
constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0),
|
||||
);
|
||||
const stat = fstatSync(descriptor);
|
||||
if (!stat.isFile() || stat.size < 1 || stat.size > MAX_COMMAND_FILE_BYTES) {
|
||||
throw new TypeError('Rotation command file is invalid');
|
||||
}
|
||||
const parsed = JSON.parse(readFileSync(descriptor, 'utf8')) as unknown;
|
||||
if (
|
||||
!parsed ||
|
||||
typeof parsed !== 'object' ||
|
||||
Array.isArray(parsed) ||
|
||||
!exactKeys(parsed, [
|
||||
'kubernetes',
|
||||
'operation',
|
||||
'request',
|
||||
'schemaVersion',
|
||||
'stagedMaterialFile',
|
||||
])
|
||||
) {
|
||||
throw new TypeError('Rotation command shape is invalid');
|
||||
}
|
||||
const candidate = parsed as Record<string, unknown>;
|
||||
if (
|
||||
candidate.schemaVersion !== 1 ||
|
||||
candidate.operation !== 'cluster.prompt-output-key.rotate' ||
|
||||
!candidate.kubernetes ||
|
||||
typeof candidate.kubernetes !== 'object' ||
|
||||
Array.isArray(candidate.kubernetes) ||
|
||||
!candidate.request ||
|
||||
typeof candidate.request !== 'object' ||
|
||||
Array.isArray(candidate.request)
|
||||
) {
|
||||
throw new TypeError('Rotation command value is invalid');
|
||||
}
|
||||
const kubernetes = candidate.kubernetes as Record<string, unknown>;
|
||||
const request = candidate.request as Record<string, unknown>;
|
||||
if (
|
||||
!exactKeys(kubernetes, [
|
||||
'dataKey',
|
||||
'expectedSecretUid',
|
||||
'namespace',
|
||||
'secretName',
|
||||
]) ||
|
||||
!exactKeys(request, [
|
||||
'expectedActiveKeyId',
|
||||
'expectedCatalogDigest',
|
||||
'mutationId',
|
||||
'newKeyId',
|
||||
'requestId',
|
||||
'rotationId',
|
||||
]) ||
|
||||
![
|
||||
request.rotationId,
|
||||
request.requestId,
|
||||
request.mutationId,
|
||||
request.expectedActiveKeyId,
|
||||
request.newKeyId,
|
||||
].every((value) => typeof value === 'string' && ID.test(value)) ||
|
||||
typeof request.expectedCatalogDigest !== 'string' ||
|
||||
!DIGEST.test(request.expectedCatalogDigest)
|
||||
) {
|
||||
throw new TypeError('Rotation command nested value is invalid');
|
||||
}
|
||||
const stagedMaterialFile = absoluteFilePath(
|
||||
candidate.stagedMaterialFile,
|
||||
'Staged material file path',
|
||||
);
|
||||
return Object.freeze({
|
||||
...(parsed as ClusterPromptOutputKeyRotationCommand),
|
||||
stagedMaterialFile,
|
||||
});
|
||||
} finally {
|
||||
if (descriptor !== undefined) closeSync(descriptor);
|
||||
}
|
||||
}
|
||||
|
||||
export function readClusterPromptOutputKeyRotationMaterial(
|
||||
filePathValue: string,
|
||||
): Buffer {
|
||||
const filePath = absoluteFilePath(filePathValue, 'Staged material file path');
|
||||
let descriptor: number | undefined;
|
||||
try {
|
||||
descriptor = openSync(
|
||||
filePath,
|
||||
constants.O_RDONLY | (constants.O_NOFOLLOW ?? 0),
|
||||
);
|
||||
const before = fstatSync(descriptor);
|
||||
if (
|
||||
!before.isFile() ||
|
||||
before.nlink !== 1 ||
|
||||
before.size !== 32 ||
|
||||
(before.mode & 0o222) !== 0 ||
|
||||
(before.mode & 0o111) !== 0 ||
|
||||
(before.mode & 0o007) !== 0 ||
|
||||
(before.mode & 0o440) === 0
|
||||
) {
|
||||
throw new TypeError('Staged rotation material is unavailable');
|
||||
}
|
||||
const material = readFileSync(descriptor);
|
||||
const after = fstatSync(descriptor);
|
||||
if (
|
||||
material.byteLength !== 32 ||
|
||||
after.dev !== before.dev ||
|
||||
after.ino !== before.ino ||
|
||||
after.size !== before.size ||
|
||||
after.mtimeMs !== before.mtimeMs
|
||||
) {
|
||||
material.fill(0);
|
||||
throw new TypeError('Staged rotation material changed during read');
|
||||
}
|
||||
return material;
|
||||
} finally {
|
||||
if (descriptor !== undefined) closeSync(descriptor);
|
||||
}
|
||||
}
|
||||
+147
@@ -0,0 +1,147 @@
|
||||
/** Prompt Output key rotation transaction composition boundary. */
|
||||
import type { OpenPostgresDatabase } from '@qinglong/runtime-core';
|
||||
import {
|
||||
createPostgresDatabaseOpener,
|
||||
type PostgresConnectionOptions,
|
||||
type PostgresPoolOptions,
|
||||
} from '@qinglong/cluster-postgres/ai-maintenance';
|
||||
import {
|
||||
PluginPackagePromptOutputKeyRotationCoordinator,
|
||||
normalizePluginPackagePromptOutputKeyRotationRequest,
|
||||
type PluginPackagePromptOutputKeyRotationMaterialAuthority,
|
||||
type PluginPackagePromptOutputKeyRotationRequest,
|
||||
} from '@qinglong/ai/plugin-package-prompt-output-key-rotation';
|
||||
import { PostgresPluginPackagePromptOutputKeyRotationRepository } from '@qinglong/ai/postgres-plugin-package-prompt-output-key-rotation-storage';
|
||||
import {
|
||||
assertPostgresPluginPackagePromptOutputMaintenanceReady,
|
||||
type PostgresPluginPackagePromptOutputMaintenanceReadinessReport,
|
||||
} from '@qinglong/ai/postgres-plugin-package-prompt-output-retention-storage';
|
||||
|
||||
export interface RunClusterPromptOutputKeyRotationProcessOptions {
|
||||
readonly database: Readonly<{
|
||||
readonly connection: PostgresConnectionOptions;
|
||||
readonly pool?: PostgresPoolOptions;
|
||||
}>;
|
||||
readonly request: Readonly<PluginPackagePromptOutputKeyRotationRequest>;
|
||||
readonly material: Uint8Array;
|
||||
readonly materials: PluginPackagePromptOutputKeyRotationMaterialAuthority;
|
||||
readonly openDatabase?: OpenPostgresDatabase;
|
||||
}
|
||||
|
||||
export interface ClusterPromptOutputKeyRotationProcessResult {
|
||||
readonly readiness: PostgresPluginPackagePromptOutputMaintenanceReadinessReport;
|
||||
readonly status: 'completed' | 'existing';
|
||||
readonly rotationId: string;
|
||||
readonly requestId: string;
|
||||
readonly mutationId: string;
|
||||
readonly preparationDigest: string;
|
||||
readonly completionDigest: string;
|
||||
readonly generation: number;
|
||||
readonly previousActiveKeyId: string;
|
||||
readonly activeKeyId: string;
|
||||
readonly catalogDigest: string;
|
||||
readonly materialProof: string;
|
||||
readonly completedAtMs: number;
|
||||
}
|
||||
|
||||
export class ClusterPromptOutputKeyRotationProcessConfigError extends TypeError {
|
||||
readonly code = 'QL3_PROMPT_OUTPUT_KEY_ROTATION_PROCESS_CONFIG_INVALID';
|
||||
|
||||
constructor(message: string, readonly cause?: unknown) {
|
||||
super(
|
||||
`Prompt output key rotation process configuration is invalid: ${message}`,
|
||||
);
|
||||
this.name = 'ClusterPromptOutputKeyRotationProcessConfigError';
|
||||
}
|
||||
}
|
||||
|
||||
export async function runClusterPromptOutputKeyRotationProcess(
|
||||
options: RunClusterPromptOutputKeyRotationProcessOptions,
|
||||
): Promise<Readonly<ClusterPromptOutputKeyRotationProcessResult>> {
|
||||
if (
|
||||
!options ||
|
||||
typeof options !== 'object' ||
|
||||
Array.isArray(options) ||
|
||||
!options.database ||
|
||||
typeof options.database !== 'object' ||
|
||||
Array.isArray(options.database) ||
|
||||
!(options.material instanceof Uint8Array) ||
|
||||
options.material.byteLength !== 32 ||
|
||||
!options.materials ||
|
||||
typeof options.materials !== 'object' ||
|
||||
typeof options.materials.rotate !== 'function'
|
||||
) {
|
||||
throw new ClusterPromptOutputKeyRotationProcessConfigError(
|
||||
'options are invalid',
|
||||
);
|
||||
}
|
||||
let request;
|
||||
try {
|
||||
request = normalizePluginPackagePromptOutputKeyRotationRequest(
|
||||
options.request,
|
||||
);
|
||||
} catch (cause) {
|
||||
throw new ClusterPromptOutputKeyRotationProcessConfigError(
|
||||
'request is invalid',
|
||||
cause,
|
||||
);
|
||||
}
|
||||
let poolError: Error | undefined;
|
||||
const openDatabase =
|
||||
options.openDatabase ??
|
||||
createPostgresDatabaseOpener({
|
||||
role: 'ai-maintenance',
|
||||
connection: options.database.connection,
|
||||
...(options.database.pool === undefined
|
||||
? {}
|
||||
: { pool: options.database.pool }),
|
||||
onPoolError(error) {
|
||||
poolError ??= error;
|
||||
},
|
||||
});
|
||||
const database = await openDatabase();
|
||||
let failure: unknown;
|
||||
try {
|
||||
const readiness =
|
||||
await assertPostgresPluginPackagePromptOutputMaintenanceReady(
|
||||
database.pool,
|
||||
);
|
||||
const result = await new PluginPackagePromptOutputKeyRotationCoordinator({
|
||||
repository: new PostgresPluginPackagePromptOutputKeyRotationRepository({
|
||||
pool: database.pool,
|
||||
}),
|
||||
materials: options.materials,
|
||||
}).rotate({ request, material: options.material });
|
||||
if (poolError) throw poolError;
|
||||
return Object.freeze({
|
||||
readiness,
|
||||
status: result.status,
|
||||
rotationId: result.preparation.rotationId,
|
||||
requestId: result.preparation.requestId,
|
||||
mutationId: result.preparation.mutationId,
|
||||
preparationDigest: result.preparation.preparationDigest,
|
||||
completionDigest: result.completion.completionDigest,
|
||||
generation: result.completion.generation,
|
||||
previousActiveKeyId: result.completion.previousActiveKeyId,
|
||||
activeKeyId: result.completion.activeKeyId,
|
||||
catalogDigest: result.completion.catalogDigest,
|
||||
materialProof: result.completion.materialProof,
|
||||
completedAtMs: result.completion.completedAtMs,
|
||||
});
|
||||
} catch (cause) {
|
||||
failure = cause;
|
||||
throw cause;
|
||||
} finally {
|
||||
try {
|
||||
await database.close();
|
||||
} catch (closeError) {
|
||||
if (failure !== undefined) {
|
||||
throw new AggregateError(
|
||||
[failure, closeError],
|
||||
'Prompt output key rotation failed and PostgreSQL did not close',
|
||||
);
|
||||
}
|
||||
throw closeError;
|
||||
}
|
||||
}
|
||||
}
|
||||
+157
@@ -0,0 +1,157 @@
|
||||
/** Least-privilege Kubernetes Secret authority assembly boundary. */
|
||||
import {
|
||||
ClusterPromptOutputKubernetesSecretKeyring,
|
||||
type ClusterPromptOutputKubernetesSecretApi,
|
||||
type ClusterPromptOutputKubernetesSecretKeyringOptions,
|
||||
} from './promptOutputKubernetesSecretKeyring';
|
||||
|
||||
interface AccessReviewAttributes {
|
||||
readonly namespace?: string;
|
||||
readonly verb: string;
|
||||
readonly resource: string;
|
||||
readonly name?: string;
|
||||
}
|
||||
|
||||
interface AuthorizationApi {
|
||||
createSelfSubjectAccessReview(
|
||||
request: Readonly<{
|
||||
body: Readonly<{
|
||||
apiVersion: 'authorization.k8s.io/v1';
|
||||
kind: 'SelfSubjectAccessReview';
|
||||
spec: Readonly<{ resourceAttributes: AccessReviewAttributes }>;
|
||||
}>;
|
||||
}>,
|
||||
): Promise<
|
||||
Readonly<{
|
||||
status?: Readonly<{ allowed?: boolean; denied?: boolean }>;
|
||||
}>
|
||||
>;
|
||||
}
|
||||
|
||||
function accessMatrix(
|
||||
options: ClusterPromptOutputKubernetesSecretKeyringOptions,
|
||||
): Readonly<{
|
||||
allowed: readonly AccessReviewAttributes[];
|
||||
denied: readonly AccessReviewAttributes[];
|
||||
}> {
|
||||
return Object.freeze({
|
||||
allowed: Object.freeze([
|
||||
{
|
||||
namespace: options.namespace,
|
||||
verb: 'get',
|
||||
resource: 'secrets',
|
||||
name: options.secretName,
|
||||
},
|
||||
{
|
||||
namespace: options.namespace,
|
||||
verb: 'update',
|
||||
resource: 'secrets',
|
||||
name: options.secretName,
|
||||
},
|
||||
]),
|
||||
denied: Object.freeze([
|
||||
{ namespace: options.namespace, verb: 'list', resource: 'secrets' },
|
||||
{ namespace: options.namespace, verb: 'watch', resource: 'secrets' },
|
||||
{ namespace: options.namespace, verb: 'create', resource: 'secrets' },
|
||||
{
|
||||
namespace: options.namespace,
|
||||
verb: 'delete',
|
||||
resource: 'secrets',
|
||||
name: options.secretName,
|
||||
},
|
||||
{
|
||||
namespace: options.namespace,
|
||||
verb: 'patch',
|
||||
resource: 'secrets',
|
||||
name: options.secretName,
|
||||
},
|
||||
{
|
||||
namespace: options.namespace,
|
||||
verb: 'get',
|
||||
resource: 'secrets',
|
||||
name: `${options.secretName}-other`,
|
||||
},
|
||||
{ namespace: options.namespace, verb: 'get', resource: 'configmaps' },
|
||||
{ namespace: options.namespace, verb: 'get', resource: 'pods' },
|
||||
]),
|
||||
});
|
||||
}
|
||||
|
||||
async function assertExactKubernetesAuthority(
|
||||
api: AuthorizationApi,
|
||||
options: ClusterPromptOutputKubernetesSecretKeyringOptions,
|
||||
): Promise<void> {
|
||||
const matrix = accessMatrix(options);
|
||||
for (const [expected, checks] of [
|
||||
[true, matrix.allowed],
|
||||
[false, matrix.denied],
|
||||
] as const) {
|
||||
for (const attributes of checks) {
|
||||
const review = await api.createSelfSubjectAccessReview({
|
||||
body: {
|
||||
apiVersion: 'authorization.k8s.io/v1',
|
||||
kind: 'SelfSubjectAccessReview',
|
||||
spec: { resourceAttributes: attributes },
|
||||
},
|
||||
});
|
||||
if (
|
||||
review.status?.allowed !== expected ||
|
||||
(expected && review.status.denied === true)
|
||||
) {
|
||||
throw new TypeError(
|
||||
'Kubernetes Secret lifecycle authority is not exact',
|
||||
);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export async function openPromptOutputKubernetesSecretAuthority(
|
||||
options: ClusterPromptOutputKubernetesSecretKeyringOptions,
|
||||
): Promise<
|
||||
Readonly<{
|
||||
materials: ClusterPromptOutputKubernetesSecretKeyring;
|
||||
dispose(): void;
|
||||
}>
|
||||
> {
|
||||
const kubernetes = await import('@kubernetes/client-node');
|
||||
const config = new kubernetes.KubeConfig();
|
||||
config.loadFromCluster();
|
||||
const cluster = config.getCurrentCluster();
|
||||
let server: URL;
|
||||
try {
|
||||
server = new URL(cluster?.server ?? '');
|
||||
} catch {
|
||||
throw new TypeError('Kubernetes cluster authority is invalid');
|
||||
}
|
||||
if (
|
||||
!cluster ||
|
||||
server.protocol !== 'https:' ||
|
||||
server.username !== '' ||
|
||||
server.password !== '' ||
|
||||
server.hash !== '' ||
|
||||
cluster.skipTLSVerify === true ||
|
||||
(typeof cluster.caData !== 'string' && typeof cluster.caFile !== 'string')
|
||||
) {
|
||||
throw new TypeError('Kubernetes cluster authority is invalid');
|
||||
}
|
||||
const secrets = config.makeApiClient(
|
||||
kubernetes.CoreV1Api,
|
||||
) as unknown as ClusterPromptOutputKubernetesSecretApi;
|
||||
const authorization = config.makeApiClient(
|
||||
kubernetes.AuthorizationV1Api,
|
||||
) as unknown as AuthorizationApi;
|
||||
await assertExactKubernetesAuthority(authorization, options);
|
||||
let active = true;
|
||||
return Object.freeze({
|
||||
materials: new ClusterPromptOutputKubernetesSecretKeyring(secrets, options),
|
||||
dispose() {
|
||||
if (!active) return;
|
||||
active = false;
|
||||
for (const user of config.getUsers()) {
|
||||
(user as { token?: string }).token = '';
|
||||
}
|
||||
config.setCurrentContext('disposed');
|
||||
},
|
||||
});
|
||||
}
|
||||
+475
@@ -0,0 +1,475 @@
|
||||
/** ResourceVersion-fenced Prompt Output Kubernetes keyring boundary. */
|
||||
import { Buffer } from 'node:buffer';
|
||||
|
||||
import {
|
||||
canonicalPluginPackagePromptOutputKeyringManifest,
|
||||
inspectPluginPackagePromptOutputKeyringManifest,
|
||||
parsePluginPackagePromptOutputKeyringManifest,
|
||||
pluginPackagePromptOutputKeyringCatalogDigest,
|
||||
retirePluginPackagePromptOutputKeyringManifest,
|
||||
rotatePluginPackagePromptOutputKeyringManifest,
|
||||
type PluginPackagePromptOutputKeyringManifest,
|
||||
type PluginPackagePromptOutputKeyringRotationMutation,
|
||||
} from '@qinglong/ai/plugin-package-prompt-output-keyring-manifest';
|
||||
import {
|
||||
InvalidPluginPackagePromptOutputKeyRetirementError,
|
||||
PluginPackagePromptOutputKeyRetirementConflictError,
|
||||
PluginPackagePromptOutputKeyRetirementUnavailableError,
|
||||
type PluginPackagePromptOutputKeyMaterialState,
|
||||
type PluginPackagePromptOutputKeyRetirementMaterialAuthority,
|
||||
type PluginPackagePromptOutputKeyRetirementPreparation,
|
||||
} from '@qinglong/ai/plugin-package-prompt-output-key-retirement';
|
||||
|
||||
const DNS_LABEL = /^[a-z0-9](?:[-a-z0-9]{0,61}[a-z0-9])?$/;
|
||||
const DNS_SUBDOMAIN = /^[a-z0-9](?:[-a-z0-9.]{0,251}[a-z0-9])?$/;
|
||||
const DATA_KEY = /^[A-Za-z0-9._-]{1,253}$/;
|
||||
const UID = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
||||
const RESOURCE_VERSION = /^[1-9][0-9]{0,31}$/;
|
||||
const BASE64 =
|
||||
/^(?:[A-Za-z0-9+/]{4})*(?:[A-Za-z0-9+/]{2}==|[A-Za-z0-9+/]{3}=)?$/;
|
||||
const FIELD_MANAGER = 'qinglong-prompt-output-key-retirement';
|
||||
const ROTATION_FIELD_MANAGER = 'qinglong-prompt-output-key-rotation';
|
||||
const MANAGED_BY_LABEL = 'app.kubernetes.io/managed-by';
|
||||
const MANAGED_BY_VALUE = 'qinglong3';
|
||||
const KEYRING_LABEL = 'qinglong.io/prompt-output-keyring';
|
||||
const KEYRING_LABEL_VALUE = 'v1';
|
||||
const GENERATION_ANNOTATION = 'qinglong.io/prompt-output-keyring-generation';
|
||||
const CATALOG_DIGEST_ANNOTATION =
|
||||
'qinglong.io/prompt-output-keyring-catalog-digest';
|
||||
const LAST_APPLIED_ANNOTATION =
|
||||
'kubectl.kubernetes.io/last-applied-configuration';
|
||||
const MAX_SECRET_DATA_BYTES = 384 * 1024;
|
||||
|
||||
export interface ClusterPromptOutputKubernetesSecretKeyringOptions {
|
||||
readonly namespace: string;
|
||||
readonly secretName: string;
|
||||
readonly expectedSecretUid: string;
|
||||
readonly dataKey?: string;
|
||||
}
|
||||
|
||||
export interface ClusterPromptOutputKubernetesSecret {
|
||||
readonly apiVersion?: string;
|
||||
readonly kind?: string;
|
||||
readonly type?: string;
|
||||
readonly immutable?: boolean;
|
||||
readonly stringData?: Readonly<Record<string, string>>;
|
||||
readonly data?: Readonly<Record<string, string>>;
|
||||
readonly metadata?: Readonly<{
|
||||
name?: string;
|
||||
namespace?: string;
|
||||
uid?: string;
|
||||
resourceVersion?: string;
|
||||
deletionTimestamp?: Date | string;
|
||||
labels?: Readonly<Record<string, string>>;
|
||||
annotations?: Readonly<Record<string, string>>;
|
||||
[key: string]: unknown;
|
||||
}>;
|
||||
readonly [key: string]: unknown;
|
||||
}
|
||||
|
||||
interface ClusterPromptOutputKubernetesSecretWrite
|
||||
extends ClusterPromptOutputKubernetesSecret {
|
||||
readonly apiVersion: 'v1';
|
||||
readonly kind: 'Secret';
|
||||
readonly type: 'Opaque';
|
||||
readonly immutable: false;
|
||||
readonly metadata: NonNullable<
|
||||
ClusterPromptOutputKubernetesSecret['metadata']
|
||||
>;
|
||||
readonly data: Readonly<Record<string, string>>;
|
||||
}
|
||||
|
||||
export interface ClusterPromptOutputKubernetesSecretApi {
|
||||
readNamespacedSecret(
|
||||
request: Readonly<{
|
||||
name: string;
|
||||
namespace: string;
|
||||
}>,
|
||||
): Promise<ClusterPromptOutputKubernetesSecret>;
|
||||
replaceNamespacedSecret(
|
||||
request: Readonly<{
|
||||
name: string;
|
||||
namespace: string;
|
||||
body: ClusterPromptOutputKubernetesSecretWrite;
|
||||
fieldManager: typeof FIELD_MANAGER | typeof ROTATION_FIELD_MANAGER;
|
||||
fieldValidation: 'Strict';
|
||||
}>,
|
||||
): Promise<ClusterPromptOutputKubernetesSecret>;
|
||||
}
|
||||
|
||||
interface StoredKeyring {
|
||||
readonly secret: ClusterPromptOutputKubernetesSecret;
|
||||
readonly manifest: Readonly<PluginPackagePromptOutputKeyringManifest>;
|
||||
readonly resourceVersion: string;
|
||||
}
|
||||
|
||||
function unavailable(
|
||||
cause?: unknown,
|
||||
): PluginPackagePromptOutputKeyRetirementUnavailableError {
|
||||
return new PluginPackagePromptOutputKeyRetirementUnavailableError({
|
||||
cause: cause instanceof Error ? cause : undefined,
|
||||
});
|
||||
}
|
||||
|
||||
function apiStatus(cause: unknown): number | null {
|
||||
if (!cause || typeof cause !== 'object') return null;
|
||||
if ('code' in cause && typeof cause.code === 'number') return cause.code;
|
||||
if (
|
||||
'response' in cause &&
|
||||
cause.response &&
|
||||
typeof cause.response === 'object' &&
|
||||
'statusCode' in cause.response &&
|
||||
typeof cause.response.statusCode === 'number'
|
||||
) {
|
||||
return cause.response.statusCode;
|
||||
}
|
||||
return null;
|
||||
}
|
||||
|
||||
function exactKeys(value: object, expected: readonly string[]): boolean {
|
||||
const actual = Object.keys(value).sort();
|
||||
const canonical = [...expected].sort();
|
||||
return (
|
||||
actual.length === canonical.length &&
|
||||
actual.every((key, index) => key === canonical[index])
|
||||
);
|
||||
}
|
||||
|
||||
function option(value: unknown, pattern: RegExp, label: string): string {
|
||||
if (typeof value !== 'string' || !pattern.test(value)) {
|
||||
throw new InvalidPluginPackagePromptOutputKeyRetirementError(
|
||||
`${label} is invalid`,
|
||||
);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function sameAbsentState(
|
||||
left: Readonly<{
|
||||
state: 'absent';
|
||||
keyId: string;
|
||||
catalogDigest: string;
|
||||
absenceProof: string;
|
||||
}>,
|
||||
right: PluginPackagePromptOutputKeyMaterialState,
|
||||
): boolean {
|
||||
return (
|
||||
right.state === 'absent' &&
|
||||
right.keyId === left.keyId &&
|
||||
right.catalogDigest === left.catalogDigest &&
|
||||
right.absenceProof === left.absenceProof
|
||||
);
|
||||
}
|
||||
|
||||
/**
|
||||
* Short-lived, resourceVersion-fenced adapter for one dedicated mutable Secret.
|
||||
* It owns no timer, watcher, cache, Secret creation, or runtime key resolution.
|
||||
*/
|
||||
export class ClusterPromptOutputKubernetesSecretKeyring
|
||||
implements PluginPackagePromptOutputKeyRetirementMaterialAuthority
|
||||
{
|
||||
readonly #namespace: string;
|
||||
readonly #secretName: string;
|
||||
readonly #expectedSecretUid: string;
|
||||
readonly #dataKey: string;
|
||||
|
||||
constructor(
|
||||
private readonly api: ClusterPromptOutputKubernetesSecretApi,
|
||||
options: ClusterPromptOutputKubernetesSecretKeyringOptions,
|
||||
) {
|
||||
if (
|
||||
!api ||
|
||||
typeof api !== 'object' ||
|
||||
typeof api.readNamespacedSecret !== 'function' ||
|
||||
typeof api.replaceNamespacedSecret !== 'function' ||
|
||||
!options ||
|
||||
typeof options !== 'object' ||
|
||||
Array.isArray(options)
|
||||
) {
|
||||
throw new InvalidPluginPackagePromptOutputKeyRetirementError(
|
||||
'Kubernetes Secret keyring options are invalid',
|
||||
);
|
||||
}
|
||||
this.#namespace = option(options.namespace, DNS_LABEL, 'namespace');
|
||||
this.#secretName = option(options.secretName, DNS_SUBDOMAIN, 'secretName');
|
||||
this.#expectedSecretUid = option(
|
||||
options.expectedSecretUid,
|
||||
UID,
|
||||
'expectedSecretUid',
|
||||
);
|
||||
this.#dataKey = option(
|
||||
options.dataKey ?? 'keyring.json',
|
||||
DATA_KEY,
|
||||
'dataKey',
|
||||
);
|
||||
}
|
||||
|
||||
async inspect(
|
||||
keyId: string,
|
||||
): Promise<PluginPackagePromptOutputKeyMaterialState> {
|
||||
return inspectPluginPackagePromptOutputKeyringManifest(
|
||||
(await this.#read()).manifest,
|
||||
keyId,
|
||||
);
|
||||
}
|
||||
|
||||
async retire(
|
||||
command: Readonly<{
|
||||
preparation: Readonly<PluginPackagePromptOutputKeyRetirementPreparation>;
|
||||
}>,
|
||||
): Promise<
|
||||
Readonly<{
|
||||
state: 'absent';
|
||||
keyId: string;
|
||||
catalogDigest: string;
|
||||
absenceProof: string;
|
||||
}>
|
||||
> {
|
||||
const current = await this.#read();
|
||||
const mutation = retirePluginPackagePromptOutputKeyringManifest(
|
||||
current.manifest,
|
||||
command.preparation,
|
||||
);
|
||||
if (!mutation.changed) return mutation.state;
|
||||
try {
|
||||
const written = this.#parse(
|
||||
await this.api.replaceNamespacedSecret({
|
||||
name: this.#secretName,
|
||||
namespace: this.#namespace,
|
||||
body: this.#body(current, mutation.manifest),
|
||||
fieldManager: FIELD_MANAGER,
|
||||
fieldValidation: 'Strict',
|
||||
}),
|
||||
);
|
||||
const state = inspectPluginPackagePromptOutputKeyringManifest(
|
||||
written.manifest,
|
||||
mutation.state.keyId,
|
||||
);
|
||||
if (!sameAbsentState(mutation.state, state)) {
|
||||
throw new PluginPackagePromptOutputKeyRetirementConflictError();
|
||||
}
|
||||
return mutation.state;
|
||||
} catch (cause) {
|
||||
const status = apiStatus(cause);
|
||||
if (status !== 409 && status !== null) {
|
||||
if (
|
||||
cause instanceof
|
||||
PluginPackagePromptOutputKeyRetirementConflictError ||
|
||||
cause instanceof
|
||||
PluginPackagePromptOutputKeyRetirementUnavailableError
|
||||
) {
|
||||
throw cause;
|
||||
}
|
||||
throw unavailable(cause);
|
||||
}
|
||||
try {
|
||||
const winner = retirePluginPackagePromptOutputKeyringManifest(
|
||||
(await this.#read()).manifest,
|
||||
command.preparation,
|
||||
);
|
||||
if (!winner.changed && sameAbsentState(mutation.state, winner.state)) {
|
||||
return winner.state;
|
||||
}
|
||||
} catch (replayCause) {
|
||||
if (status === null) throw unavailable(cause);
|
||||
throw replayCause;
|
||||
}
|
||||
if (status === null) throw unavailable(cause);
|
||||
throw new PluginPackagePromptOutputKeyRetirementConflictError();
|
||||
}
|
||||
}
|
||||
|
||||
async rotate(
|
||||
command: Readonly<{
|
||||
expectedActiveKeyId: string;
|
||||
expectedCatalogDigest: string;
|
||||
newKeyId: string;
|
||||
material: Uint8Array;
|
||||
}>,
|
||||
): Promise<
|
||||
Readonly<PluginPackagePromptOutputKeyringRotationMutation['state']>
|
||||
> {
|
||||
const current = await this.#read();
|
||||
const mutation = rotatePluginPackagePromptOutputKeyringManifest(
|
||||
current.manifest,
|
||||
command,
|
||||
);
|
||||
if (!mutation.changed) return mutation.state;
|
||||
try {
|
||||
const written = this.#parse(
|
||||
await this.api.replaceNamespacedSecret({
|
||||
name: this.#secretName,
|
||||
namespace: this.#namespace,
|
||||
body: this.#body(current, mutation.manifest),
|
||||
fieldManager: ROTATION_FIELD_MANAGER,
|
||||
fieldValidation: 'Strict',
|
||||
}),
|
||||
);
|
||||
const winner = rotatePluginPackagePromptOutputKeyringManifest(
|
||||
written.manifest,
|
||||
command,
|
||||
);
|
||||
if (winner.changed) {
|
||||
throw new PluginPackagePromptOutputKeyRetirementConflictError();
|
||||
}
|
||||
return winner.state;
|
||||
} catch (cause) {
|
||||
const status = apiStatus(cause);
|
||||
if (status !== 409 && status !== null) {
|
||||
if (
|
||||
cause instanceof
|
||||
PluginPackagePromptOutputKeyRetirementConflictError ||
|
||||
cause instanceof
|
||||
PluginPackagePromptOutputKeyRetirementUnavailableError
|
||||
) {
|
||||
throw cause;
|
||||
}
|
||||
throw unavailable(cause);
|
||||
}
|
||||
try {
|
||||
const winner = rotatePluginPackagePromptOutputKeyringManifest(
|
||||
(await this.#read()).manifest,
|
||||
command,
|
||||
);
|
||||
if (!winner.changed) return winner.state;
|
||||
} catch (replayCause) {
|
||||
if (status === null) throw unavailable(cause);
|
||||
throw replayCause;
|
||||
}
|
||||
if (status === null) throw unavailable(cause);
|
||||
throw new PluginPackagePromptOutputKeyRetirementConflictError();
|
||||
}
|
||||
}
|
||||
|
||||
async #read(): Promise<StoredKeyring> {
|
||||
try {
|
||||
return this.#parse(
|
||||
await this.api.readNamespacedSecret({
|
||||
name: this.#secretName,
|
||||
namespace: this.#namespace,
|
||||
}),
|
||||
);
|
||||
} catch (cause) {
|
||||
if (
|
||||
cause instanceof PluginPackagePromptOutputKeyRetirementConflictError ||
|
||||
cause instanceof PluginPackagePromptOutputKeyRetirementUnavailableError
|
||||
) {
|
||||
throw cause;
|
||||
}
|
||||
throw unavailable(cause);
|
||||
}
|
||||
}
|
||||
|
||||
#parse(secret: ClusterPromptOutputKubernetesSecret): StoredKeyring {
|
||||
const metadata = secret?.metadata;
|
||||
const data = secret?.data;
|
||||
const encoded = data?.[this.#dataKey];
|
||||
let bytes: Buffer | undefined;
|
||||
let canonical: Buffer | undefined;
|
||||
try {
|
||||
if (
|
||||
secret.apiVersion !== 'v1' ||
|
||||
secret.kind !== 'Secret' ||
|
||||
secret.type !== 'Opaque' ||
|
||||
secret.immutable !== false ||
|
||||
secret.stringData !== undefined ||
|
||||
!metadata ||
|
||||
metadata.name !== this.#secretName ||
|
||||
metadata.namespace !== this.#namespace ||
|
||||
metadata.uid !== this.#expectedSecretUid ||
|
||||
typeof metadata.resourceVersion !== 'string' ||
|
||||
!RESOURCE_VERSION.test(metadata.resourceVersion) ||
|
||||
metadata.deletionTimestamp !== undefined ||
|
||||
metadata.labels?.[MANAGED_BY_LABEL] !== MANAGED_BY_VALUE ||
|
||||
metadata.labels?.[KEYRING_LABEL] !== KEYRING_LABEL_VALUE ||
|
||||
metadata.annotations?.[LAST_APPLIED_ANNOTATION] !== undefined ||
|
||||
!data ||
|
||||
!exactKeys(data, [this.#dataKey]) ||
|
||||
typeof encoded !== 'string' ||
|
||||
encoded.length < 1 ||
|
||||
encoded.length > MAX_SECRET_DATA_BYTES ||
|
||||
!BASE64.test(encoded)
|
||||
) {
|
||||
throw unavailable();
|
||||
}
|
||||
bytes = Buffer.from(encoded, 'base64');
|
||||
if (bytes.toString('base64') !== encoded) throw unavailable();
|
||||
const manifest = parsePluginPackagePromptOutputKeyringManifest(bytes);
|
||||
canonical = canonicalPluginPackagePromptOutputKeyringManifest(manifest);
|
||||
if (
|
||||
!bytes.equals(canonical) ||
|
||||
metadata.annotations?.[GENERATION_ANNOTATION] !==
|
||||
String(manifest.generation) ||
|
||||
metadata.annotations?.[CATALOG_DIGEST_ANNOTATION] !==
|
||||
pluginPackagePromptOutputKeyringCatalogDigest(manifest)
|
||||
) {
|
||||
throw unavailable();
|
||||
}
|
||||
return Object.freeze({
|
||||
secret,
|
||||
manifest,
|
||||
resourceVersion: metadata.resourceVersion,
|
||||
});
|
||||
} catch (cause) {
|
||||
throw cause instanceof
|
||||
PluginPackagePromptOutputKeyRetirementUnavailableError
|
||||
? cause
|
||||
: unavailable(cause);
|
||||
} finally {
|
||||
bytes?.fill(0);
|
||||
canonical?.fill(0);
|
||||
}
|
||||
}
|
||||
|
||||
#body(
|
||||
current: StoredKeyring,
|
||||
manifest: Readonly<PluginPackagePromptOutputKeyringManifest>,
|
||||
): ClusterPromptOutputKubernetesSecretWrite {
|
||||
const bytes = canonicalPluginPackagePromptOutputKeyringManifest(manifest);
|
||||
const { stringData: _ignoredStringData, ...secretWithoutStringData } =
|
||||
current.secret;
|
||||
try {
|
||||
return Object.freeze({
|
||||
...secretWithoutStringData,
|
||||
apiVersion: 'v1' as const,
|
||||
kind: 'Secret' as const,
|
||||
type: 'Opaque' as const,
|
||||
immutable: false as const,
|
||||
metadata: Object.freeze({
|
||||
...current.secret.metadata,
|
||||
name: this.#secretName,
|
||||
namespace: this.#namespace,
|
||||
uid: this.#expectedSecretUid,
|
||||
resourceVersion: current.resourceVersion,
|
||||
labels: Object.freeze({
|
||||
...current.secret.metadata?.labels,
|
||||
[MANAGED_BY_LABEL]: MANAGED_BY_VALUE,
|
||||
[KEYRING_LABEL]: KEYRING_LABEL_VALUE,
|
||||
}),
|
||||
annotations: Object.freeze({
|
||||
...current.secret.metadata?.annotations,
|
||||
[GENERATION_ANNOTATION]: String(manifest.generation),
|
||||
[CATALOG_DIGEST_ANNOTATION]:
|
||||
pluginPackagePromptOutputKeyringCatalogDigest(manifest),
|
||||
}),
|
||||
}),
|
||||
data: Object.freeze({ [this.#dataKey]: bytes.toString('base64') }),
|
||||
});
|
||||
} finally {
|
||||
bytes.fill(0);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
export const clusterPromptOutputKubernetesSecretKeyringMetadata = Object.freeze(
|
||||
{
|
||||
fieldManager: FIELD_MANAGER,
|
||||
rotationFieldManager: ROTATION_FIELD_MANAGER,
|
||||
managedByLabel: MANAGED_BY_LABEL,
|
||||
managedByValue: MANAGED_BY_VALUE,
|
||||
keyringLabel: KEYRING_LABEL,
|
||||
keyringLabelValue: KEYRING_LABEL_VALUE,
|
||||
generationAnnotation: GENERATION_ANNOTATION,
|
||||
catalogDigestAnnotation: CATALOG_DIGEST_ANNOTATION,
|
||||
},
|
||||
);
|
||||
+42
@@ -0,0 +1,42 @@
|
||||
/** Bounded Prompt Output maintenance PostgreSQL connection boundary. */
|
||||
import {
|
||||
loadPostgresCertificateAuthorityFile,
|
||||
loadPostgresConnectionEnvironment,
|
||||
type PostgresConnectionOptions,
|
||||
} from '@qinglong/cluster-postgres/ai-maintenance';
|
||||
|
||||
export function loadPromptOutputPostgresMaintenanceConnection(
|
||||
environment: NodeJS.ProcessEnv,
|
||||
): PostgresConnectionOptions {
|
||||
const base = loadPostgresConnectionEnvironment(environment, {
|
||||
connectionString: 'QL3_POSTGRES_AI_MAINTENANCE_URL',
|
||||
host: 'QL3_POSTGRES_AI_MAINTENANCE_HOST',
|
||||
port: 'QL3_POSTGRES_AI_MAINTENANCE_PORT',
|
||||
database: 'QL3_POSTGRES_AI_MAINTENANCE_DATABASE',
|
||||
user: 'QL3_POSTGRES_AI_MAINTENANCE_USER',
|
||||
password: 'QL3_POSTGRES_AI_MAINTENANCE_PASSWORD',
|
||||
});
|
||||
const mode = environment.QL3_POSTGRES_TLS_MODE ?? 'verify-full';
|
||||
if (mode === 'disable') {
|
||||
if (environment.QL3_POSTGRES_ALLOW_INSECURE !== 'true') {
|
||||
throw new TypeError('Insecure PostgreSQL requires an explicit gate');
|
||||
}
|
||||
return Object.freeze({ ...base, tls: { mode: 'disable' as const } });
|
||||
}
|
||||
if (mode !== 'verify-full') {
|
||||
throw new TypeError('PostgreSQL TLS mode is invalid');
|
||||
}
|
||||
const caFile = environment.QL3_POSTGRES_TLS_CA_FILE;
|
||||
const servername = environment.QL3_POSTGRES_TLS_SERVERNAME;
|
||||
if (!caFile || !servername) {
|
||||
throw new TypeError('PostgreSQL TLS CA and servername are required');
|
||||
}
|
||||
return Object.freeze({
|
||||
...base,
|
||||
tls: {
|
||||
mode: 'verify-full' as const,
|
||||
ca: loadPostgresCertificateAuthorityFile(caFile),
|
||||
servername,
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -0,0 +1,144 @@
|
||||
#!/usr/bin/env node
|
||||
|
||||
/** One-shot Prompt Output garbage collection CLI boundary. */
|
||||
import { readFileSync } from 'node:fs';
|
||||
import path from 'node:path';
|
||||
|
||||
import {
|
||||
loadPostgresCertificateAuthorityFile,
|
||||
loadPostgresConnectionEnvironment,
|
||||
type PostgresConnectionOptions,
|
||||
} from '@qinglong/cluster-postgres/ai-maintenance';
|
||||
import type { PluginPackagePromptOutputRetentionPolicyCatalog } from '@qinglong/ai/plugin-package-prompt-output-retention';
|
||||
|
||||
import { runClusterPromptOutputGcProcess } from './promptOutputGcProcess';
|
||||
|
||||
const USAGE =
|
||||
'Usage: ql3-prompt-output-gc run --policy-file /absolute/retention-policies.json';
|
||||
const MAX_POLICY_FILE_BYTES = 65_536;
|
||||
|
||||
function policyCatalog(
|
||||
filePath: string,
|
||||
): PluginPackagePromptOutputRetentionPolicyCatalog {
|
||||
if (!path.isAbsolute(filePath) || filePath.includes('\0')) {
|
||||
throw new TypeError('Policy file path is invalid');
|
||||
}
|
||||
const bytes = readFileSync(filePath);
|
||||
if (bytes.length < 1 || bytes.length > MAX_POLICY_FILE_BYTES) {
|
||||
throw new TypeError('Policy file size is invalid');
|
||||
}
|
||||
return JSON.parse(
|
||||
bytes.toString('utf8'),
|
||||
) as PluginPackagePromptOutputRetentionPolicyCatalog;
|
||||
}
|
||||
|
||||
function limit(): number {
|
||||
const raw = process.env.QL3_PROMPT_OUTPUT_GC_LIMIT ?? '32';
|
||||
if (!/^\d+$/.test(raw)) throw new TypeError('GC limit is invalid');
|
||||
const value = Number(raw);
|
||||
if (!Number.isSafeInteger(value) || value < 1 || value > 128) {
|
||||
throw new TypeError('GC limit is invalid');
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function connection(): PostgresConnectionOptions {
|
||||
const base = loadPostgresConnectionEnvironment(process.env, {
|
||||
connectionString: 'QL3_POSTGRES_AI_MAINTENANCE_URL',
|
||||
host: 'QL3_POSTGRES_AI_MAINTENANCE_HOST',
|
||||
port: 'QL3_POSTGRES_AI_MAINTENANCE_PORT',
|
||||
database: 'QL3_POSTGRES_AI_MAINTENANCE_DATABASE',
|
||||
user: 'QL3_POSTGRES_AI_MAINTENANCE_USER',
|
||||
password: 'QL3_POSTGRES_AI_MAINTENANCE_PASSWORD',
|
||||
});
|
||||
const mode = process.env.QL3_POSTGRES_TLS_MODE ?? 'verify-full';
|
||||
if (mode === 'disable') {
|
||||
if (process.env.QL3_POSTGRES_ALLOW_INSECURE !== 'true') {
|
||||
throw new TypeError('Insecure PostgreSQL requires an explicit gate');
|
||||
}
|
||||
return Object.freeze({ ...base, tls: { mode: 'disable' as const } });
|
||||
}
|
||||
if (mode !== 'verify-full')
|
||||
throw new TypeError('PostgreSQL TLS mode is invalid');
|
||||
const caFile = process.env.QL3_POSTGRES_TLS_CA_FILE;
|
||||
const servername = process.env.QL3_POSTGRES_TLS_SERVERNAME;
|
||||
if (!caFile || !servername) {
|
||||
throw new TypeError('PostgreSQL TLS CA and servername are required');
|
||||
}
|
||||
return Object.freeze({
|
||||
...base,
|
||||
tls: {
|
||||
mode: 'verify-full' as const,
|
||||
ca: loadPostgresCertificateAuthorityFile(caFile),
|
||||
servername,
|
||||
},
|
||||
});
|
||||
}
|
||||
|
||||
async function main(argv: readonly string[]): Promise<void> {
|
||||
if (argv.length === 1 && (argv[0] === '--help' || argv[0] === '-h')) {
|
||||
process.stdout.write(`${USAGE}\n`);
|
||||
return;
|
||||
}
|
||||
if (
|
||||
argv.length !== 3 ||
|
||||
argv[0] !== 'run' ||
|
||||
argv[1] !== '--policy-file' ||
|
||||
!argv[2]
|
||||
) {
|
||||
process.stderr.write(
|
||||
`${JSON.stringify({
|
||||
code: 'QL3_PROMPT_OUTPUT_GC_CLI_USAGE_INVALID',
|
||||
message: USAGE,
|
||||
})}\n`,
|
||||
);
|
||||
process.exitCode = 64;
|
||||
return;
|
||||
}
|
||||
try {
|
||||
const result = await runClusterPromptOutputGcProcess({
|
||||
database: {
|
||||
connection: connection(),
|
||||
pool: {
|
||||
applicationName: 'qinglong3-prompt-output-gc',
|
||||
maxConnections: 1,
|
||||
},
|
||||
},
|
||||
retentionPolicyCatalog: policyCatalog(argv[2]),
|
||||
limit: limit(),
|
||||
});
|
||||
process.stdout.write(
|
||||
`${JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
component: 'qinglong3-prompt-output-gc',
|
||||
event: 'gc_completed',
|
||||
scanned: result.scanned,
|
||||
tombstoned: result.tombstoned,
|
||||
skipped: result.skipped,
|
||||
hasMore: result.hasMore,
|
||||
})}\n`,
|
||||
);
|
||||
} catch (error) {
|
||||
const candidate = error as {
|
||||
readonly code?: unknown;
|
||||
readonly name?: unknown;
|
||||
};
|
||||
process.stderr.write(
|
||||
`${JSON.stringify({
|
||||
schemaVersion: 1,
|
||||
component: 'qinglong3-prompt-output-gc',
|
||||
event: 'gc_failed',
|
||||
name:
|
||||
typeof candidate.name === 'string'
|
||||
? candidate.name.slice(0, 128)
|
||||
: 'Error',
|
||||
...(typeof candidate.code === 'string'
|
||||
? { code: candidate.code.slice(0, 128) }
|
||||
: {}),
|
||||
})}\n`,
|
||||
);
|
||||
process.exitCode = 1;
|
||||
}
|
||||
}
|
||||
|
||||
void main(process.argv.slice(2));
|
||||
@@ -0,0 +1,112 @@
|
||||
/** Prompt Output garbage collection PostgreSQL process boundary. */
|
||||
import type { OpenPostgresDatabase } from '@qinglong/runtime-core';
|
||||
import {
|
||||
createPostgresDatabaseOpener,
|
||||
type PostgresConnectionOptions,
|
||||
type PostgresPoolOptions,
|
||||
} from '@qinglong/cluster-postgres/ai-maintenance';
|
||||
import {
|
||||
PostgresPluginPackagePromptOutputGarbageCollector,
|
||||
assertPostgresPluginPackagePromptOutputMaintenanceReady,
|
||||
type PostgresPluginPackagePromptOutputMaintenanceReadinessReport,
|
||||
} from '@qinglong/ai/postgres-plugin-package-prompt-output-retention-storage';
|
||||
import {
|
||||
createPluginPackagePromptOutputRetentionPolicyCatalogResolver,
|
||||
type PluginPackagePromptOutputRetentionPolicyCatalog,
|
||||
} from '@qinglong/ai/plugin-package-prompt-output-retention';
|
||||
|
||||
export interface RunClusterPromptOutputGcProcessOptions {
|
||||
readonly database: Readonly<{
|
||||
readonly connection: PostgresConnectionOptions;
|
||||
readonly pool?: PostgresPoolOptions;
|
||||
}>;
|
||||
readonly retentionPolicyCatalog: PluginPackagePromptOutputRetentionPolicyCatalog;
|
||||
readonly limit?: number;
|
||||
readonly openDatabase?: OpenPostgresDatabase;
|
||||
}
|
||||
|
||||
export interface ClusterPromptOutputGcProcessResult {
|
||||
readonly readiness: PostgresPluginPackagePromptOutputMaintenanceReadinessReport;
|
||||
readonly scanned: number;
|
||||
readonly tombstoned: number;
|
||||
readonly skipped: number;
|
||||
readonly hasMore: boolean;
|
||||
}
|
||||
|
||||
export class ClusterPromptOutputGcProcessConfigError extends TypeError {
|
||||
readonly code = 'QL3_PROMPT_OUTPUT_GC_PROCESS_CONFIG_INVALID';
|
||||
|
||||
constructor(message: string, readonly cause?: unknown) {
|
||||
super(`Prompt output GC process configuration is invalid: ${message}`);
|
||||
this.name = 'ClusterPromptOutputGcProcessConfigError';
|
||||
}
|
||||
}
|
||||
|
||||
export async function runClusterPromptOutputGcProcess(
|
||||
options: RunClusterPromptOutputGcProcessOptions,
|
||||
): Promise<Readonly<ClusterPromptOutputGcProcessResult>> {
|
||||
if (
|
||||
!options ||
|
||||
typeof options !== 'object' ||
|
||||
Array.isArray(options) ||
|
||||
!options.database ||
|
||||
typeof options.database !== 'object' ||
|
||||
Array.isArray(options.database)
|
||||
) {
|
||||
throw new ClusterPromptOutputGcProcessConfigError('options are invalid');
|
||||
}
|
||||
let policies;
|
||||
try {
|
||||
policies = createPluginPackagePromptOutputRetentionPolicyCatalogResolver(
|
||||
options.retentionPolicyCatalog,
|
||||
);
|
||||
} catch (cause) {
|
||||
throw new ClusterPromptOutputGcProcessConfigError(
|
||||
'retention policy catalog is invalid',
|
||||
cause,
|
||||
);
|
||||
}
|
||||
let poolError: Error | undefined;
|
||||
const openDatabase =
|
||||
options.openDatabase ??
|
||||
createPostgresDatabaseOpener({
|
||||
role: 'ai-maintenance',
|
||||
connection: options.database.connection,
|
||||
...(options.database.pool === undefined
|
||||
? {}
|
||||
: { pool: options.database.pool }),
|
||||
onPoolError(error) {
|
||||
poolError ??= error;
|
||||
},
|
||||
});
|
||||
const database = await openDatabase();
|
||||
let failure: unknown;
|
||||
try {
|
||||
const readiness =
|
||||
await assertPostgresPluginPackagePromptOutputMaintenanceReady(
|
||||
database.pool,
|
||||
);
|
||||
const result = await new PostgresPluginPackagePromptOutputGarbageCollector({
|
||||
pool: database.pool,
|
||||
policies,
|
||||
...(options.limit === undefined ? {} : { limit: options.limit }),
|
||||
}).collect();
|
||||
if (poolError) throw poolError;
|
||||
return Object.freeze({ readiness, ...result });
|
||||
} catch (cause) {
|
||||
failure = cause;
|
||||
throw cause;
|
||||
} finally {
|
||||
try {
|
||||
await database.close();
|
||||
} catch (closeError) {
|
||||
if (failure !== undefined) {
|
||||
throw new AggregateError(
|
||||
[failure, closeError],
|
||||
'Prompt output GC failed and PostgreSQL did not close',
|
||||
);
|
||||
}
|
||||
throw closeError;
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user