feat(ql3): establish 3.0 incubation baseline

This commit is contained in:
whyour committed 2026-08-12 00:25:26 +08:00
1 parent 4bf92dcfeb
commit c699c32461
2817 files changed
+779642 -653

No files matched your search

@@ -0,0 +1,282 @@
const assert = require('node:assert/strict');
const { test } = require('node:test');
const {
ClusterControlAdmissionSecurityError,
createClusterControlAdmissionPipeline,
createClusterControlProjectPolicyAuthorizer,
} = require('@qinglong/cluster-control/admission');
const {
createClusterControlRouteRegistry,
} = require('@qinglong/cluster-control/routes');
const NOW = 10_000;
const PRINCIPAL = Object.freeze({
subject: Object.freeze({ type: 'user', id: 'usr_primary' }),
authenticationId: 'session:abc123',
authenticatedAtMs: 9_000,
expiresAtMs: 11_000,
assurance: 'multi_factor',
});
const METADATA = Object.freeze({
requestId: 'request-1',
method: 'POST',
path: '/api/v3/projects/prj_default/runs',
query: Object.freeze({}),
headers: Object.freeze({ authorization: 'Bearer opaque' }),
signal: new AbortController().signal,
});
function options(overrides = {}) {
const events = overrides.events ?? [];
return {
routes: createClusterControlRouteRegistry([
{
method: 'POST',
path: '/api/v3/projects/{projectId}/runs',
operationId: 'run.create',
permission: 'run.start',
projectParameter: 'projectId',
handle(input, parameters) {
events.push(
`handle:${parameters.projectId}:${input.request.body.taskId}`,
);
return { statusCode: 202, body: { accepted: true } };
},
},
]),
authenticator: {
authenticate() {
events.push('authenticate');
return PRINCIPAL;
},
},
policy: {
authorize(request) {
events.push(`authorize:${request.permission}`);
return {
effect: 'allow',
reasons: ['role_grant'],
fence: { projectVersion: 2, bindingVersion: 3 },
};
},
},
audit: {
record(record) {
events.push(`audit:${record.outcome}`);
},
},
now: () => NOW,
...overrides,
};
}
test('authenticates, authorizes and audits before accepting a body', async () => {
const events = [];
const pipeline = createClusterControlAdmissionPipeline(options({ events }));
const prepared = await pipeline.prepare(METADATA);
assert.deepEqual(events, [
'authenticate',
'authorize:run.start',
'audit:allowed',
]);
assert.deepEqual(await prepared.handle({ taskId: 'task-1' }), {
statusCode: 202,
body: { accepted: true },
});
assert.deepEqual(events.slice(-1), ['handle:prj_default:task-1']);
});
test('requires a reviewed route registry and rejects unknown routes before authentication', async () => {
assert.throws(
() =>
createClusterControlAdmissionPipeline(
options({
routes: {
contractVersion: 1,
size: 1,
resolve() {
return null;
},
},
}),
),
/options are invalid/,
);
const events = [];
const pipeline = createClusterControlAdmissionPipeline(options({ events }));
await assert.rejects(
pipeline.prepare({
...METADATA,
path: '/api/v3/projects/prj_default/tasks',
}),
(error) =>
error instanceof ClusterControlAdmissionSecurityError &&
error.statusCode === 404 &&
error.code === 'route_not_found',
);
assert.deepEqual(events, []);
});
test('rejects missing authentication before policy and handler execution', async () => {
const events = [];
const pipeline = createClusterControlAdmissionPipeline(
options({
events,
authenticator: {
authenticate() {
events.push('authenticate');
return null;
},
},
}),
);
await assert.rejects(
pipeline.prepare(METADATA),
(error) =>
error instanceof ClusterControlAdmissionSecurityError &&
error.statusCode === 401 &&
error.code === 'authentication_required',
);
assert.equal(events.includes('authorize:run.start'), false);
assert.equal(
events.some((event) => event.startsWith('handle:')),
false,
);
assert.equal(events.includes('audit:authentication_rejected'), true);
});
test('maps policy decisions to low-sensitive deny and approval responses', async () => {
for (const [effect, code, outcome] of [
['deny', 'forbidden', 'denied'],
['require_approval', 'approval_required', 'approval_required'],
]) {
const events = [];
const pipeline = createClusterControlAdmissionPipeline(
options({
events,
policy: {
authorize() {
return { effect, reasons: ['policy_decision'], fence: null };
},
},
}),
);
await assert.rejects(
pipeline.prepare(METADATA),
(error) =>
error instanceof ClusterControlAdmissionSecurityError &&
error.statusCode === 403 &&
error.code === code &&
!error.message.includes('policy_decision'),
);
assert.equal(events.includes(`audit:${outcome}`), true);
}
});
test('fails closed when authentication, policy or security audit is unavailable', async () => {
const scenarios = [
{
override: {
authenticator: {
authenticate() {
throw new Error('identity database detail');
},
},
},
code: 'authentication_unavailable',
},
{
override: {
policy: {
authorize() {
throw new Error('policy database detail');
},
},
},
code: 'authorization_unavailable',
},
{
override: {
audit: {
record() {
throw new Error('audit store detail');
},
},
},
code: 'security_audit_unavailable',
},
];
for (const scenario of scenarios) {
const pipeline = createClusterControlAdmissionPipeline(
options(scenario.override),
);
await assert.rejects(
pipeline.prepare(METADATA),
(error) =>
error instanceof ClusterControlAdmissionSecurityError &&
error.statusCode === 503 &&
error.code === scenario.code &&
!error.message.includes('database detail') &&
!error.message.includes('store detail'),
);
}
});
test('adapts the shared fenced Project Policy engine without an allow-all seam', async () => {
const policy = createClusterControlProjectPolicyAuthorizer({
async resolve(projectId, subject) {
assert.equal(projectId, 'prj_default');
return {
project: {
id: projectId,
name: 'Default',
slug: 'default',
status: 'active',
version: 4,
createdAtMs: 0,
updatedAtMs: 1,
},
binding: {
projectId,
subject,
version: 7,
state: 'active',
role: 'operator',
mutationId: 'grant-7',
changedBy: { type: 'user', id: 'usr_owner' },
createdAtMs: 1,
},
};
},
async append() {
throw new Error('not used');
},
});
assert.deepEqual(
await policy.authorize({
principal: PRINCIPAL,
operationId: 'run.create',
permission: 'run.start',
projectId: 'prj_default',
signal: METADATA.signal,
}),
{
effect: 'allow',
reasons: ['role_grant'],
fence: { projectVersion: 4, bindingVersion: 7 },
},
);
assert.equal(
(
await policy.authorize({
principal: PRINCIPAL,
operationId: 'project.update',
permission: 'project.manage',
projectId: null,
signal: METADATA.signal,
})
).effect,
'deny',
);
});
@@ -0,0 +1,268 @@
const assert = require('node:assert/strict');
const { chmod, mkdtemp, rm, writeFile } = require('node:fs/promises');
const { tmpdir } = require('node:os');
const { join } = require('node:path');
const { test } = require('node:test');
const {
ProductionClusterAiConfigError,
loadProductionClusterAiConfig,
startProductionClusterAiControlApplication,
} = require('@qinglong/cluster-control/ai-production');
const {
canonicalPluginPackagePromptOutputKeyringManifest,
PLUGIN_PACKAGE_PROMPT_OUTPUT_KEYRING_MANIFEST_SCHEMA,
} = require('@qinglong/ai/plugin-package-prompt-output-keyring-manifest');
function enabledEnvironment(overrides = {}) {
return {
QL3_CLUSTER_AI_ENABLED: 'true',
QL3_CLUSTER_AI_PROVIDER_AUTHORITY_FILE: '/var/run/qinglong/ai/providers.json',
QL3_CLUSTER_AI_SECRET_ROOT: '/var/run/qinglong/ai/provider-secrets',
...overrides,
};
}
function controlConfig() {
return {
enabled: true,
profile: 'cluster-control',
http: { host: '127.0.0.1', port: 5800 },
database: {
connection: {
host: '127.0.0.1',
port: 5432,
database: 'qinglong',
user: 'ql3_runtime',
password: 'test-only',
tls: { mode: 'disable' },
},
pool: { maxConnections: 8 },
},
security: { apiCredentialPepper: 'test-only' },
};
}
test('AI config is fail-closed and bounded behind the explicit process flag', () => {
assert.throws(
() => loadProductionClusterAiConfig({}),
(error) =>
error instanceof ProductionClusterAiConfigError &&
error.code === 'QL3_CLUSTER_AI_CONFIG_INVALID',
);
assert.deepEqual(loadProductionClusterAiConfig(enabledEnvironment()), {
enabled: true,
providerAuthorityFile: '/var/run/qinglong/ai/providers.json',
secretRootDirectory: '/var/run/qinglong/ai/provider-secrets',
maxConcurrent: 4,
recoveryLimit: 32,
databaseMaxConnections: 4,
});
assert.throws(
() =>
loadProductionClusterAiConfig(
enabledEnvironment({ QL3_CLUSTER_AI_MAX_CONCURRENT: '65' }),
),
/between 1 and 64/,
);
assert.throws(
() =>
loadProductionClusterAiConfig(
enabledEnvironment({
QL3_CLUSTER_AI_PROMPT_OUTPUT_ENABLED: 'true',
}),
),
/QL3_CLUSTER_AI_PROMPT_OUTPUT_KEYRING_ROOT is invalid/,
);
});
test('explicit AI composition injects one reviewed Prompt capability and drains it after HTTP control', async () => {
const secretRoot = await mkdtemp(join(tmpdir(), 'ql3-cluster-ai-secret-'));
const events = [];
const promptCatalog = Object.freeze({ inspect() {} });
const promptExecutions = Object.freeze({ execute() {} });
const promptExecutionInspections = Object.freeze({ inspectAuthorized() {} });
let promptOptions;
let controlOptions;
const neverUnavailable = new Promise(() => {});
try {
const application = await startProductionClusterAiControlApplication({
control: { config: controlConfig() },
ai: {
enabled: true,
providerAuthorityFile: '/unused/providers.json',
secretRootDirectory: secretRoot,
maxConcurrent: 3,
recoveryLimit: 11,
databaseMaxConnections: 2,
},
audit() {},
async bootstrapPrompt(options) {
promptOptions = options;
return {
status: 'active',
profile: 'cluster',
readiness: {},
capability: {},
prompts: {},
promptCatalog,
promptExecutions,
promptExecutionInspections,
async stop() {
events.push('stop-prompt');
return 'stopped';
},
};
},
async startControl(options) {
controlOptions = options;
return {
status: 'active',
address: { host: '127.0.0.1', port: 5800 },
evidence: {},
recovery: { safe: true, remaining: 0, failed: 0 },
unavailable: neverUnavailable,
availabilityStatus() {
return 'ready';
},
async stop() {
events.push('stop-control');
return 'stopped';
},
};
},
});
assert.equal(application.status, 'active');
assert.equal(application.availabilityStatus(), 'ready');
assert.equal(promptOptions.enabled, true);
assert.equal(promptOptions.maxConcurrent, 3);
assert.equal(promptOptions.recoveryLimit, 11);
assert.equal(controlOptions.promptCatalog.capability, promptCatalog);
assert.equal(controlOptions.promptExecution.capability, promptExecutions);
assert.equal(
controlOptions.promptExecutionInspection.capability,
promptExecutionInspections,
);
assert.equal('promptOutputRead' in controlOptions, false);
assert.equal(await application.stop(), 'stopped');
assert.equal(await application.stop(), 'stopped');
assert.deepEqual(events, ['stop-control', 'stop-prompt']);
} finally {
await rm(secretRoot, { recursive: true, force: true });
}
});
test('output-enabled AI composition wires exact and request-keyed protected reads', async () => {
const secretRoot = await mkdtemp(join(tmpdir(), 'ql3-cluster-ai-secret-'));
const outputRoot = await mkdtemp(join(tmpdir(), 'ql3-cluster-ai-output-'));
const manifest = canonicalPluginPackagePromptOutputKeyringManifest({
schema: PLUGIN_PACKAGE_PROMPT_OUTPUT_KEYRING_MANIFEST_SCHEMA,
generation: 1,
activeKeyId: 'prompt-key-1',
keys: { 'prompt-key-1': Buffer.alloc(32, 7).toString('base64url') },
retirements: {},
});
await writeFile(join(outputRoot, 'keyring.json'), manifest, { mode: 0o440 });
await chmod(join(outputRoot, 'keyring.json'), 0o440);
let promptOptions;
let controlOptions;
const promptOutputs = Object.freeze({ read() {} });
const promptExecutionOutputs = Object.freeze({ read() {} });
try {
const application = await startProductionClusterAiControlApplication({
control: { config: controlConfig() },
ai: {
enabled: true,
providerAuthorityFile: '/unused/providers.json',
secretRootDirectory: secretRoot,
promptOutputKeyringRootDirectory: outputRoot,
maxConcurrent: 1,
recoveryLimit: 1,
databaseMaxConnections: 1,
},
audit() {},
async bootstrapPrompt(options) {
promptOptions = options;
return {
status: 'active',
profile: 'cluster',
readiness: {},
capability: {},
prompts: {},
promptCatalog: { inspect() {} },
promptExecutions: { execute() {} },
promptExecutionInspections: { inspectAuthorized() {} },
promptOutputs,
promptExecutionOutputs,
async stop() { return 'stopped'; },
};
},
async startControl(options) {
controlOptions = options;
return {
status: 'active',
address: { host: '127.0.0.1', port: 5800 },
evidence: {},
recovery: { safe: true, remaining: 0, failed: 0 },
unavailable: new Promise(() => {}),
availabilityStatus() { return 'ready'; },
async stop() { return 'stopped'; },
};
},
});
assert.equal(typeof promptOptions.promptOutputKeys.resolve, 'function');
assert.equal(
typeof promptOptions.promptOutputRead.authorizer.authorize,
'function',
);
assert.equal(controlOptions.promptOutputRead.capability, promptOutputs);
assert.equal(
controlOptions.promptExecutionOutputRead.capability,
promptExecutionOutputs,
);
assert.equal(await application.stop(), 'stopped');
} finally {
manifest.fill(0);
await rm(secretRoot, { recursive: true, force: true });
await rm(outputRoot, { recursive: true, force: true });
}
});
test('AI composition fails closed and drains a non-active Prompt bootstrap', async () => {
const secretRoot = await mkdtemp(join(tmpdir(), 'ql3-cluster-ai-secret-'));
let stops = 0;
try {
await assert.rejects(
startProductionClusterAiControlApplication({
control: { config: controlConfig() },
ai: {
enabled: true,
providerAuthorityFile: '/unused/providers.json',
secretRootDirectory: secretRoot,
maxConcurrent: 1,
recoveryLimit: 1,
databaseMaxConnections: 1,
},
audit() {},
async bootstrapPrompt() {
return {
status: 'disabled',
profile: 'cluster',
async stop() {
stops += 1;
return 'stopped';
},
};
},
async startControl() {
throw new Error('control must not start');
},
}),
/Prompt application did not activate/,
);
assert.equal(stops, 1);
} finally {
await rm(secretRoot, { recursive: true, force: true });
}
});
@@ -0,0 +1,178 @@
const assert = require('node:assert/strict');
const { createHmac } = require('node:crypto');
const { test } = require('node:test');
const {
ApiCredentialUnavailableError,
} = require('@qinglong/runtime-core/api-credential');
const {
ClusterControlApiCredentialConfigurationError,
ClusterControlApiCredentialUnavailableError,
apiCredentialSecretDigest,
createClusterControlApiCredentialAuthenticator,
} = require('@qinglong/cluster-control/api-credential');
const NOW = 10_000;
const PEPPER = Buffer.alloc(32, 1).toString('base64url');
const SECRET = Buffer.alloc(32, 2).toString('base64url');
const CREDENTIAL_ID = 'app_primary';
function metadata(authorization = `Bearer ql3c_${CREDENTIAL_ID}_${SECRET}`) {
return {
requestId: 'request-1',
method: 'POST',
path: '/api/v3/projects/default/runs',
query: Object.freeze({}),
headers: Object.freeze({ authorization }),
signal: new AbortController().signal,
};
}
function credential(overrides = {}) {
return {
credentialId: CREDENTIAL_ID,
version: 2,
pepperKeyId: 'legacy-v1',
state: 'active',
subject: { type: 'api_app', id: 'app_primary' },
subjectStatus: 'active',
secretDigest: apiCredentialSecretDigest(PEPPER, CREDENTIAL_ID, SECRET),
createdAtMs: 1,
notBeforeAtMs: 1,
expiresAtMs: 100_000,
...overrides,
};
}
function authenticator(value = credential(), overrides = {}) {
return createClusterControlApiCredentialAuthenticator(
{
async resolve(credentialId) {
assert.equal(credentialId, CREDENTIAL_ID);
return value;
},
},
PEPPER,
{ now: () => NOW, ...overrides },
);
}
test('authenticates a high-entropy service bearer as a short-lived principal', async () => {
const principal = await authenticator().authenticate(metadata());
assert.deepEqual(principal, {
subject: { type: 'api_app', id: 'app_primary' },
authenticationId: 'api_credential:app_primary:2',
authenticatedAtMs: NOW,
expiresAtMs: NOW + 60_000,
assurance: 'service',
});
assert.equal(Object.isFrozen(principal), true);
assert.equal(JSON.stringify(principal).includes(SECRET), false);
});
test('derives a domain-separated HMAC digest and user assurance', async () => {
const expected = createHmac('sha256', Buffer.from(PEPPER, 'base64url'))
.update(Buffer.from('qinglong-api-credential-v1\0', 'utf8'))
.update(CREDENTIAL_ID, 'utf8')
.update('\0', 'utf8')
.update(Buffer.from(SECRET, 'base64url'))
.digest('hex');
assert.equal(
apiCredentialSecretDigest(PEPPER, CREDENTIAL_ID, SECRET),
expected,
);
const principal = await authenticator(
credential({ subject: { type: 'user', id: 'usr_primary' } }),
).authenticate(metadata());
assert.equal(principal.assurance, 'single_factor');
});
test('rejects missing, malformed, wrong, inactive and disabled credentials', async () => {
let repositoryCalls = 0;
const strict = createClusterControlApiCredentialAuthenticator(
{
async resolve() {
repositoryCalls += 1;
return credential();
},
},
PEPPER,
{ now: () => NOW },
);
for (const header of [
undefined,
'bearer token',
`Bearer ql3c_${CREDENTIAL_ID}_short`,
`Bearer ql3c_${CREDENTIAL_ID}_${Buffer.alloc(32, 3).toString('base64url')}`,
]) {
const request = metadata();
request.headers = Object.freeze(
header === undefined ? {} : { authorization: header },
);
assert.equal(await strict.authenticate(request), null);
}
assert.equal(
repositoryCalls,
1,
'only a structurally valid token reaches SQL',
);
for (const value of [
credential({ state: 'revoked' }),
credential({ subjectStatus: 'disabled' }),
credential({ notBeforeAtMs: NOW + 1 }),
credential({ expiresAtMs: NOW }),
null,
]) {
assert.equal(await authenticator(value).authenticate(metadata()), null);
}
});
test('maps storage, corrupt record and cancellation failures to unavailable', async () => {
const unavailable = createClusterControlApiCredentialAuthenticator(
{
async resolve() {
throw new ApiCredentialUnavailableError();
},
},
PEPPER,
{ now: () => NOW },
);
await assert.rejects(
unavailable.authenticate(metadata()),
ClusterControlApiCredentialUnavailableError,
);
await assert.rejects(
authenticator(credential({ secretDigest: 'corrupt' })).authenticate(
metadata(),
),
ClusterControlApiCredentialUnavailableError,
);
await assert.rejects(
authenticator(credential({ pepperKeyId: 'other-v1' })).authenticate(
metadata(),
),
ClusterControlApiCredentialUnavailableError,
);
const controller = new AbortController();
controller.abort();
await assert.rejects(
authenticator().authenticate({ ...metadata(), signal: controller.signal }),
ClusterControlApiCredentialUnavailableError,
);
});
test('rejects weak pepper and unbounded principal lifetime at construction', () => {
const repository = { async resolve() {} };
assert.throws(
() => createClusterControlApiCredentialAuthenticator(repository, 'weak'),
ClusterControlApiCredentialConfigurationError,
);
assert.throws(
() =>
createClusterControlApiCredentialAuthenticator(repository, PEPPER, {
principalTtlMs: 300_001,
}),
ClusterControlApiCredentialConfigurationError,
);
});
@@ -0,0 +1,787 @@
const assert = require('node:assert/strict');
const http = require('node:http');
const net = require('node:net');
const { test } = require('node:test');
const {
startClusterControlApplication,
} = require('@qinglong/cluster-control/application');
const {
ClusterControlAvailabilityFence,
} = require('@qinglong/cluster-control/availability');
const {
apiCredentialSecretDigest,
} = require('@qinglong/cluster-control/api-credential');
const {
createClusterControlAdmissionPipeline,
createClusterControlProjectPolicyAuthorizer,
} = require('@qinglong/cluster-control/admission');
const {
createClusterControlRouteRegistry,
} = require('@qinglong/cluster-control/routes');
const {
PostgresSchemaReadinessError,
postgresqlMainMigrationManifest,
} = require('@qinglong/cluster-postgres/runtime');
const {
postgresqlControlSchemaContract,
} = require('@qinglong/cluster-postgres');
function freePort() {
return new Promise((resolve, reject) => {
const server = net.createServer();
server.once('error', reject);
server.listen(0, '127.0.0.1', () => {
const address = server.address();
server.close((error) => {
if (error) reject(error);
else resolve(address.port);
});
});
});
}
function request(port, path, options = {}) {
const body =
options.body === undefined
? undefined
: Buffer.from(JSON.stringify(options.body));
return new Promise((resolve, reject) => {
const outgoing = http.request(
{
host: '127.0.0.1',
port,
path,
method: options.method ?? 'GET',
headers: {
connection: 'close',
...(body
? {
'content-type': 'application/json',
'content-length': String(body.byteLength),
}
: {}),
...options.headers,
},
},
(response) => {
const chunks = [];
response.on('data', (chunk) => chunks.push(chunk));
response.on('end', () => {
const text = Buffer.concat(chunks).toString('utf8');
resolve({
statusCode: response.statusCode,
body: text.length === 0 ? null : JSON.parse(text),
});
});
},
);
outgoing.once('error', reject);
if (body) outgoing.write(body);
outgoing.end();
});
}
function migrationHistory() {
return postgresqlMainMigrationManifest.migrations.map((migration, index) => ({
streamId: postgresqlMainMigrationManifest.id,
dialect: postgresqlMainMigrationManifest.dialect,
migrationId: migration.id,
checksum: migration.checksum,
appliedAtMs: index + 1,
}));
}
function admission(handler) {
return {
async prepare(metadata) {
return {
handle(body) {
return handler({ ...metadata, body });
},
};
},
};
}
function runtimePrivileges() {
const privileges = {
schema_migrations: [true, false, false, false],
schema_capabilities: [true, false, false, false],
projects: [true, true, true, false],
task_definitions: [true, false, false, false],
task_definition_revisions: [true, false, false, false],
task_execution_revisions: [true, false, false, false],
triggers: [true, false, false, false],
trigger_revisions: [true, false, false, false],
trigger_schedules: [true, false, true, false],
project_role_bindings: [true, true, false, false],
identity_subjects: [true, false, false, false],
api_credentials: [true, false, false, false],
security_audit_events: [false, true, false, false],
identity_subject_mutations: [false, false, false, false],
api_credential_mutations: [false, false, false, false],
runs: [true, true, true, false],
step_runs: [true, true, true, false],
step_run_mutations: [true, true, false, false],
tool_execution_trace_anchors: [true, true, false, false],
tool_execution_audit_receipts: [true, true, false, false],
tool_execution_start_barriers: [true, true, false, false],
tool_execution_start_artifact_bindings: [true, true, false, false],
tool_execution_completions: [true, true, false, false],
tool_execution_failure_completions: [true, true, false, false],
tool_result_key_catalog_generations: [true, false, false, false],
tool_execution_result_key_bindings: [true, true, false, false],
tool_execution_result_rekey_overlays: [true, false, false, false],
tool_execution_result_rekey_heads: [true, false, false, false],
tool_result_key_retirement_receipts: [false, false, false, false],
tool_invocation_input_artifacts: [true, true, false, false],
tool_invocation_preview_artifacts: [true, true, false, false],
run_attempts: [true, true, true, false],
run_recovery_controls: [true, true, true, false],
worker_sessions: [true, true, true, false],
run_dispatch_leases: [true, true, true, false],
worker_credentials: [false, false, false, false],
worker_credential_mutations: [false, false, false, false],
worker_credential_deliveries: [false, false, false, false],
worker_credential_stage_discards: [false, false, false, false],
worker_credential_management_plans: [false, false, false, false],
worker_credential_management_quota_buckets: [false, false, false, false],
plugin_package_installs: [false, false, false, false],
plugin_package_install_heads: [false, false, false, false],
plugin_package_install_mutations: [false, false, false, false],
approval_requests: [false, false, false, false],
approved_action_dispatches: [false, false, false, false],
approved_action_executions: [false, false, false, false],
plugin_package_install_proposals: [false, false, false, false],
plugin_package_admission_receipts: [false, false, false, false],
plugin_package_management_quota_buckets: [false, false, false, false],
plugin_package_identity_keyset_ledger: [false, false, false, false],
plugin_package_materialized_revisions: [false, false, false, false],
plugin_package_task_ownerships: [false, false, false, false],
plugin_package_task_reconciliations: [false, false, false, false],
plugin_package_task_reconciliation_items: [false, false, false, false],
project_tool_definition_snapshots: [false, false, false, false],
project_tool_definition_snapshot_sources: [false, false, false, false],
plugin_package_publisher_provenance: [false, false, false, false],
plugin_package_publisher_revocation_impact_items: [
false,
false,
false,
false,
],
plugin_package_publisher_revocation_impacts: [false, false, false, false],
plugin_package_publisher_revocation_proposals: [false, false, false, false],
plugin_package_publisher_revocation_receipts: [false, false, false, false],
plugin_package_publisher_trust_heads: [false, false, false, false],
plugin_package_publisher_trust_snapshots: [false, false, false, false],
plugin_package_publisher_trust_transition_proposals: [
false,
false,
false,
false,
],
plugin_package_publisher_trust_transition_receipts: [
false,
false,
false,
false,
],
plugin_package_quarantine_events: [false, false, false, false],
plugin_package_withdrawal_receipts: [false, false, false, false],
plugin_package_withdrawal_tasks: [false, false, false, false],
plugin_package_lifecycle_events: [false, false, false, false],
plugin_package_lifecycle_heads: [false, false, false, false],
plugin_package_lifecycle_receipts: [false, false, false, false],
plugin_package_lifecycle_tasks: [false, false, false, false],
plugin_package_lifecycle_plans: [false, false, false, false],
plugin_package_automation_publications: [true, false, false, false],
plugin_package_automation_publication_heads: [true, false, false, false],
plugin_package_workflow_admissions: [true, true, false, false],
plugin_package_workflow_admission_steps: [true, true, false, false],
plugin_package_workflow_task_attempt_admissions: [
true,
true,
false,
false,
],
worker_execution_attestations: [true, false, false, false],
run_events: [true, true, false, false],
run_retry_policies: [true, true, true, false],
};
return Object.entries(privileges).map(
([
tableName,
[selectAllowed, insertAllowed, updateAllowed, deleteAllowed],
]) => ({
tableName,
selectAllowed,
insertAllowed,
updateAllowed,
deleteAllowed,
isOwner: false,
}),
);
}
function databaseResource(events, options = {}) {
const contract = postgresqlControlSchemaContract;
let firstQuery = true;
const pool = {
async query(text, values) {
events.push('query');
if (firstQuery && options.readinessGate) {
firstQuery = false;
options.onReadinessQuery?.();
await options.readinessGate;
}
if (text.includes("current_setting('server_version_num')")) {
return {
rows: [
{
serverVersionNum: options.serverVersionNum ?? '160014',
currentUser: 'ql3_runtime',
inRecovery: false,
transactionReadOnly: 'off',
},
],
};
}
if (text.includes('FROM "ql3"."schema_migrations"')) {
return { rows: migrationHistory() };
}
if (text.includes('FROM "ql3"."schema_capabilities"')) {
return {
rows: [
{
contractName: contract.contractName,
contractVersion: contract.contractVersion,
migrationId: contract.migrationId,
capabilities: contract.capabilities,
},
],
};
}
if (text.includes('FROM pg_class tables')) {
return {
rows: contract.tables.flatMap((table) =>
table.columns.map((columnName) => ({
tableName: table.name,
columnName,
})),
),
};
}
if (text.includes('FROM pg_indexes')) {
return { rows: contract.indexes.map((indexName) => ({ indexName })) };
}
if (text.includes('FROM pg_constraint')) {
return {
rows: [
...contract.checks.map((constraintName) => ({
constraintName,
constraintType: 'check',
})),
...contract.foreignKeys.map((constraintName) => ({
constraintName,
constraintType: 'foreign_key',
})),
],
};
}
if (text.includes('FROM pg_proc routines')) {
return {
rows: contract.functions.map((definition) => ({
functionName: definition.name,
identityArguments: definition.identityArguments,
owner: definition.owner,
securityDefiner: definition.securityDefiner,
volatility: definition.volatility,
configuration: definition.configuration,
publicExecute: false,
})),
};
}
if (text.includes('FROM pg_catalog.pg_roles')) {
return {
rows: [
{
canLogin: true,
superuser: false,
createDatabase: false,
createRole: false,
replication: false,
bypassRowLevelSecurity: false,
databaseConnect: true,
},
],
};
}
if (text.includes('has_schema_privilege')) {
return { rows: [{ schemaUsage: true, schemaCreate: false }] };
}
if (text.includes('has_table_privilege')) {
return { rows: runtimePrivileges() };
}
if (text.includes('has_function_privilege')) {
return {
rows: contract.functions.map(({ name: functionName }) => ({
functionName,
executeAllowed: [
'plugin_package_automation_start_allowed',
'plugin_package_workflow_admission_snapshot',
'plugin_package_workflow_task_attempt_snapshot',
'plugin_package_run_start_allowed',
'plugin_package_tool_start_allowed',
].includes(functionName),
isOwner: false,
})),
};
}
if (text.includes('WITH observation AS')) {
return {
rows: options.recoveryRows ?? [
{
observedAtMs: '1',
kind: null,
id: null,
runId: null,
status: null,
createdAtMs: null,
},
],
};
}
if (options.query) return options.query(text, values);
throw new Error(`unexpected query: ${text}`);
},
async connect() {
throw new Error('Repository connections are not used by this fixture');
},
};
return {
pool,
async close() {
events.push('close-database');
},
};
}
function baseOptions(events, port, overrides = {}) {
return {
enabled: true,
profile: 'cluster-control',
apiCredentialPepper: 'A'.repeat(43),
recovery: { ownerId: 'test-replica', providers: [] },
availability: new ClusterControlAvailabilityFence(),
http: { host: '127.0.0.1', port, drainTimeoutMs: 1000 },
async openDatabase() {
events.push('open-database');
return databaseResource(events);
},
create({
evidence,
authenticator,
policies,
runs,
taskDefinitions,
taskExecutionRevisions,
triggers,
schedules,
securityAudit,
}) {
events.push('create-stack');
assert.equal(
evidence.contractVersion,
postgresqlControlSchemaContract.contractVersion,
);
assert.equal(typeof authenticator.authenticate, 'function');
assert.equal(typeof policies.resolve, 'function');
assert.equal(typeof runs.transaction, 'function');
assert.equal(
typeof taskDefinitions.findCurrentTaskDefinition,
'function',
);
assert.equal(
typeof taskExecutionRevisions.resolveClusterTaskExecutionRevision,
'function',
);
assert.equal(typeof triggers.findCurrentTrigger, 'function');
assert.equal(typeof schedules.claimNextClusterSchedule, 'function');
assert.equal(typeof schedules.commitClusterScheduleDecision, 'function');
assert.equal(typeof securityAudit.record, 'function');
return {
async reconcile() {
events.push('reconcile');
return { safe: true, remaining: 0, failed: 0 };
},
async startLifecycles() {
events.push('start-lifecycles');
return true;
},
admission: admission(async (incoming) => {
events.push(`handle:${incoming.path}`);
return { statusCode: 202, body: { accepted: true } };
}),
async stop() {
events.push('stop-stack');
return 'stopped';
},
};
},
audit(record) {
events.push(`audit:${record.state}`);
},
...overrides,
};
}
test('disabled and wrong-profile applications never bind or open PostgreSQL', async () => {
const disabledEvents = [];
const disabled = await startClusterControlApplication(
baseOptions(disabledEvents, 0, { enabled: false }),
);
assert.equal(disabled.status, 'disabled');
assert.deepEqual(disabledEvents, ['audit:disabled']);
const wrongProfileEvents = [];
await assert.rejects(
startClusterControlApplication(
baseOptions(wrongProfileEvents, 0, { profile: 'standalone' }),
),
/cannot activate cluster-control/,
);
assert.deepEqual(wrongProfileEvents, []);
});
test('rejects an invalid credential pepper before binding or opening PostgreSQL', async () => {
const events = [];
await assert.rejects(
startClusterControlApplication(
baseOptions(events, 0, { apiCredentialPepper: undefined }),
),
/API credential configuration is invalid/,
);
assert.deepEqual(events, []);
});
test('rejects an enabled application without an availability source', async () => {
const events = [];
await assert.rejects(
startClusterControlApplication(
baseOptions(events, 0, { availability: undefined }),
),
/availability source is invalid/,
);
assert.deepEqual(events, []);
});
test('composes bearer authentication, fenced Policy and durable audit on one Pool', async (t) => {
const pepper = 'A'.repeat(43);
const secret = Buffer.alloc(32, 2).toString('base64url');
const digest = apiCredentialSecretDigest(pepper, 'app_primary', secret);
const auditWrites = [];
const events = [];
const port = await freePort();
const result = await startClusterControlApplication(
baseOptions(events, port, {
apiCredentialPepper: pepper,
async openDatabase() {
events.push('open-database');
return databaseResource(events, {
async query(text, values) {
if (text.includes('FROM "ql3"."api_credentials"')) {
return {
rows: [
{
credentialId: 'app_primary',
version: '1',
state: 'active',
subjectType: 'api_app',
subjectId: 'app_primary',
subjectStatus: 'active',
pepperKeyId: 'legacy-v1',
secretDigest: digest,
createdAtMs: '1',
notBeforeAtMs: '1',
expiresAtMs: String(Date.now() + 60_000),
},
],
};
}
if (text.includes('FROM "ql3"."projects" AS project')) {
return {
rows: [
{
projectId: 'default',
projectName: 'Default',
projectSlug: 'default',
projectStatus: 'active',
projectVersion: '2',
projectCreatedAtMs: '0',
projectUpdatedAtMs: '1',
bindingProjectId: 'default',
bindingSubjectType: 'api_app',
bindingSubjectId: 'app_primary',
bindingVersion: '3',
bindingState: 'active',
bindingRole: 'operator',
bindingMutationId: 'grant-app',
bindingChangedByType: 'user',
bindingChangedById: 'usr_owner',
bindingCreatedAtMs: '1',
},
],
};
}
if (text.startsWith('INSERT INTO "ql3"."security_audit_events"')) {
auditWrites.push(values);
return { rows: [] };
}
throw new Error(`unexpected repository query: ${text}`);
},
});
},
create({ authenticator, policies, securityAudit }) {
events.push('create-stack');
return {
async reconcile() {
return { safe: true, remaining: 0, failed: 0 };
},
async startLifecycles() {
return true;
},
admission: createClusterControlAdmissionPipeline({
routes: createClusterControlRouteRegistry([
{
method: 'POST',
path: '/api/v3/projects/{projectId}/runs',
operationId: 'run.create',
permission: 'run.start',
projectParameter: 'projectId',
handle(input) {
return {
statusCode: 202,
body: {
accepted: true,
subject: input.principal.subject.id,
},
};
},
},
]),
authenticator,
policy: createClusterControlProjectPolicyAuthorizer(policies),
audit: securityAudit,
}),
async stop() {
return 'stopped';
},
};
},
}),
);
t.after(() => result.stop());
const rejected = await request(port, '/api/v3/projects/default/runs', {
method: 'POST',
headers: {
'content-type': 'application/json',
'content-length': String(1024 * 1024),
},
});
assert.equal(rejected.statusCode, 401);
assert.equal(auditWrites.length, 1);
assert.equal(auditWrites[0][7], 'authentication_rejected');
const accepted = await request(port, '/api/v3/projects/default/runs', {
method: 'POST',
headers: {
authorization: `Bearer ql3c_app_primary_${secret}`,
},
body: { taskId: 'task-1' },
});
assert.equal(accepted.statusCode, 202);
assert.deepEqual(accepted.body, {
accepted: true,
subject: 'app_primary',
});
assert.equal(auditWrites.length, 2);
assert.equal(auditWrites[1][7], 'allowed');
assert.equal(auditWrites[1][9], 2);
assert.equal(auditWrites[1][10], 3);
assert.equal(JSON.stringify(auditWrites).includes(secret), false);
});
test('serves not-ready while auditing PostgreSQL, then opens admission', async () => {
const events = [];
const port = await freePort();
let releaseReadiness;
const readinessGate = new Promise((resolve) => {
releaseReadiness = resolve;
});
let readinessStarted;
const readinessStartedPromise = new Promise((resolve) => {
readinessStarted = resolve;
});
const starting = startClusterControlApplication(
baseOptions(events, port, {
async openDatabase() {
events.push('open-database');
return databaseResource(events, {
readinessGate,
onReadinessQuery: readinessStarted,
});
},
}),
);
await readinessStartedPromise;
assert.equal((await request(port, '/livez')).statusCode, 200);
assert.deepEqual(await request(port, '/readyz'), {
statusCode: 503,
body: { status: 'not_ready' },
});
assert.equal(events.includes('create-stack'), false);
releaseReadiness();
const application = await starting;
assert.equal(application.status, 'active');
assert.deepEqual(await request(port, '/readyz'), {
statusCode: 200,
body: { status: 'ready' },
});
assert.deepEqual(
await request(port, '/api/v3/runs', {
method: 'POST',
body: { taskId: 'task-1' },
}),
{ statusCode: 202, body: { accepted: true } },
);
assert.equal(await application.stop(), 'stopped');
assert.deepEqual(events.slice(-3), [
'stop-stack',
'audit:stopped',
'close-database',
]);
await assert.rejects(request(port, '/livez'));
});
test('withdraws and drains application admission before stack and Pool stop', async () => {
const events = [];
const port = await freePort();
let entered;
const enteredPromise = new Promise((resolve) => {
entered = resolve;
});
let release;
const handlerGate = new Promise((resolve) => {
release = resolve;
});
const application = await startClusterControlApplication(
baseOptions(events, port, {
create(input) {
const stack = baseOptions([], port).create(input);
return {
...stack,
admission: admission(async () => {
events.push('handle:slow');
entered();
await handlerGate;
events.push('handler-finished');
return { statusCode: 200, body: { completed: true } };
}),
async stop() {
events.push('stop-stack');
return 'stopped';
},
};
},
}),
);
const admitted = request(port, '/api/v3/slow');
await enteredPromise;
const stopping = application.stop();
assert.deepEqual(await request(port, '/readyz'), {
statusCode: 503,
body: { status: 'not_ready' },
});
assert.equal(events.includes('stop-stack'), false);
release();
assert.deepEqual(await admitted, {
statusCode: 503,
body: { code: 'admission_draining' },
});
assert.equal(await stopping, 'stopped');
assert.ok(events.indexOf('handler-finished') < events.indexOf('stop-stack'));
assert.ok(events.indexOf('stop-stack') < events.indexOf('close-database'));
});
test('a database availability signal withdraws admission but keeps liveness', async () => {
const events = [];
const port = await freePort();
const availability = new ClusterControlAvailabilityFence();
const application = await startClusterControlApplication(
baseOptions(events, port, { availability }),
);
assert.equal(application.availabilityStatus(), 'ready');
assert.equal((await request(port, '/readyz')).statusCode, 200);
const unavailable = new Error('PostgreSQL connection lost');
assert.equal(await availability.signal(unavailable), 'signaled');
assert.equal(await application.unavailable, unavailable);
assert.equal(application.availabilityStatus(), 'unavailable');
assert.deepEqual(await request(port, '/readyz'), {
statusCode: 503,
body: { status: 'not_ready' },
});
assert.equal((await request(port, '/livez')).statusCode, 200);
assert.deepEqual(
await request(port, '/api/v3/runs', {
method: 'POST',
body: { taskId: 'task-1' },
}),
{ statusCode: 503, body: { code: 'not_ready' } },
);
assert.ok(events.indexOf('stop-stack') < events.indexOf('close-database'));
assert.equal(await application.stop(), 'stopped');
assert.equal(application.availabilityStatus(), 'stopped');
await assert.rejects(request(port, '/livez'));
});
test('an availability signal raised before startup cannot open admission', async () => {
const events = [];
const port = await freePort();
const availability = new ClusterControlAvailabilityFence();
assert.equal(
await availability.signal(new Error('PostgreSQL unavailable at startup')),
'signaled',
);
await assert.rejects(
startClusterControlApplication(baseOptions(events, port, { availability })),
(error) => error?.code === 'CLUSTER_CONTROL_DATABASE_UNAVAILABLE',
);
assert.ok(events.indexOf('stop-stack') < events.indexOf('close-database'));
await assert.rejects(request(port, '/livez'));
});
test('readiness failure closes both PostgreSQL and the probe listener', async () => {
const events = [];
const port = await freePort();
await assert.rejects(
startClusterControlApplication(
baseOptions(events, port, {
async openDatabase() {
events.push('open-database');
return databaseResource(events, { serverVersionNum: '150018' });
},
}),
),
(error) =>
error instanceof PostgresSchemaReadinessError &&
error.code === 'server_version_unsupported',
);
assert.equal(events.includes('create-stack'), false);
assert.deepEqual(events.slice(-2), ['audit:failed', 'close-database']);
await assert.rejects(request(port, '/livez'));
});
@@ -0,0 +1,120 @@
const assert = require('node:assert/strict');
const { test } = require('node:test');
const {
createClusterControlAuthenticationShield,
} = require('../dist/authentication/authenticationShield.js');
function shield(overrides = {}) {
let currentTime = 1000;
const instance = createClusterControlAuthenticationShield({
windowMs: 1000,
maxRequestsPerPeer: 1,
maxRequestsGlobal: 3,
maxTrackedPeers: 2,
now: () => currentTime,
...overrides,
});
return {
instance,
advance(milliseconds) {
currentTime += milliseconds;
},
setTime(value) {
currentTime = value;
},
};
}
function assertAllowed(result) {
assert.equal(result.allowed, true);
assert.equal(typeof result.refund, 'function');
return result;
}
test('bounds per-peer and aggregate attempts in a process-local window', () => {
const { instance } = shield();
assertAllowed(instance.consume('192.0.2.10'));
assert.deepEqual(instance.consume('192.0.2.10'), {
allowed: false,
reason: 'peer',
retryAfterMs: 1000,
});
assertAllowed(instance.consume('192.0.2.11'));
assert.deepEqual(instance.consume('192.0.2.12'), {
allowed: false,
reason: 'global',
retryAfterMs: 1000,
});
instance.close();
});
test('keeps peer state bounded and reclaims expired windows lazily', () => {
const clock = shield({ maxRequestsGlobal: 20 });
assertAllowed(clock.instance.consume('192.0.2.10'));
assertAllowed(clock.instance.consume('192.0.2.11'));
assert.deepEqual(clock.instance.consume('192.0.2.12'), {
allowed: false,
reason: 'capacity',
retryAfterMs: 1000,
});
clock.advance(1000);
assertAllowed(clock.instance.consume('192.0.2.12'));
clock.instance.close();
});
test('fails closed on a broken monotonic clock and after disposal', () => {
const clock = shield({ maxRequestsPerPeer: 20, maxRequestsGlobal: 20 });
assertAllowed(clock.instance.consume(undefined));
clock.setTime(999);
assert.deepEqual(clock.instance.consume(undefined), {
allowed: false,
reason: 'clock',
retryAfterMs: 1000,
});
clock.instance.close();
assert.deepEqual(clock.instance.consume('192.0.2.10'), {
allowed: false,
reason: 'clock',
retryAfterMs: 1000,
});
});
test('refunds only the exact successful authentication attempt once', () => {
const { instance } = shield({
maxRequestsPerPeer: 1,
maxRequestsGlobal: 1,
});
const first = assertAllowed(instance.consume('192.0.2.10'));
assert.deepEqual(instance.consume('192.0.2.10'), {
allowed: false,
reason: 'global',
retryAfterMs: 1000,
});
first.refund();
first.refund();
const second = assertAllowed(instance.consume('192.0.2.10'));
second.refund();
assertAllowed(instance.consume('192.0.2.11'));
instance.close();
});
test('a delayed refund cannot alter a replacement window', () => {
const clock = shield({
maxRequestsPerPeer: 1,
maxRequestsGlobal: 1,
});
const expired = assertAllowed(clock.instance.consume('192.0.2.10'));
clock.advance(1000);
assertAllowed(clock.instance.consume('192.0.2.10'));
expired.refund();
assert.deepEqual(clock.instance.consume('192.0.2.11'), {
allowed: false,
reason: 'global',
retryAfterMs: 1000,
});
clock.instance.close();
});
@@ -0,0 +1,40 @@
const assert = require('node:assert/strict');
const { test } = require('node:test');
const {
ClusterControlAvailabilityFence,
} = require('@qinglong/cluster-control/availability');
test('signals one bound listener exactly once without a retry path', async () => {
const fence = new ClusterControlAvailabilityFence();
const reasons = [];
const unsubscribe = fence.subscribe(async (error) => {
reasons.push(error.message);
});
assert.equal(fence.status, 'available');
assert.equal(await fence.signal(new Error('connection lost')), 'signaled');
assert.equal(fence.status, 'unavailable');
assert.equal(
await fence.signal(new Error('second connection lost')),
'already_unavailable',
);
assert.deepEqual(reasons, ['connection lost']);
unsubscribe();
unsubscribe();
fence.dispose();
assert.equal(fence.status, 'disposed');
assert.equal(await fence.signal(new Error('after dispose')), 'disposed');
});
test('delivers an early signal when the single application listener binds', async () => {
const fence = new ClusterControlAvailabilityFence();
assert.equal(await fence.signal(new Error('early failure')), 'signaled');
let reason;
fence.subscribe((error) => {
reason = error.message;
});
await Promise.resolve();
assert.equal(reason, 'early failure');
assert.throws(() => fence.subscribe(() => {}), /already bound/);
await assert.rejects(() => fence.signal('invalid'), /error is invalid/);
});
@@ -0,0 +1,753 @@
const assert = require('node:assert/strict');
const { test } = require('node:test');
const {
PostgresSchemaReadinessError,
postgresqlControlSchemaContract,
postgresqlMainMigrationStream,
} = require('@qinglong/cluster-postgres');
const { bootstrapClusterControlRuntime } = require('@qinglong/cluster-control');
function migrationHistory() {
return postgresqlMainMigrationStream.migrations.map((migration, index) => ({
streamId: 'postgresql-main',
dialect: 'postgresql',
migrationId: migration.id,
checksum: migration.checksum,
appliedAtMs: index + 1,
}));
}
function runtimePrivileges() {
const privileges = {
schema_migrations: [true, false, false, false],
schema_capabilities: [true, false, false, false],
projects: [true, true, true, false],
task_definitions: [true, false, false, false],
task_definition_revisions: [true, false, false, false],
task_execution_revisions: [true, false, false, false],
triggers: [true, false, false, false],
trigger_revisions: [true, false, false, false],
trigger_schedules: [true, false, true, false],
project_role_bindings: [true, true, false, false],
identity_subjects: [true, false, false, false],
api_credentials: [true, false, false, false],
security_audit_events: [false, true, false, false],
identity_subject_mutations: [false, false, false, false],
api_credential_mutations: [false, false, false, false],
runs: [true, true, true, false],
step_runs: [true, true, true, false],
step_run_mutations: [true, true, false, false],
tool_execution_trace_anchors: [true, true, false, false],
tool_execution_audit_receipts: [true, true, false, false],
tool_execution_start_barriers: [true, true, false, false],
tool_execution_start_artifact_bindings: [true, true, false, false],
tool_execution_completions: [true, true, false, false],
tool_execution_failure_completions: [true, true, false, false],
tool_result_key_catalog_generations: [true, false, false, false],
tool_execution_result_key_bindings: [true, true, false, false],
tool_execution_result_rekey_overlays: [true, false, false, false],
tool_execution_result_rekey_heads: [true, false, false, false],
tool_result_key_retirement_receipts: [false, false, false, false],
tool_invocation_input_artifacts: [true, true, false, false],
tool_invocation_preview_artifacts: [true, true, false, false],
run_attempts: [true, true, true, false],
run_recovery_controls: [true, true, true, false],
worker_sessions: [true, true, true, false],
run_dispatch_leases: [true, true, true, false],
worker_credentials: [false, false, false, false],
worker_credential_mutations: [false, false, false, false],
worker_credential_deliveries: [false, false, false, false],
worker_credential_stage_discards: [false, false, false, false],
worker_credential_management_plans: [false, false, false, false],
worker_credential_management_quota_buckets: [false, false, false, false],
plugin_package_installs: [false, false, false, false],
plugin_package_install_heads: [false, false, false, false],
plugin_package_install_mutations: [false, false, false, false],
approval_requests: [false, false, false, false],
approved_action_dispatches: [false, false, false, false],
approved_action_executions: [false, false, false, false],
plugin_package_install_proposals: [false, false, false, false],
plugin_package_admission_receipts: [false, false, false, false],
plugin_package_management_quota_buckets: [false, false, false, false],
plugin_package_identity_keyset_ledger: [false, false, false, false],
plugin_package_materialized_revisions: [false, false, false, false],
plugin_package_task_ownerships: [false, false, false, false],
plugin_package_task_reconciliations: [false, false, false, false],
plugin_package_task_reconciliation_items: [false, false, false, false],
project_tool_definition_snapshots: [false, false, false, false],
project_tool_definition_snapshot_sources: [false, false, false, false],
plugin_package_publisher_provenance: [false, false, false, false],
plugin_package_publisher_revocation_impact_items: [
false,
false,
false,
false,
],
plugin_package_publisher_revocation_impacts: [false, false, false, false],
plugin_package_publisher_revocation_proposals: [false, false, false, false],
plugin_package_publisher_revocation_receipts: [false, false, false, false],
plugin_package_publisher_trust_heads: [false, false, false, false],
plugin_package_publisher_trust_snapshots: [false, false, false, false],
plugin_package_publisher_trust_transition_proposals: [
false,
false,
false,
false,
],
plugin_package_publisher_trust_transition_receipts: [
false,
false,
false,
false,
],
plugin_package_quarantine_events: [false, false, false, false],
plugin_package_withdrawal_receipts: [false, false, false, false],
plugin_package_withdrawal_tasks: [false, false, false, false],
plugin_package_lifecycle_events: [false, false, false, false],
plugin_package_lifecycle_heads: [false, false, false, false],
plugin_package_lifecycle_receipts: [false, false, false, false],
plugin_package_lifecycle_tasks: [false, false, false, false],
plugin_package_lifecycle_plans: [false, false, false, false],
plugin_package_automation_publications: [true, false, false, false],
plugin_package_automation_publication_heads: [true, false, false, false],
plugin_package_workflow_admissions: [true, true, false, false],
plugin_package_workflow_admission_steps: [true, true, false, false],
plugin_package_workflow_task_attempt_admissions: [true, true, false, false],
worker_execution_attestations: [true, false, false, false],
run_events: [true, true, false, false],
run_retry_policies: [true, true, true, false],
};
return Object.entries(privileges).map(
([
tableName,
[selectAllowed, insertAllowed, updateAllowed, deleteAllowed],
]) => ({
tableName,
selectAllowed,
insertAllowed,
updateAllowed,
deleteAllowed,
isOwner: false,
}),
);
}
function databaseResource(events, overrides = {}) {
const contract = postgresqlControlSchemaContract;
const pool = {
async query(text) {
events.push(
`query:${
events.filter((event) => event.startsWith('query:')).length + 1
}`,
);
if (text.includes("current_setting('server_version_num')")) {
return {
rows: [
{
serverVersionNum: overrides.serverVersionNum ?? '160014',
currentUser: 'ql3_runtime',
inRecovery: false,
transactionReadOnly: 'off',
},
],
};
}
if (text.includes('FROM "ql3"."schema_migrations"')) {
return { rows: migrationHistory() };
}
if (text.includes('FROM "ql3"."schema_capabilities"')) {
return {
rows: [
{
contractName: contract.contractName,
contractVersion: contract.contractVersion,
migrationId: contract.migrationId,
capabilities: contract.capabilities,
},
],
};
}
if (text.includes('FROM pg_class tables')) {
return {
rows: contract.tables.flatMap((table) =>
table.columns.map((columnName) => ({
tableName: table.name,
columnName,
})),
),
};
}
if (text.includes('FROM pg_indexes')) {
return {
rows: contract.indexes.map((indexName) => ({ indexName })),
};
}
if (text.includes('FROM pg_constraint')) {
return {
rows: [
...contract.checks.map((constraintName) => ({
constraintName,
constraintType: 'check',
})),
...contract.foreignKeys.map((constraintName) => ({
constraintName,
constraintType: 'foreign_key',
})),
],
};
}
if (text.includes('FROM pg_proc routines')) {
return {
rows: contract.functions.map((definition) => ({
functionName: definition.name,
identityArguments: definition.identityArguments,
owner: definition.owner,
securityDefiner: definition.securityDefiner,
volatility: definition.volatility,
configuration: definition.configuration,
publicExecute: false,
})),
};
}
if (text.includes('FROM pg_catalog.pg_roles')) {
return {
rows: [
{
canLogin: true,
superuser: false,
createDatabase: false,
createRole: false,
replication: false,
bypassRowLevelSecurity: false,
databaseConnect: true,
},
],
};
}
if (text.includes('has_schema_privilege')) {
return { rows: [{ schemaUsage: true, schemaCreate: false }] };
}
if (text.includes('has_table_privilege')) {
return { rows: runtimePrivileges() };
}
if (text.includes('has_function_privilege')) {
return {
rows: contract.functions.map(({ name: functionName }) => ({
functionName,
executeAllowed: [
'plugin_package_automation_start_allowed',
'plugin_package_workflow_admission_snapshot',
'plugin_package_workflow_task_attempt_snapshot',
'plugin_package_run_start_allowed',
'plugin_package_tool_start_allowed',
].includes(functionName),
isOwner: false,
})),
};
}
if (
overrides.runtimeScans &&
text.includes('JOIN LATERAL') &&
text.includes('"ql3"."run_retry_policies"')
) {
events.push('scan:lost-retry');
return { rows: [], rowCount: 0 };
}
if (
text.includes('WITH observation AS') &&
!text.includes('FROM "ql3"."trigger_schedules"')
) {
return {
rows: overrides.recoveryRows ?? [
{
observedAtMs: '1',
kind: null,
id: null,
runId: null,
status: null,
createdAtMs: null,
},
],
};
}
if (
overrides.runtimeScans &&
text.includes('FROM "ql3"."trigger_schedules"')
) {
events.push('scan:schedules');
return { rows: [], rowCount: 0 };
}
if (
overrides.runtimeScans &&
text.includes(
'FROM "ql3"."plugin_package_workflow_admissions" AS admission',
)
) {
events.push('scan:workflow-frontier');
return { rows: [], rowCount: 0 };
}
throw new Error(`unexpected query: ${text}`);
},
async connect() {
if (overrides.runtimeScans) {
return {
async query(text) {
if (
text === 'BEGIN ISOLATION LEVEL READ COMMITTED' ||
text.startsWith('SET LOCAL ') ||
text === 'COMMIT' ||
text === 'ROLLBACK'
) {
return { rows: [], rowCount: 0 };
}
if (
text.includes('attempt.lease_expires_at_ms') &&
text.includes('LEFT JOIN candidates AS candidate')
) {
events.push('scan:runtime-recovery');
return {
rows: [
{
observedAtMs: '1',
attemptId: null,
runId: null,
status: null,
createdAtMs: null,
},
],
rowCount: 1,
};
}
if (
text.includes(
'"ql3"."plugin_package_workflow_task_attempt_admissions"',
)
) {
events.push('scan:workflow-task-attempts');
return { rows: [], rowCount: 0 };
}
throw new Error(`unexpected repository query: ${text}`);
},
release() {
events.push('release:workflow-task-attempts');
},
};
}
throw new Error('Repository connections are not used during bootstrap');
},
};
return {
pool,
async close() {
events.push('close-database');
if (overrides.closeError) throw overrides.closeError;
},
};
}
function activationStack(
events,
recovery = { safe: true, remaining: 0, failed: 0 },
) {
return {
async reconcile() {
events.push('reconcile');
return recovery;
},
async startLifecycles() {
events.push('start-lifecycles');
return true;
},
installAdmission() {
events.push('install-admission');
return () => events.push('dispose-admission');
},
async stop() {
events.push('stop-stack');
return 'stopped';
},
};
}
function bootstrapOptions(events, overrides = {}) {
return {
enabled: true,
profile: 'cluster-control',
apiCredentialPepper: 'A'.repeat(43),
recovery: { ownerId: 'test-replica', providers: [] },
async openDatabase() {
events.push('open-database');
return databaseResource(events);
},
create(input) {
const {
evidence,
authenticator,
policies,
runs,
runCancellation,
taskDefinitions,
taskExecutionRevisions,
triggers,
schedules,
trustedToolStorage,
securityAudit,
} = input;
events.push('create-stack');
assert.equal('pool' in input, false);
assert.equal('recovery' in input, false);
assert.equal('recoveryClaims' in input, false);
assert.equal('recoveryTransitions' in input, false);
assert.equal(
evidence.contractVersion,
postgresqlControlSchemaContract.contractVersion,
);
assert.equal(typeof authenticator.authenticate, 'function');
assert.equal(typeof policies.resolve, 'function');
assert.equal(typeof runs.transaction, 'function');
assert.equal(typeof runCancellation.requestUserCancellation, 'function');
assert.equal(
typeof taskDefinitions.findCurrentTaskDefinition,
'function',
);
assert.equal('appendTaskDefinitionRevision' in taskDefinitions, false);
assert.equal(
typeof taskExecutionRevisions.resolveClusterTaskExecutionRevision,
'function',
);
assert.equal(typeof triggers.findCurrentTrigger, 'function');
assert.equal('appendTriggerRevision' in triggers, false);
assert.equal(typeof schedules.claimNextClusterSchedule, 'function');
assert.equal(typeof schedules.commitClusterScheduleDecision, 'function');
assert.equal(Object.isFrozen(trustedToolStorage), true);
assert.equal(
typeof trustedToolStorage.invocationArtifacts.findInput,
'function',
);
assert.equal(typeof trustedToolStorage.stepRuns.findById, 'function');
assert.equal(
typeof trustedToolStorage.startBarriers.findByStartId,
'function',
);
assert.equal(
typeof trustedToolStorage.completions.findByStartId,
'function',
);
assert.equal(
typeof trustedToolStorage.failureCompletions.findByStartId,
'function',
);
assert.equal(
typeof trustedToolStorage.resultKeyCatalog.findCurrent,
'function',
);
assert.equal(trustedToolStorage.resultKeyCatalog.append, undefined);
assert.equal(
typeof trustedToolStorage.resultRekeys.findHeadByArtifactId,
'function',
);
assert.equal(trustedToolStorage.resultRekeys.append, undefined);
assert.equal(
typeof trustedToolStorage.toolDefinitionSnapshots.findCurrent,
'function',
);
assert.equal(typeof securityAudit.record, 'function');
return activationStack(events);
},
audit(record) {
events.push(`audit:${record.state}`);
},
...overrides,
};
}
test('disabled and wrong-profile bootstrap never opens PostgreSQL', async () => {
const disabledEvents = [];
const disabled = await bootstrapClusterControlRuntime(
bootstrapOptions(disabledEvents, { enabled: false }),
);
assert.equal(disabled.status, 'disabled');
assert.deepEqual(disabledEvents, ['audit:disabled']);
const wrongProfileEvents = [];
await assert.rejects(
bootstrapClusterControlRuntime(
bootstrapOptions(wrongProfileEvents, { profile: 'edge' }),
),
/cannot activate cluster-control/,
);
assert.deepEqual(wrongProfileEvents, []);
});
test('rejects a missing credential pepper before opening PostgreSQL', async () => {
const events = [];
await assert.rejects(
bootstrapClusterControlRuntime(
bootstrapOptions(events, { apiCredentialPepper: undefined }),
),
/API credential configuration is invalid/,
);
assert.deepEqual(events, []);
});
test('rejects missing or unbounded recovery configuration before opening PostgreSQL', async () => {
const missingEvents = [];
await assert.rejects(
bootstrapClusterControlRuntime(
bootstrapOptions(missingEvents, { recovery: undefined }),
),
/requires bounded recovery configuration/,
);
assert.deepEqual(missingEvents, []);
const timeoutEvents = [];
await assert.rejects(
bootstrapClusterControlRuntime(
bootstrapOptions(timeoutEvents, {
recovery: {
ownerId: 'test-replica',
claimLeaseMs: 1_000,
providerTimeoutMs: 900,
},
}),
),
/250ms for fenced settlement/,
);
assert.deepEqual(timeoutEvents, []);
const localClockEvents = [];
await assert.rejects(
bootstrapClusterControlRuntime(
bootstrapOptions(localClockEvents, {
scheduler: { clock: () => 1 },
}),
),
/scheduler configuration is invalid/,
);
assert.deepEqual(localClockEvents, []);
});
test('readiness failure closes the database before returning the root error', async () => {
const events = [];
await assert.rejects(
bootstrapClusterControlRuntime(
bootstrapOptions(events, {
async openDatabase() {
events.push('open-database');
return databaseResource(events, { serverVersionNum: '150018' });
},
}),
),
(error) =>
error instanceof PostgresSchemaReadinessError &&
error.code === 'server_version_unsupported',
);
assert.equal(events.includes('create-stack'), false);
assert.deepEqual(events.slice(-2), ['audit:failed', 'close-database']);
});
test('opens once, assembles after readiness, and closes after stack shutdown', async () => {
const events = [];
const result = await bootstrapClusterControlRuntime(bootstrapOptions(events));
assert.equal(result.status, 'active');
assert.equal(events.filter((event) => event === 'open-database').length, 1);
assert.ok(events.indexOf('create-stack') > events.lastIndexOf('query:8'));
const first = result.stop();
assert.equal(first, result.stop());
assert.equal(await first, 'stopped');
assert.deepEqual(events.slice(-4), [
'dispose-admission',
'stop-stack',
'audit:stopped',
'close-database',
]);
});
test('injects reviewed Worker operations without exposing the runtime Pool', async () => {
const events = [];
const artifactStore = {
async put() {
throw new Error('not invoked during assembly');
},
async inspect() {
throw new Error('not invoked during assembly');
},
};
const result = await bootstrapClusterControlRuntime(
bootstrapOptions(events, {
workerRuntime: { artifactStore },
create(input) {
events.push('create-stack');
assert.equal('pool' in input, false);
assert.equal(Object.isFrozen(input.workerRuntime), true);
assert.equal(typeof input.workerRuntime.offers.claimNext, 'function');
assert.equal(
typeof input.workerRuntime.activation.acknowledgeStarting,
'function',
);
assert.equal(input.workerRuntime.secrets, undefined);
assert.equal(typeof input.workerRuntime.artifacts.upload, 'function');
assert.equal(
typeof input.workerRuntime.completion.complete,
'function',
);
assert.equal(
typeof input.workerRuntime.leaseControl.control,
'function',
);
return activationStack(events);
},
}),
);
assert.equal(result.status, 'active');
assert.equal(await result.stop(), 'stopped');
});
test('production scheduler cadence scans schedules, Workflow frontier, and Task Attempt admission', async () => {
const events = [];
let resolveCycle;
const cycle = new Promise((resolve) => {
resolveCycle = resolve;
});
const result = await bootstrapClusterControlRuntime(
bootstrapOptions(events, {
scheduler: {
intervalMs: 250,
onDiagnostic(error, summary) {
resolveCycle({ error, summary });
},
},
cancellationConvergence: { intervalMs: 60 * 60_000 },
async openDatabase() {
events.push('open-database');
return databaseResource(events, { runtimeScans: true });
},
}),
);
const observed = await Promise.race([
cycle,
new Promise((_, reject) => {
const timeout = setTimeout(
() => reject(new Error('production scheduler cycle did not run')),
2_000,
);
timeout.unref?.();
}),
]);
assert.equal(observed.error, undefined);
assert.deepEqual(observed.summary, {
firstClaimAcquiredAtMs: null,
lastClaimAcquiredAtMs: null,
claimed: 0,
initialized: 0,
skipped: 0,
admitted: 0,
raced: 0,
saturated: false,
});
assert.deepEqual(
events.filter((event) => event.startsWith('scan:')),
[
'scan:runtime-recovery',
'scan:lost-retry',
'scan:schedules',
'scan:workflow-frontier',
'scan:workflow-task-attempts',
],
);
assert.equal(await result.stop(), 'stopped');
assert.ok(events.includes('release:workflow-task-attempts'));
});
test('unsafe recovery stops the stack and closes the database', async () => {
const events = [];
await assert.rejects(
bootstrapClusterControlRuntime(
bootstrapOptions(events, {
create({ runs }) {
events.push('create-stack');
assert.equal(typeof runs.findRunById, 'function');
return activationStack(events, {
safe: false,
remaining: 1,
failed: 0,
});
},
}),
),
/did not converge safely/,
);
assert.equal(events.includes('install-admission'), false);
assert.deepEqual(events.slice(-3), [
'stop-stack',
'audit:failed',
'close-database',
]);
});
test('bootstrap-owned recovery blocks a false-safe stack when the claim store is unavailable', async () => {
const events = [];
await assert.rejects(
bootstrapClusterControlRuntime(
bootstrapOptions(events, {
async openDatabase() {
events.push('open-database');
return databaseResource(events, {
recoveryRows: [
{
observedAtMs: '1',
kind: 'run',
id: 'run-1',
runId: 'run-1',
status: 'running',
createdAtMs: '1',
},
{
observedAtMs: '1',
kind: 'attempt',
id: 'attempt-1',
runId: 'run-1',
status: 'running',
createdAtMs: '2',
},
],
});
},
}),
),
(error) =>
error?.name === 'ClusterControlRecoveryStoreError' &&
error.retryable === true,
);
assert.equal(events.includes('install-admission'), false);
assert.equal(events.includes('reconcile'), false);
assert.deepEqual(events.slice(-3), [
'stop-stack',
'audit:failed',
'close-database',
]);
});
test('database close failure does not skip stack shutdown and remains idempotent', async () => {
const events = [];
const closeError = new Error('database close failed');
const result = await bootstrapClusterControlRuntime(
bootstrapOptions(events, {
async openDatabase() {
events.push('open-database');
return databaseResource(events, { closeError });
},
}),
);
const first = result.stop();
assert.equal(first, result.stop());
await assert.rejects(first, (error) => error === closeError);
assert.deepEqual(events.slice(-4), [
'dispose-admission',
'stop-stack',
'audit:stopped',
'close-database',
]);
});
@@ -0,0 +1,201 @@
const assert = require('node:assert/strict');
const path = require('node:path');
const { test } = require('node:test');
const {
loadPostgresCertificateAuthorityFile,
} = require('@qinglong/cluster-postgres/runtime');
const {
ClusterControlConfigError,
createClusterControlDatabaseBinding,
loadClusterControlConfig,
} = require('@qinglong/cluster-control/config');
const CA_FILE = path.join(__dirname, 'fixtures', 'mtls', 'ca-cert.pem');
const CA_BUNDLE = loadPostgresCertificateAuthorityFile(CA_FILE);
const BASE_ENV = Object.freeze({
QL3_CLUSTER_CONTROL_ENABLED: 'true',
QL_DEPLOYMENT_PROFILE: 'cluster-control',
QL3_POSTGRES_RUNTIME_URL:
'postgresql://ql3_runtime:secret@database.internal:5432/qinglong',
QL3_POSTGRES_TLS_SERVERNAME: 'database.internal',
QL3_API_CREDENTIAL_PEPPER: 'A'.repeat(43),
});
test('disabled configuration does not read PostgreSQL credentials', () => {
const reads = [];
const environment = new Proxy(
{
QL3_CLUSTER_CONTROL_ENABLED: 'false',
QL_DEPLOYMENT_PROFILE: 'standalone',
},
{
get(target, property, receiver) {
reads.push(property);
if (
property === 'QL3_POSTGRES_RUNTIME_URL' ||
property === 'QL3_API_CREDENTIAL_PEPPER'
) {
throw new Error('credential must not be read');
}
return Reflect.get(target, property, receiver);
},
},
);
assert.deepEqual(loadClusterControlConfig(environment), {
enabled: false,
profile: 'standalone',
});
assert.equal(reads.includes('QL3_POSTGRES_RUNTIME_URL'), false);
assert.equal(reads.includes('QL3_API_CREDENTIAL_PEPPER'), false);
});
test('enabled configuration requires the exact cluster-control profile', () => {
assert.throws(
() =>
loadClusterControlConfig({
...BASE_ENV,
QL_DEPLOYMENT_PROFILE: 'standalone',
}),
ClusterControlConfigError,
);
assert.throws(
() =>
loadClusterControlConfig({
...BASE_ENV,
QL3_CLUSTER_CONTROL_ENABLED: 'yes',
}),
ClusterControlConfigError,
);
});
test('builds an exact runtime-only TLS-verified Pool configuration', async () => {
const config = loadClusterControlConfig({
...BASE_ENV,
QL3_CLUSTER_HTTP_HOST: '127.0.0.1',
QL3_CLUSTER_HTTP_PORT: '5900',
QL3_CLUSTER_HTTP_MAX_IN_FLIGHT: '32',
QL3_CLUSTER_AUTH_RATE_WINDOW_MS: '30000',
QL3_CLUSTER_AUTH_RATE_PER_PEER: '20',
QL3_CLUSTER_AUTH_RATE_GLOBAL: '200',
QL3_CLUSTER_AUTH_RATE_MAX_PEERS: '512',
QL3_POSTGRES_MAX_CONNECTIONS: '12',
QL3_POSTGRES_TLS_SERVERNAME: 'database.internal',
QL3_POSTGRES_TLS_CA_FILE: CA_FILE,
});
assert.equal(config.enabled, true);
assert.deepEqual(config.http, {
host: '127.0.0.1',
port: 5900,
maxBodyBytes: 1024 * 1024,
maxInFlightRequests: 32,
authenticationRateWindowMs: 30_000,
authenticationRatePerPeer: 20,
authenticationRateGlobal: 200,
authenticationRateMaxPeers: 512,
requestTimeoutMs: 15_000,
drainTimeoutMs: 10_000,
});
assert.deepEqual(config.database, {
connection: {
connectionString: BASE_ENV.QL3_POSTGRES_RUNTIME_URL,
tls: {
mode: 'verify-full',
ca: CA_BUNDLE,
servername: 'database.internal',
},
},
pool: {
applicationName: 'qinglong-cluster-runtime',
maxConnections: 12,
connectionTimeoutMs: 5_000,
},
});
assert.deepEqual(config.security, {
apiCredentialPepper: BASE_ENV.QL3_API_CREDENTIAL_PEPPER,
});
const binding = createClusterControlDatabaseBinding(config);
assert.equal(binding.availability.status, 'available');
const database = await binding.openDatabase();
await database.close();
});
test('loads discrete operator-managed runtime credentials without a DSN copy', () => {
const {
QL3_POSTGRES_RUNTIME_URL: _connectionString,
...withoutConnectionString
} = BASE_ENV;
const config = loadClusterControlConfig({
...withoutConnectionString,
QL3_POSTGRES_RUNTIME_HOST: 'ql3-postgres-rw.qinglong3-system.svc',
QL3_POSTGRES_RUNTIME_PORT: '5432',
QL3_POSTGRES_RUNTIME_DATABASE: 'qinglong',
QL3_POSTGRES_RUNTIME_USER: 'ql3_runtime',
QL3_POSTGRES_RUNTIME_PASSWORD: 'operator-secret',
});
assert.deepEqual(config.database.connection, {
host: 'ql3-postgres-rw.qinglong3-system.svc',
port: 5432,
database: 'qinglong',
user: 'ql3_runtime',
password: 'operator-secret',
tls: {
mode: 'verify-full',
servername: 'database.internal',
},
});
});
test('requires a second explicit gate before disabling PostgreSQL TLS', () => {
assert.throws(
() =>
loadClusterControlConfig({
...BASE_ENV,
QL3_POSTGRES_TLS_MODE: 'disable',
}),
/requires QL3_POSTGRES_ALLOW_INSECURE=true/,
);
const config = loadClusterControlConfig({
...BASE_ENV,
QL3_POSTGRES_TLS_MODE: 'disable',
QL3_POSTGRES_ALLOW_INSECURE: 'true',
});
assert.deepEqual(config.database.connection.tls, { mode: 'disable' });
});
test('rejects TLS query overrides, missing credentials and unbounded values', () => {
for (const environment of [
{
...BASE_ENV,
QL3_POSTGRES_RUNTIME_URL:
'postgresql://database.internal/qinglong?sslmode=disable',
},
{ ...BASE_ENV, QL3_POSTGRES_TLS_SERVERNAME: undefined },
{ ...BASE_ENV, QL3_POSTGRES_TLS_SERVERNAME: '127.0.0.1' },
{ ...BASE_ENV, QL3_POSTGRES_TLS_CA_FILE: 'relative-ca.pem' },
{
...BASE_ENV,
QL3_POSTGRES_TLS_MODE: 'disable',
QL3_POSTGRES_ALLOW_INSECURE: 'true',
QL3_POSTGRES_TLS_CA_FILE: CA_FILE,
},
{ ...BASE_ENV, QL3_POSTGRES_RUNTIME_URL: '' },
{
...BASE_ENV,
QL3_POSTGRES_RUNTIME_HOST: 'database.internal',
},
{ ...BASE_ENV, QL3_POSTGRES_MAX_CONNECTIONS: '65' },
{ ...BASE_ENV, QL3_CLUSTER_HTTP_MAX_BODY_BYTES: '99999999' },
{ ...BASE_ENV, QL3_CLUSTER_AUTH_RATE_WINDOW_MS: '99999999' },
{ ...BASE_ENV, QL3_CLUSTER_AUTH_RATE_PER_PEER: '0' },
{ ...BASE_ENV, QL3_CLUSTER_AUTH_RATE_GLOBAL: '1000001' },
{ ...BASE_ENV, QL3_CLUSTER_AUTH_RATE_MAX_PEERS: '65537' },
{ ...BASE_ENV, QL3_API_CREDENTIAL_PEPPER: 'weak' },
]) {
assert.throws(
() => loadClusterControlConfig(environment),
ClusterControlConfigError,
);
}
});
@@ -0,0 +1,50 @@
const assert = require('node:assert/strict');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
const { test } = require('node:test');
test('public application, config, admission and route exports exclude migration and legacy modules', () => {
const packageDirectory = path.resolve(__dirname, '..');
const script = `
const application = require('@qinglong/cluster-control/application');
const config = require('@qinglong/cluster-control/config');
const admission = require('@qinglong/cluster-control/admission');
const routes = require('@qinglong/cluster-control/routes');
const runRoutes = require('@qinglong/cluster-control/run-routes');
const apiCredential = require('@qinglong/cluster-control/api-credential');
const loaded = Object.keys(require.cache).map((file) => file.replaceAll('\\\\', '/'));
process.stdout.write(JSON.stringify({
hasStart: typeof application.startClusterControlApplication === 'function',
hasConfig: typeof config.loadClusterControlConfig === 'function',
hasAdmission: typeof admission.createClusterControlAdmissionPipeline === 'function',
hasRoutes: typeof routes.createClusterControlRouteRegistry === 'function',
hasRunReadRoute: typeof runRoutes.createClusterControlRunReadRoute === 'function',
hasApiCredential: typeof apiCredential.createClusterControlApiCredentialAuthenticator === 'function',
loaded,
}));
`;
const result = spawnSync(process.execPath, ['-e', script], {
cwd: packageDirectory,
encoding: 'utf8',
});
assert.equal(result.status, 0, result.stderr);
const report = JSON.parse(result.stdout);
assert.equal(report.hasStart, true);
assert.equal(report.hasConfig, true);
assert.equal(report.hasAdmission, true);
assert.equal(report.hasRoutes, true);
assert.equal(report.hasRunReadRoute, true);
assert.equal(report.hasApiCredential, true);
assert.equal(
report.loaded.some(
(file) =>
file.includes('/back/') ||
/\/ql3-cluster-postgres\/dist\/migrations\/pg-\d/.test(file) ||
file.endsWith('/ql3-cluster-postgres/dist/migration/migrate.js') ||
file.endsWith('/ql3-cluster-postgres/dist/migration/migration.js') ||
file.endsWith('/ql3-cluster-postgres/dist/schema/schema.js'),
),
false,
report.loaded.join('\n'),
);
});
@@ -0,0 +1,20 @@
-----BEGIN CERTIFICATE-----
MIIDMTCCAhmgAwIBAgIUT09qZ5rsuZyfzb0ngF3gc/MLVT0wDQYJKoZIhvcNAQEL
BQAwIDEeMBwGA1UEAwwVUWluZ0xvbmctMy1UZXN0LUNBLXYyMB4XDTI2MDcxOTE1
MDU0M1oXDTQ2MDcxNDE1MDU0M1owIDEeMBwGA1UEAwwVUWluZ0xvbmctMy1UZXN0
LUNBLXYyMIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8AMIIBCgKCAQEA3ZjZrBMqBu5U
fGgnp4j9ohhwq2iCW9Y1U8tkFvxpca9SJawQAZE8U0D0fy1JPUOrUHP1j5PzDMk3
CC3WfrP/e26Xx/BwXp45QfZS24vHPu8+0KCo3FfNoQPcXra58+XpNh6AhLdk1cMl
/kSFDC/fwo4elETiETdmCD7g/JwvM0U4l+5yGN4lW0Wb7P4S+6Red1xxt9QWT6b7
FREoXtL/Ego69T8kabLH38WlUVm+Mfhb18yMTlDDpOI83xbxDUinfivGREr41QUe
RGE2+I1XKjztXqowdkIb3T3JVDx/WMI9+4m2vOX1ZJNjS0ZpaEeMzlNLSJKNQaMR
uOmDqBPJJwIDAQABo2MwYTAdBgNVHQ4EFgQUZw224kl/JxHPu4khthe4bwJw5JIw
HwYDVR0jBBgwFoAUZw224kl/JxHPu4khthe4bwJw5JIwDwYDVR0TAQH/BAUwAwEB
/zAOBgNVHQ8BAf8EBAMCAQYwDQYJKoZIhvcNAQELBQADggEBAF6yWGbSYV7PT5+G
6Am4M7n2xpy6EjtKN6jaeh46K6xTReooTJKj3Yix/AYYYG/Bh24CCjg7zxIq7CzL
gPoJjGiSJVZBguHwSmzo1HajJJ7ncumT5cZwXbxHQ521CqQbskrltPJNf3P5tKq5
AzCJ2KrTmi30LNbH1G1v9bkwsVv+T4aWYN+o3cIpMPklLvWKq381dT7eN0/O/rwK
wUUXOUYFClHqm7M5jOQNrt7dneHU/R9GEYGWCw/T9FwNe7QovhcI22Q5xtbJZ9HR
B/8/OZ+yB6ZmkPnw1STJ1YOckorSRNQLFOchdZP7CeXFOTRmU9KHoIka+zG9aOab
/NVGuLU=
-----END CERTIFICATE-----
@@ -0,0 +1,19 @@
-----BEGIN CERTIFICATE-----
MIIDKzCCAhOgAwIBAgICEAEwDQYJKoZIhvcNAQELBQAwIDEeMBwGA1UEAwwVUWlu
Z0xvbmctMy1UZXN0LUNBLXYyMB4XDTI2MDcxOTE1MDYzOFoXDTQ2MDcxNDE1MDYz
OFowGjEYMBYGA1UEAwwPcWwzLXRlc3Qtd29ya2VyMIIBIjANBgkqhkiG9w0BAQEF
AAOCAQ8AMIIBCgKCAQEArmm2syXGg03ZHQgoMknVv+QC9qVGA46Xnr8K/lgppZID
H/7obm8P0oiAbgOQbKhEzoY+9fjoW2VWBKft1PkVfzjxBvsU/76KIrluKBn+wwtr
LEkPxHaawYTtMUm6Urvxq2VlzU7pdZVJ1PLWovBxyhwe8OUagkvtqYkLN3t6YHZo
kMgIjHKx8SKWUZRQ846V6mm2/8e+lO+BTd/wb7cEvZDYbqoKaqlm91sO6NDuvAJl
DrLLQprdBg4kn6rI1/T2vztuz7TkAgAlkJyDJ2rz+VGSTZ6NxFKaV4hbF8b5RA4S
SKDwqaNtFYoS+p5gJsyNSGvMOKUzMCiyapd8fB6tBQIDAQABo3UwczAMBgNVHRMB
Af8EAjAAMA4GA1UdDwEB/wQEAwIFoDATBgNVHSUEDDAKBggrBgEFBQcDAjAdBgNV
HQ4EFgQUj2XZPOHX/LbNTC2Uolt6HAkofbUwHwYDVR0jBBgwFoAUZw224kl/JxHP
u4khthe4bwJw5JIwDQYJKoZIhvcNAQELBQADggEBAGsbsLjPTnev7JCpfC88HmgW
pL22q93WDQ407O2+t/5dOc5AyZZx9kR6cUKfKT/JlseDN6x8V0yVDeq6OtKKYmDg
xB8P1n/e/GCjx3w3cYWhP5bNw9yNNTIReG3DnKGr4Q6Xe8YA415o7GQSp24oNa0R
Kx3xCr+y3VLOu6eeotsSb7tezcEvGTFXAd61wNMPIjyN1ZevIoNcMnYUbjAkH2py
sDVP/8XjQCcU9vXTZPVtxGKkC+w6oiYpG96kixe//N8IgruiJHL/74/RxiOR0Zt/
MDnrYFyS3Mp9hMHGbhJ41NhaUUDr7IAQQqsY9su6CMS50DtgSwZQ+kkzf+NBo4I=
-----END CERTIFICATE-----
@@ -0,0 +1,28 @@
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQCuabazJcaDTdkd
CCgySdW/5AL2pUYDjpeevwr+WCmlkgMf/uhubw/SiIBuA5BsqETOhj71+OhbZVYE
p+3U+RV/OPEG+xT/vooiuW4oGf7DC2ssSQ/EdprBhO0xSbpSu/GrZWXNTul1lUnU
8tai8HHKHB7w5RqCS+2piQs3e3pgdmiQyAiMcrHxIpZRlFDzjpXqabb/x76U74FN
3/BvtwS9kNhuqgpqqWb3Ww7o0O68AmUOsstCmt0GDiSfqsjX9Pa/O27PtOQCACWQ
nIMnavP5UZJNno3EUppXiFsXxvlEDhJIoPCpo20VihL6nmAmzI1Ia8w4pTMwKLJq
l3x8Hq0FAgMBAAECggEADWf/zJ5rN12NAj/FwzPMs87FcYr7qjtUKTYbFLjXHqxu
BBAWcqKjzzWB1bL9b3SxsUQ9Y6/JwHi2F26HB/dLcTeBw10aXJwbRxcEwh1ZaUmf
58wH47yQIa7jgoXdxg0/QsLtA858gHbEsZMm72hW/seRk0ew9XH7pyvrCk05918S
IvtN49gZdffw0O/V89Mys1ZA/w/hsi6NuZI0zEIjOMWN1hMPKYHbVbaYaIX0mC6P
Yg26UXqf8g6SgW/dYLt28r69yGvKBwyztYw47Ieo2NyWToZsHHg5ypdjUXnt++wn
sFPNo28KVu/NYTGY6Y2TphamdZTUetQ+0AfeITTiYwKBgQDaa6gmDHqHEPwdgLmu
fwrKNiU/NwNx8ZwEMYYvlyCmmXRLbTFux3AE1xHUUQac1PAhmelZwulm3tInQ94F
pDTkjfcZt/K83gLkNVLbNepbVKfrvcAHbPcoBC3k161RcrYW0LxR/P8z/YXyzkUI
04/g90INoKKITc8hoI1Ttmyn3wKBgQDMa72ICOa/HFmoT/G8xWkqU71F1rKGanJ3
sTPZXjGEyx0atSWB0XfmBd0hiIAx1DWuUo4EZ9Yul1B97gmnJSxbXGcKTfp8+1kS
YySIx1GE0qG23n/xppeT0xPUCyJl/UuAKEKi7l3ZtT4RiaDP/KRo2LuKmCXuxSSa
6d5YYsAXmwKBgQC8fEjXxM77vZmDMDGMNs+t3nnYCnZrns8/AynD6cvgWO51pJ4S
9gJh+uLE8MMfFda/eF1Z+4yFHGYIQlXXUnPeg/An/oh3mbKvEqEU0HsUI4LhOZb8
EXlby/d60vAbKD2ghLLuob/tMquj84K5cjBoN5eFwQhhTZwgbbdn9TXgywKBgHxG
6BQi7T20m6Fi8OFF1xi/jis+SozDfFHeLlpxFIPaBBivllzlHxJ98CEp3l3s2LHh
SKvPAPyUS4AzzjSKufvVImO2YpnHKTCvi4+INbwdXelSPdCI6lAZnE1mc4QzyMni
MBjj97SapmB9HoIz4zRGx0WMGEugGRABLIbpikUPAoGAbdUAdEwQIIcOZEvl5spC
CNX2AMXCIQk4qkauJo+c/fQJXL/nHaO3reOXSJc1QjB1ceoZ+s0WuN7avkwy+jJ/
ZXGxdo/ewFNYTqELnnN2/Kr6GDvpwrlwGhdNpp2Sxjnyq7DAxnfbaTdhUo+WGV70
+VIzVYYa+dhmUFNEvWtwt4Y=
-----END PRIVATE KEY-----
@@ -0,0 +1,10 @@
-----BEGIN X509 CRL-----
MIIBeTBjAgEBMA0GCSqGSIb3DQEBCwUAMCAxHjAcBgNVBAMMFVFpbmdMb25nLTMt
VGVzdC1DQS12MhcNMjYwNzE5MTUwNjQ0WhcNNDYwNzE0MTUwNjQ0WqAPMA0wCwYD
VR0UBAQCAhAAMA0GCSqGSIb3DQEBCwUAA4IBAQA3HS0UP59J+d0bRTTjFzLRHaaX
BUr/2FBK7YcKr6wiSa8EVhiiRZ6zcPShIfKPDhNn/rozMJST0SyO4aH6A+BOuAsl
jK37Cz1gdDcdnNTo87/QTPVSe1wQqNHu8fJSQgQMIOqjUigB8crIhcNBJO7wSVxl
AELA5XV6QiVKT3vQZjfY6o99y1790x+BjcIi/zWSFRY5dFFLVCuPgxj+fR6+S04V
cAVAWNt9z+eRf0uYbV+VseT2Xb5HieR/PZCN2oc3xyEQsNs5m2txCAy+ld3sUl/z
2FDP+JBla05W+0xP8Ql5sCd1NZahrrxVvbRFJcJG25sRuYOGZVNHbtqMGD5U
-----END X509 CRL-----
@@ -0,0 +1,11 @@
-----BEGIN X509 CRL-----
MIIBkDB6AgEBMA0GCSqGSIb3DQEBCwUAMCAxHjAcBgNVBAMMFVFpbmdMb25nLTMt
VGVzdC1DQS12MhcNMjYwNzE5MTUwNjUzWhcNNDYwNzE0MTUwNjUzWjAVMBMCAhAB
Fw0yNjA3MTkxNTA2NDlaoA8wDTALBgNVHRQEBAICEAEwDQYJKoZIhvcNAQELBQAD
ggEBALG0R1hPya3WzAeLkGqcGoVz3HLDn1igESMSK34532NWSJwq161sZXLogy+K
J1+NL7g8C9FbMqP9ZkA36rKt4TDRpdoLO1uLKCUVEQ3O87iUVixyKTWU2lUDOk5P
ivJNf6y/TypKK5dOxkrOUH6eB4qmGPLZu1w8JWSbYlYLXueQ6NXR1mXeN4ZPaLi5
5HGxMdAjRRWkiRm4LFbeJEiIcDEAxOwfKObdH5eC+VSl9acECQfLOkJ38ku18gtH
Wha1Na5cQ6G6TwMbtQ60RXkdLmLonD3b/mRBoVwuIMbXq7tXOigc08+JANUjnair
Df9nrEWjhB8V4NoDsAYZddG/cEc=
-----END X509 CRL-----
@@ -0,0 +1,20 @@
-----BEGIN CERTIFICATE-----
MIIDQzCCAiugAwIBAgICEAAwDQYJKoZIhvcNAQELBQAwIDEeMBwGA1UEAwwVUWlu
Z0xvbmctMy1UZXN0LUNBLXYyMB4XDTI2MDcxOTE1MDYyMloXDTQ2MDcxNDE1MDYy
MlowFDESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEFAAOCAQ8A
MIIBCgKCAQEAwzxMyomJ5BxMMlRpZgmUd1t5SnEYxN7YLjOW5fdaI0tyg6r5R7Rm
Ykui0ArxInaICXecgXk9O7MydAT8+W+aU8VLOaBA/lY6waFMrMGinCrmIXjuaB/H
POeslX4hvx6i1teOGA1HmF0ELyDbuUNlIQjJ12sKJ3+FLo9vZf+JjRW3DP0Yt1tB
mxWURb51VSnLzBTCp/INlm25/DZ7M+Kr2gqXtHoegO6aqTRWIRgCXlVKpCoaA2lv
1RY1LwPY1KhTM/fUMYz9/pwwDPmKFRQbvH6lBRl3tayP0uR1jIheOAeC5/F2A1TA
G5LMusSQ0vrn1+wolkB4qf6bBgTK5y6R4wIDAQABo4GSMIGPMAwGA1UdEwEB/wQC
MAAwDgYDVR0PAQH/BAQDAgWgMBMGA1UdJQQMMAoGCCsGAQUFBwMBMBoGA1UdEQQT
MBGCCWxvY2FsaG9zdIcEfwAAATAdBgNVHQ4EFgQUDB+Pt69+4JOSkxeky0fLzgVN
9UIwHwYDVR0jBBgwFoAUZw224kl/JxHPu4khthe4bwJw5JIwDQYJKoZIhvcNAQEL
BQADggEBAJpLx9FSXd426hE8q7QbhAyaK27/li7J/X93Zzkf7FV7mHFpl22SZ5No
airtCM41hZXBY9BTb0OGzHOb4L7Yef5c6zjKrsDNlWixAunJg7kMJ+So8DhLugXo
OIjWV1qX3dkx7oPg9I9s62rZGdQPFhmz+YAz/7WYAeNBpnwC0bCBH2ksOo0SArEA
W4S0SlX+3g+vTk9f1JM90ytqDKU7fCcHFCuI+kM5IcWIjhvejpxmmywFYBXvng2+
dL2xOmhyTWey+Q057JFqG8UNYF75OJ/Q090Lq/QVCMX7715wG8Uwe6InMll/otgl
u6GSeoX8wp5aM6+IBynaRhdpJoSK/Ik=
-----END CERTIFICATE-----
@@ -0,0 +1,28 @@
-----BEGIN PRIVATE KEY-----
MIIEvQIBADANBgkqhkiG9w0BAQEFAASCBKcwggSjAgEAAoIBAQDDPEzKiYnkHEwy
VGlmCZR3W3lKcRjE3tguM5bl91ojS3KDqvlHtGZiS6LQCvEidogJd5yBeT07szJ0
BPz5b5pTxUs5oED+VjrBoUyswaKcKuYheO5oH8c856yVfiG/HqLW144YDUeYXQQv
INu5Q2UhCMnXawonf4Uuj29l/4mNFbcM/Ri3W0GbFZRFvnVVKcvMFMKn8g2Wbbn8
Nnsz4qvaCpe0eh6A7pqpNFYhGAJeVUqkKhoDaW/VFjUvA9jUqFMz99QxjP3+nDAM
+YoVFBu8fqUFGXe1rI/S5HWMiF44B4Ln8XYDVMAbksy6xJDS+ufX7CiWQHip/psG
BMrnLpHjAgMBAAECggEAK7fvjDUjWyDZETYkyfQgOmAR95D+1mr+Zs4nnsR2e0vU
T1a0bpGfkahVQ5gHqkt3qAMQWU/gXeOBS0ioq2SJ3vNhpnxTwYBmtOBdTpwnwSe8
E8fEPy3KjEFmvK0benQuS8TGLW2f2CcQHkuR2FkWpsCUjjgKdJDSLnxxGhqQXzaW
3sVFH6m6tYtOqcGPJscNkKiPh2fHIfKgiKLCVZSM4zw1FRXFk9c9dfnu1yNKeKZE
fDn7p5+bDHQJio/w0AbOO90satqHYJEirPEuhrTQ6xo3jkJ+u0XWZ0n5fkxyHaiU
oJcQ1BZ2VCMK2uD3MnlW1Kea8HeVWFAAaoNMjt278QKBgQDrVSlqRXdtSVaGu9WT
20jVttUrcZl1D8G5CEO+PfMmMtJ8HyanlZPIiOzbSIWw94EXW6qpMeq2nxIn6xJI
rJKWDkkYkAjScVfH6nNxyg4FDpbzMbD6ZN+KBkdbj7QyjYqo3PbSjFdDu5BDtKa1
J5xaIWc8jB2R57yOekm3+QvPswKBgQDUYajbr+owoN9G8ij9PbpnacnrK8l+MvZO
kwYlKB/IFXa+Zp9GA1W0ViyndTd8Jjq+JYXn4XpZyoPznLmxKUlXrlUBLgml2+nX
gUYKerW2h3k1xd7mWalG2Iwqykkm27qSjeJteQsjI2lb+d2F7J4+wufWOXzfT+FP
ISTYOmedEQKBgQC/lAyrHvIiXdm6xZ8RRyr8EGNpgolS6wjiAQBlFzmily0TLqjh
NLuiPRXVTizH7DWDNnSwWJqjIMw/AvdXgmWzEt4eyOLlrq+vaAWjVMIlC8OHJ6TT
stroGkRtHYesv91pqriknutLkJ3ZAG/WefCmzxqkB8zqwqSVuKfaxTwAUQKBgA99
f/9l+ULKuP5Hs02lLu9T+/I3I18dAHICrzQOlSLWze5dNci5fYrFrkQYfI+FiktM
GVQsUewypSUjjTeqtzq58GFBplp+i7O4Lg+dm5tQjjqpz/QlHf+Y08BbOLKo3BbM
WnN5nKJXdtvKgam+9FvHg3lQgBcZkGlhFXrf56bBAoGARWjH3qFhePIIR/o/YyU4
fPhLYtiIgIvr5Is4hkGcMIOu2bnmYUCHa/zBmLqKV4K3F4u4RWmieAiLmvwi+9YD
3xZ/RVIi5yK5CKCk7hOp4AVBF9bdLIxXiRSkIO6QMithomoYlc+UkfXHMGyZFQ6h
bxKAymile6IWwd4ALAsPb3U=
-----END PRIVATE KEY-----
@@ -0,0 +1,710 @@
const assert = require('node:assert/strict');
const { readFileSync } = require('node:fs');
const http = require('node:http');
const https = require('node:https');
const path = require('node:path');
const { test } = require('node:test');
const {
ClusterControlAdmissionDrainTimeoutError,
ClusterControlHttpConfigurationError,
startClusterControlHttpSurface,
} = require('@qinglong/cluster-control/http');
const EVIDENCE = Object.freeze({
contractName: 'control-core',
contractVersion: 2,
serverMajor: 16,
migrationIds: Object.freeze([
'pg-0001-schema-capability',
'pg-0002-run-core',
'pg-0003-run-retry-policy',
]),
});
const MTLS_FIXTURES = path.join(__dirname, 'fixtures', 'mtls');
const MTLS = Object.freeze({
privateKey: readFileSync(path.join(MTLS_FIXTURES, 'server-key.pem')),
certificateChain: readFileSync(path.join(MTLS_FIXTURES, 'server-cert.pem')),
clientCertificateAuthorities: Object.freeze([
readFileSync(path.join(MTLS_FIXTURES, 'ca-cert.pem')),
]),
});
function pipeline(handler) {
return {
async prepare(metadata) {
return {
handle(body) {
return handler({ ...metadata, body });
},
};
},
};
}
function request(address, options = {}) {
const rawBody = options.rawBody;
const body =
rawBody === undefined
? options.body === undefined
? undefined
: Buffer.from(JSON.stringify(options.body))
: Buffer.from(rawBody);
const headers = { connection: 'close', ...options.headers };
if (body && headers['content-length'] === undefined) {
headers['content-length'] = String(body.byteLength);
}
if (options.body !== undefined && headers['content-type'] === undefined) {
headers['content-type'] = 'application/json';
}
return new Promise((resolve, reject) => {
const outgoing = http.request(
{
host: address.host,
port: address.port,
method: options.method ?? 'GET',
path: options.path ?? '/',
headers,
},
(response) => {
const chunks = [];
response.on('data', (chunk) => chunks.push(chunk));
response.on('end', () => {
const text = Buffer.concat(chunks).toString('utf8');
resolve({
statusCode: response.statusCode,
headers: response.headers,
body: text.length === 0 ? null : JSON.parse(text),
});
});
},
);
outgoing.on('error', reject);
if (body) outgoing.write(body);
outgoing.end();
});
}
function secureRequest(address, withClientCertificate, options = {}) {
return new Promise((resolve, reject) => {
const outgoing = https.request(
{
host: '127.0.0.1',
servername: 'localhost',
port: address.port,
path: options.path ?? '/livez',
method: options.method ?? 'GET',
agent: options.agent,
ca: readFileSync(path.join(MTLS_FIXTURES, 'ca-cert.pem')),
...(withClientCertificate
? {
key: readFileSync(path.join(MTLS_FIXTURES, 'client-key.pem')),
cert: readFileSync(path.join(MTLS_FIXTURES, 'client-cert.pem')),
}
: {}),
minVersion: 'TLSv1.3',
maxVersion: 'TLSv1.3',
},
(response) => {
const tlsProtocol = response.socket.getProtocol();
const chunks = [];
response.on('data', (chunk) => chunks.push(chunk));
response.on('end', () => {
resolve({
statusCode: response.statusCode,
tlsProtocol,
headers: response.headers,
body: JSON.parse(Buffer.concat(chunks).toString('utf8')),
});
});
},
);
outgoing.once('error', reject);
outgoing.end();
});
}
test('requires a trusted client certificate on the TLS 1.3 surface', async (t) => {
const surface = await startClusterControlHttpSurface({
host: '127.0.0.1',
port: 0,
mutualTls: MTLS,
});
t.after(() => surface.close());
await assert.rejects(secureRequest(surface.address, false));
const trusted = await secureRequest(surface.address, true);
assert.equal(trusted.statusCode, 200);
assert.equal(trusted.tlsProtocol, 'TLSv1.3');
assert.deepEqual(trusted.body, { status: 'live' });
});
test('reloads mTLS trust and CRLs without rebinding the listener', async (t) => {
const emptyCrl = readFileSync(path.join(MTLS_FIXTURES, 'empty-crl.pem'));
const revokedClientCrl = readFileSync(
path.join(MTLS_FIXTURES, 'revoked-client-crl.pem'),
);
const surface = await startClusterControlHttpSurface({
host: '127.0.0.1',
port: 0,
mutualTls: {
...MTLS,
certificateRevocationLists: [emptyCrl],
},
});
t.after(() => surface.close());
const address = { ...surface.address };
assert.equal((await secureRequest(address, true)).statusCode, 200);
assert.equal(
surface.reloadMutualTls({
...MTLS,
certificateRevocationLists: [revokedClientCrl],
}),
2,
);
assert.deepEqual(surface.address, address);
await assert.rejects(secureRequest(address, true));
assert.equal(
surface.reloadMutualTls({
...MTLS,
certificateRevocationLists: [emptyCrl],
}),
3,
);
assert.equal((await secureRequest(address, true)).statusCode, 200);
assert.throws(
() =>
surface.reloadMutualTls({
...MTLS,
certificateChain: 'not a certificate',
certificateRevocationLists: [emptyCrl],
}),
ClusterControlHttpConfigurationError,
);
assert.equal((await secureRequest(address, true)).statusCode, 200);
});
test('forces pre-reload keep-alive sockets to reconnect before routing', async (t) => {
const surface = await startClusterControlHttpSurface({
host: '127.0.0.1',
port: 0,
mutualTls: MTLS,
});
t.after(() => surface.close());
const agent = new https.Agent({ keepAlive: true, maxSockets: 1 });
t.after(() => agent.destroy());
let entered;
let release;
const enteredPromise = new Promise((resolve) => {
entered = resolve;
});
const releasePromise = new Promise((resolve) => {
release = resolve;
});
const dispose = surface.installAdmission(
EVIDENCE,
pipeline(async () => {
entered();
await releasePromise;
return { statusCode: 200, body: { status: 'completed' } };
}),
);
t.after(() => dispose());
const active = secureRequest(surface.address, true, {
agent,
path: '/api/v3/hold',
});
await enteredPromise;
assert.equal(surface.reloadMutualTls(MTLS), 2);
release();
assert.equal((await active).statusCode, 200);
const stale = await secureRequest(surface.address, true, { agent });
assert.equal(stale.statusCode, 503);
assert.deepEqual(stale.body, { code: 'tls_context_reloaded' });
assert.equal(stale.headers.connection, 'close');
assert.equal(
(await secureRequest(surface.address, true, { agent })).statusCode,
200,
);
});
test('exposes probes but rejects API work until admission is installed', async (t) => {
const surface = await startClusterControlHttpSurface({
host: '127.0.0.1',
port: 0,
});
t.after(() => surface.close());
const live = await request(surface.address, { path: '/livez' });
assert.equal(live.statusCode, 200);
assert.deepEqual(live.body, { status: 'live' });
assert.equal(live.headers['cache-control'], 'no-store');
const invalidProbeMethod = await request(surface.address, {
method: 'POST',
path: '/livez',
});
assert.equal(invalidProbeMethod.statusCode, 405);
assert.deepEqual(invalidProbeMethod.body, { code: 'method_not_allowed' });
const waiting = await request(surface.address, { path: '/readyz' });
assert.equal(waiting.statusCode, 503);
assert.deepEqual(waiting.body, { status: 'not_ready' });
const rejected = await request(surface.address, {
method: 'POST',
path: '/api/v3/runs',
headers: { connection: 'keep-alive' },
body: { mustNotBeRead: true },
});
assert.equal(rejected.statusCode, 503);
assert.equal(rejected.headers.connection, 'close');
let observed;
const dispose = surface.installAdmission(
EVIDENCE,
pipeline(async (incoming) => {
observed = incoming;
return { statusCode: 201, body: { accepted: true } };
}),
);
const ready = await request(surface.address, { path: '/readyz' });
assert.equal(ready.statusCode, 200);
assert.deepEqual(ready.body, { status: 'ready' });
const admitted = await request(surface.address, {
method: 'POST',
path: '/api/v3/runs?tag=a&tag=b',
headers: { 'x-request-id': 'request-123' },
body: { taskId: 'task-1' },
});
assert.equal(admitted.statusCode, 201);
assert.deepEqual(admitted.body, { accepted: true });
assert.equal(admitted.headers['x-request-id'], 'request-123');
assert.equal(observed.requestId, 'request-123');
assert.equal(observed.method, 'POST');
assert.equal(observed.path, '/api/v3/runs');
assert.deepEqual(observed.query.tag, ['a', 'b']);
assert.deepEqual(observed.body, { taskId: 'task-1' });
await dispose();
assert.equal(
(await request(surface.address, { path: '/readyz' })).statusCode,
503,
);
assert.equal(
(
await request(surface.address, {
method: 'POST',
path: '/api/v3/runs',
body: { ignored: true },
})
).statusCode,
503,
);
});
test('enforces bounded JSON requests and responses without leaking failures', async (t) => {
const diagnostics = [];
const surface = await startClusterControlHttpSurface({
host: '127.0.0.1',
port: 0,
maxBodyBytes: 1024,
maxResponseBytes: 1024,
onError(diagnostic) {
diagnostics.push(diagnostic);
},
});
t.after(() => surface.close());
const dispose = surface.installAdmission(
EVIDENCE,
pipeline(async (incoming) => {
if (incoming.path.endsWith('/large')) {
return { statusCode: 200, body: { value: 'x'.repeat(2048) } };
}
if (incoming.path.endsWith('/throw')) {
throw new Error('secret driver detail');
}
return { statusCode: 200, body: incoming.body };
}),
);
t.after(() => dispose());
const invalidJson = await request(surface.address, {
method: 'POST',
path: '/api/v3/test',
headers: { 'content-type': 'application/json' },
rawBody: '{',
});
assert.equal(invalidJson.statusCode, 400);
assert.deepEqual(invalidJson.body, { code: 'invalid_json' });
const unsupported = await request(surface.address, {
method: 'POST',
path: '/api/v3/test',
headers: { 'content-type': 'text/plain' },
rawBody: 'hello',
});
assert.equal(unsupported.statusCode, 415);
assert.deepEqual(unsupported.body, { code: 'unsupported_content_type' });
const oversized = await request(surface.address, {
method: 'POST',
path: '/api/v3/test',
headers: { 'content-type': 'application/json' },
rawBody: JSON.stringify({ value: 'x'.repeat(1024) }),
});
assert.equal(oversized.statusCode, 413);
assert.deepEqual(oversized.body, { code: 'request_too_large' });
const largeResponse = await request(surface.address, {
path: '/api/v3/large',
});
assert.equal(largeResponse.statusCode, 500);
assert.deepEqual(largeResponse.body, { code: 'response_too_large' });
const internal = await request(surface.address, {
path: '/api/v3/throw',
});
assert.equal(internal.statusCode, 500);
assert.deepEqual(internal.body, { code: 'internal_error' });
assert.equal(
JSON.stringify(internal).includes('secret driver detail'),
false,
);
assert.equal(
diagnostics.some(
(diagnostic) =>
diagnostic.phase === 'request' && diagnostic.path === '/api/v3/throw',
),
true,
);
});
test('completes admission preflight before reading an untrusted body', async (t) => {
const surface = await startClusterControlHttpSurface({
host: '127.0.0.1',
port: 0,
});
t.after(() => surface.close());
const dispose = surface.installAdmission(EVIDENCE, {
async prepare() {
throw Object.assign(new Error('credential rejected'), {
statusCode: 401,
code: 'authentication_required',
});
},
});
t.after(() => dispose());
const rejected = await request(surface.address, {
method: 'POST',
path: '/api/v3/runs',
headers: {
connection: 'keep-alive',
'content-type': 'application/json',
'content-length': String(1024 * 1024),
},
});
assert.equal(rejected.statusCode, 401);
assert.deepEqual(rejected.body, { code: 'authentication_required' });
assert.equal(rejected.headers.connection, 'close');
});
test('streams one route-bounded body without widening the JSON body cap', async (t) => {
const observations = [];
const surface = await startClusterControlHttpSurface({
host: '127.0.0.1',
port: 0,
maxBodyBytes: 1024,
});
t.after(() => surface.close());
const dispose = surface.installAdmission(EVIDENCE, {
async prepare(metadata) {
observations.push(`prepare:${metadata.path}`);
return {
bodyMode: 'stream',
contentType: 'application/vnd.qinglong.worker-artifact',
maximumBodyBytes: 8 * 1024,
async handleStream(body) {
observations.push(`handle:${body.contentLength}`);
let total = 0;
let chunks = 0;
for await (const chunk of body.chunks) {
total += chunk.byteLength;
chunks += 1;
}
return {
statusCode: 200,
body: { total, chunks, contentType: body.contentType },
};
},
};
},
});
t.after(() => dispose());
const bytes = Buffer.alloc(4 * 1024, 7);
const result = await request(surface.address, {
method: 'POST',
path: '/api/v3/worker-ingress/artifacts',
headers: {
'content-type': 'application/vnd.qinglong.worker-artifact',
},
rawBody: bytes,
});
assert.equal(result.statusCode, 200);
assert.deepEqual(result.body, {
total: bytes.byteLength,
chunks: 1,
contentType: 'application/vnd.qinglong.worker-artifact',
});
assert.deepEqual(observations, [
'prepare:/api/v3/worker-ingress/artifacts',
`handle:${bytes.byteLength}`,
]);
});
test('rejects invalid stream envelopes and incomplete consumption', async (t) => {
let handles = 0;
const surface = await startClusterControlHttpSurface({
host: '127.0.0.1',
port: 0,
});
t.after(() => surface.close());
const dispose = surface.installAdmission(EVIDENCE, {
async prepare() {
return {
bodyMode: 'stream',
contentType: 'application/vnd.qinglong.worker-artifact',
maximumBodyBytes: 1024,
async handleStream() {
handles += 1;
return { statusCode: 200, body: { accepted: true } };
},
};
},
});
t.after(() => dispose());
const oversized = await request(surface.address, {
method: 'POST',
path: '/api/v3/worker-ingress/artifacts',
headers: {
'content-type': 'application/vnd.qinglong.worker-artifact',
'content-length': '1025',
},
});
assert.equal(oversized.statusCode, 413);
assert.deepEqual(oversized.body, { code: 'request_too_large' });
assert.equal(handles, 0);
const unsupported = await request(surface.address, {
method: 'POST',
path: '/api/v3/worker-ingress/artifacts',
headers: { 'content-type': 'application/octet-stream' },
rawBody: 'log',
});
assert.equal(unsupported.statusCode, 415);
assert.deepEqual(unsupported.body, { code: 'unsupported_content_type' });
assert.equal(handles, 0);
const incomplete = await request(surface.address, {
method: 'POST',
path: '/api/v3/worker-ingress/artifacts',
headers: {
'content-type': 'application/vnd.qinglong.worker-artifact',
},
rawBody: 'log',
});
assert.equal(incomplete.statusCode, 500);
assert.deepEqual(incomplete.body, { code: 'internal_error' });
assert.equal(incomplete.headers.connection, 'close');
assert.equal(handles, 1);
});
test('refunds successful admission and limits failed preflight before body reads', async (t) => {
const events = [];
const surface = await startClusterControlHttpSurface({
host: '127.0.0.1',
port: 0,
authenticationRatePerPeer: 1,
authenticationRateGlobal: 10,
authenticationRateMaxPeers: 4,
onAuthenticationShieldEvent(event) {
events.push(event);
},
});
t.after(() => surface.close());
const beforeRead = await request(surface.address, {
path: '/api/v3/test',
headers: { 'x-forwarded-for': '198.51.100.10' },
});
assert.equal(beforeRead.statusCode, 503);
assert.deepEqual(beforeRead.body, { code: 'not_ready' });
let prepares = 0;
const dispose = surface.installAdmission(EVIDENCE, {
async prepare(metadata) {
prepares += 1;
if (metadata.path === '/api/v3/rejected') {
throw Object.assign(new Error('authentication failed'), {
statusCode: 401,
code: 'authentication_required',
});
}
return { handle: () => ({ statusCode: 204 }) };
},
});
t.after(() => dispose());
const admitted = await request(surface.address, {
path: '/api/v3/test',
headers: { 'x-forwarded-for': '198.51.100.11' },
});
assert.equal(admitted.statusCode, 204);
assert.equal(prepares, 1);
const rejected = await request(surface.address, {
path: '/api/v3/rejected',
});
assert.equal(rejected.statusCode, 401);
assert.deepEqual(rejected.body, { code: 'authentication_required' });
assert.equal(prepares, 2);
const limited = await request(surface.address, {
method: 'POST',
path: '/api/v3/rejected',
headers: {
connection: 'keep-alive',
'content-type': 'application/json',
'content-length': String(1024 * 1024),
'x-forwarded-for': '203.0.113.99',
},
});
assert.equal(limited.statusCode, 429);
assert.deepEqual(limited.body, { code: 'authentication_rate_limited' });
assert.equal(limited.headers['retry-after'], '60');
assert.equal(limited.headers.connection, 'close');
assert.equal(prepares, 2);
assert.deepEqual(events, [{ outcome: 'rate_limited', reason: 'peer' }]);
const probe = await request(surface.address, { path: '/livez' });
assert.equal(probe.statusCode, 200);
});
test('withdraws admission immediately and drains in-flight requests', async (t) => {
const surface = await startClusterControlHttpSurface({
host: '127.0.0.1',
port: 0,
maxInFlightRequests: 1,
drainTimeoutMs: 1000,
});
t.after(() => surface.close());
let entered;
const enteredPromise = new Promise((resolve) => {
entered = resolve;
});
let release;
const gate = new Promise((resolve) => {
release = resolve;
});
const dispose = surface.installAdmission(
EVIDENCE,
pipeline(async () => {
entered();
await gate;
return { statusCode: 200, body: { completed: true } };
}),
);
const first = request(surface.address, { path: '/api/v3/slow' });
await enteredPromise;
const capacity = await request(surface.address, { path: '/api/v3/second' });
assert.equal(capacity.statusCode, 503);
assert.deepEqual(capacity.body, { code: 'admission_capacity_exhausted' });
let drained = false;
const draining = dispose().then(() => {
drained = true;
});
assert.equal(
(await request(surface.address, { path: '/readyz' })).statusCode,
503,
);
await new Promise((resolve) => setImmediate(resolve));
assert.equal(drained, false);
release();
const withdrawn = await first;
assert.equal(withdrawn.statusCode, 503);
assert.deepEqual(withdrawn.body, { code: 'admission_draining' });
await draining;
assert.equal(drained, true);
});
test('reports a drain timeout when a handler ignores cancellation', async (t) => {
const surface = await startClusterControlHttpSurface({
host: '127.0.0.1',
port: 0,
drainTimeoutMs: 100,
});
t.after(() => surface.close());
let entered;
const enteredPromise = new Promise((resolve) => {
entered = resolve;
});
const dispose = surface.installAdmission(
EVIDENCE,
pipeline(async () => {
entered();
await new Promise(() => {});
return { statusCode: 200 };
}),
);
const response = request(surface.address, { path: '/api/v3/stuck' });
await enteredPromise;
await assert.rejects(dispose(), ClusterControlAdmissionDrainTimeoutError);
const timedOut = await response;
assert.equal(timedOut.statusCode, 503);
assert.deepEqual(timedOut.body, { code: 'admission_draining' });
});
test('rejects unsafe listener and resource configurations before binding', async () => {
const plaintext = await startClusterControlHttpSurface({ port: 0 });
await assert.rejects(
Promise.resolve().then(() => plaintext.reloadMutualTls(MTLS)),
/does not use mutual TLS/,
);
await plaintext.close();
await assert.rejects(
startClusterControlHttpSurface({
port: 0,
mutualTls: {
...MTLS,
certificateRevocationLists: [
'-----BEGIN X509 CRL-----\ninvalid\n-----END X509 CRL-----',
],
},
}),
ClusterControlHttpConfigurationError,
);
await assert.rejects(
startClusterControlHttpSurface({ host: '0.0.0.0;bad', port: 0 }),
ClusterControlHttpConfigurationError,
);
await assert.rejects(
startClusterControlHttpSurface({
port: 0,
maxInFlightRequests: 1025,
}),
ClusterControlHttpConfigurationError,
);
await assert.rejects(
startClusterControlHttpSurface({
port: 0,
authenticationRateMaxPeers: 65_537,
}),
ClusterControlHttpConfigurationError,
);
});
@@ -0,0 +1,157 @@
'use strict';
const assert = require('node:assert/strict');
const {
chmod,
mkdir,
mkdtemp,
rename,
rm,
symlink,
writeFile,
} = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const { test } = require('node:test');
const { createSecretRef } = require('@qinglong/runtime-core/secret-reference');
const {
ClusterMountedSecretProvider,
ClusterMountedSecretProviderError,
clusterMountedSecretFileName,
createClusterMountedSecretProvider,
} = require('@qinglong/cluster-control/mounted-secret-provider');
const SECRET_REF = createSecretRef({
projectId: 'project-1',
name: 'api-token',
});
const VERSIONED_SECRET_REF = createSecretRef({
projectId: 'project-1',
name: 'certificate',
version: 3,
});
function authority(secretRefs = [SECRET_REF]) {
return {
workerId: 'worker-1',
workerSessionId: '018f0000-0000-7000-8000-000000000001',
workerGeneration: 1,
runId: 'run-1',
attemptId: 'attempt-1',
projectId: 'project-1',
taskId: 'task-1',
taskRevision: 'revision-1',
executionDigest: 'a'.repeat(64),
offerId: 'offer-1',
leaseGeneration: 1,
leaseVersion: 1,
secretRefs,
};
}
async function privateFile(file, value, mode = 0o400) {
await writeFile(file, value);
await chmod(file, mode);
}
test('maps canonical SecretRef to a stable path-free Kubernetes key', () => {
const first = clusterMountedSecretFileName(SECRET_REF);
assert.match(first, /^[0-9a-f]{64}$/);
assert.equal(clusterMountedSecretFileName(SECRET_REF), first);
assert.notEqual(
clusterMountedSecretFileName(VERSIONED_SECRET_REF),
first,
);
assert.throws(
() => clusterMountedSecretFileName('not-a-secret-ref'),
ClusterMountedSecretProviderError,
);
});
test('resolves every request again and observes atomic material rotation', async (t) => {
const root = await mkdtemp(path.join(os.tmpdir(), 'ql3-mounted-secret-'));
t.after(() => rm(root, { recursive: true, force: true }));
await chmod(root, 0o700);
const file = path.join(root, clusterMountedSecretFileName(SECRET_REF));
await privateFile(file, 'generation-one');
const provider = await createClusterMountedSecretProvider({
rootDirectory: root,
});
const first = await provider.resolve(authority());
assert.deepEqual(first.values, [
{ secretRef: SECRET_REF, value: 'generation-one' },
]);
await first.dispose();
const replacement = `${file}.replacement`;
await privateFile(replacement, 'generation-two');
await rename(replacement, file);
const second = await provider.resolve(authority());
assert.deepEqual(second.values, [
{ secretRef: SECRET_REF, value: 'generation-two' },
]);
await second.dispose();
await second.dispose();
});
test('accepts an in-root projected-volume symlink and rejects escapes or unsafe bytes', async (t) => {
const root = await mkdtemp(path.join(os.tmpdir(), 'ql3-projected-secret-'));
const outside = await mkdtemp(path.join(os.tmpdir(), 'ql3-outside-secret-'));
t.after(async () => {
await rm(root, { recursive: true, force: true });
await rm(outside, { recursive: true, force: true });
});
await chmod(root, 0o700);
const generation = path.join(root, '..data-generation-1');
await mkdir(generation, { mode: 0o700 });
const name = clusterMountedSecretFileName(SECRET_REF);
await privateFile(path.join(generation, name), 'projected-value', 0o440);
await symlink(path.join('..data-generation-1', name), path.join(root, name));
const provider = new ClusterMountedSecretProvider({ rootDirectory: root });
const projected = await provider.resolve(authority());
assert.equal(projected.values[0].value, 'projected-value');
await projected.dispose();
await rm(path.join(root, name));
await privateFile(path.join(outside, name), 'escaped-value');
await symlink(path.join(outside, name), path.join(root, name));
await assert.rejects(
provider.resolve(authority()),
ClusterMountedSecretProviderError,
);
await rm(path.join(root, name));
await privateFile(path.join(root, name), 'world-readable', 0o444);
await assert.rejects(
provider.resolve(authority()),
ClusterMountedSecretProviderError,
);
await rm(path.join(root, name));
await privateFile(path.join(root, name), Buffer.from([0xff]), 0o400);
await assert.rejects(
provider.resolve(authority()),
ClusterMountedSecretProviderError,
);
});
test('fails readiness for a missing or symlinked provider root', async (t) => {
const parent = await mkdtemp(path.join(os.tmpdir(), 'ql3-secret-root-'));
t.after(() => rm(parent, { recursive: true, force: true }));
const target = path.join(parent, 'target');
const link = path.join(parent, 'link');
await mkdir(target, { mode: 0o700 });
await symlink(target, link);
await assert.rejects(
createClusterMountedSecretProvider({ rootDirectory: link }),
ClusterMountedSecretProviderError,
);
await assert.rejects(
createClusterMountedSecretProvider({
rootDirectory: path.join(parent, 'missing'),
}),
ClusterMountedSecretProviderError,
);
});
@@ -0,0 +1,95 @@
const assert = require('node:assert/strict');
const { test } = require('node:test');
const {
CLUSTER_PLUGIN_PACKAGE_PROMPT_CATALOG_RESPONSE_SCHEMA,
createClusterControlPluginPackagePromptCatalogRoute,
} = require('@qinglong/cluster-control/prompt-routes');
function authorized(body = null) {
return {
request: {
requestId: '00000000-0000-4000-8000-000000000001',
method: 'GET',
path: '/api/v3/projects/project-1/packages/example/prompts',
query: {},
headers: {},
signal: new AbortController().signal,
body,
},
principal: {
subject: { type: 'api_app', id: 'app-1' },
authenticationId: 'credential-1',
authenticatedAtMs: 1,
expiresAtMs: 10_000,
assurance: 'service',
},
operationId: 'prompt.read',
permission: 'model.invoke',
projectId: 'project-1',
policyFence: { projectVersion: 3, bindingVersion: 7 },
};
}
test('returns a bounded content-free Prompt catalog', async () => {
let target;
const route = createClusterControlPluginPackagePromptCatalogRoute({
async inspect(projectId, packageName) {
target = { projectId, packageName };
return {
schema: CLUSTER_PLUGIN_PACKAGE_PROMPT_CATALOG_RESPONSE_SCHEMA,
projectId,
packageName,
found: true,
publicationState: 'active',
prompts: [{
id: 'summary',
name: 'Summary',
description: null,
parameters: [{ name: 'subject', description: null, required: true }],
}],
};
},
});
assert.equal(route.operationId, 'prompt.read');
assert.equal(route.permission, 'model.invoke');
const result = await route.handle(authorized(), {
projectId: 'project-1',
packageName: 'example',
});
assert.equal(result.statusCode, 200);
assert.deepEqual(target, { projectId: 'project-1', packageName: 'example' });
assert.equal(JSON.stringify(result).includes('template'), false);
});
test('rejects bodies and masks malformed or unavailable catalog state', async () => {
let calls = 0;
const route = createClusterControlPluginPackagePromptCatalogRoute({
async inspect(projectId, packageName) {
calls += 1;
return {
schema: CLUSTER_PLUGIN_PACKAGE_PROMPT_CATALOG_RESPONSE_SCHEMA,
projectId: 'another-project',
packageName,
found: false,
publicationState: null,
prompts: [],
};
},
});
assert.deepEqual(
await route.handle(authorized({ unexpected: true }), {
projectId: 'project-1',
packageName: 'example',
}),
{ statusCode: 400, body: { code: 'invalid_prompt_catalog_request' } },
);
assert.equal(calls, 0);
assert.deepEqual(
await route.handle(authorized(), {
projectId: 'project-1',
packageName: 'example',
}),
{ statusCode: 503, body: { code: 'prompt_catalog_unavailable' } },
);
});
@@ -0,0 +1,130 @@
const assert = require('node:assert/strict');
const { test } = require('node:test');
const {
createClusterControlPluginPackagePromptExecutionInspectionRoute,
} = require('@qinglong/cluster-control/prompt-routes');
function authorized(body = null) {
return {
request: {
requestId: '00000000-0000-4000-8000-000000000001',
method: 'GET',
path: '/api/v3/projects/project-1/packages/example/prompts/summary/executions/execution-request-1',
query: {},
headers: {},
signal: new AbortController().signal,
body,
},
principal: {
subject: { type: 'user', id: 'owner-1' },
authenticationId: 'api_credential:credential-1:1',
authenticatedAtMs: 1,
expiresAtMs: 10_000,
assurance: 'multi_factor',
},
operationId: 'prompt.execution.read',
permission: 'run.read',
projectId: 'project-1',
policyFence: { projectVersion: 3, bindingVersion: 7 },
};
}
const parameters = {
projectId: 'project-1',
packageName: 'example',
promptId: 'summary',
executionRequestId: 'execution-request-1',
};
function found(command) {
return {
schema: 'qinglong/plugin-package-prompt-execution-inspection@v1',
found: true,
projectId: command.projectId,
packageName: command.packageName,
promptId: command.promptId,
executionRequestId: command.executionRequestId,
execution: {
invocationId: 'invocation-1',
runId: '00000000-0000-4000-8000-000000000010',
stepRunId: 'step-1',
runStatus: 'succeeded',
runVersion: 5,
eventSequence: 5,
stepStatus: 'succeeded',
stepVersion: 3,
admittedAtMs: 1_000,
startedAtMs: 1_000,
finishedAtMs: 1_500,
finalizedAtMs: 1_500,
},
};
}
test('reads one content-free Prompt execution by caller-known requestId', async () => {
let command;
const route = createClusterControlPluginPackagePromptExecutionInspectionRoute(
{
async inspectAuthorized(value) {
command = value;
return found(value);
},
},
{
now: () => 2_000,
createEventId: () => '00000000-0000-4000-8000-000000000002',
},
);
assert.equal(route.operationId, 'prompt.execution.read');
assert.equal(route.permission, 'run.read');
const result = await route.handle(authorized(), parameters);
assert.equal(result.statusCode, 200);
assert.equal(command.executionRequestId, 'execution-request-1');
assert.equal(command.audit.operationId, 'prompt.execution.read');
assert.equal(JSON.stringify(result).includes('template'), false);
assert.equal(JSON.stringify(result).includes('parameter'), false);
});
test('masks cross-target absence and maps an authorization fence race', async () => {
let calls = 0;
const missing = createClusterControlPluginPackagePromptExecutionInspectionRoute(
{
async inspectAuthorized(command) {
calls += 1;
return { ...found(command), found: false, execution: null };
},
},
{
now: () => 2_000,
createEventId: () => '00000000-0000-4000-8000-000000000002',
},
);
assert.deepEqual(await missing.handle(authorized({ widened: true }), parameters), {
statusCode: 400,
body: { code: 'invalid_request_body' },
});
assert.equal(calls, 0);
assert.deepEqual(await missing.handle(authorized(), parameters), {
statusCode: 404,
body: { code: 'prompt_execution_not_found' },
});
const conflict = createClusterControlPluginPackagePromptExecutionInspectionRoute(
{
async inspectAuthorized() {
throw Object.assign(new Error('drift'), {
code: 'PLUGIN_PACKAGE_PROMPT_EXECUTION_INSPECTION_AUTHORIZATION_FENCE_CONFLICT',
});
},
},
{
now: () => 2_000,
createEventId: () => '00000000-0000-4000-8000-000000000003',
},
);
assert.deepEqual(await conflict.handle(authorized(), parameters), {
statusCode: 409,
body: { code: 'authorization_fence_conflict' },
});
});
@@ -0,0 +1,132 @@
const assert = require('node:assert/strict');
const { test } = require('node:test');
const {
createClusterControlPluginPackagePromptExecutionOutputReadRoute,
} = require('@qinglong/cluster-control/prompt-routes');
const parameters = Object.freeze({
projectId: 'project-1',
packageName: 'example',
promptId: 'summary',
executionRequestId: 'execution-request-1',
});
function authorized(body = null) {
return {
request: {
requestId: 'request-1',
method: 'GET',
path: '/unused',
query: {},
headers: {},
signal: new AbortController().signal,
body,
},
principal: {
subject: { type: 'user', id: 'owner-1' },
authenticationId: 'authentication-1',
authenticatedAtMs: 1,
expiresAtMs: 10_000,
assurance: 'multi_factor',
},
operationId: 'prompt.execution.output.read',
permission: 'artifact.read',
projectId: 'project-1',
policyFence: { projectVersion: 3, bindingVersion: 7 },
};
}
function available(command, overrides = {}) {
return {
schema: 'qinglong/plugin-package-prompt-execution-output-read-result@v1',
status: 'available',
projectId: command.projectId,
packageName: command.packageName,
promptId: command.promptId,
executionRequestId: command.executionRequestId,
reference: {
schema: 'qinglong/plugin-package-prompt-output-artifact-reference@v1',
artifactId: 'pao:0123456789abcdef0123456789abcdef',
projectId: command.projectId,
runId: '00000000-0000-4000-8000-000000000010',
stepRunId: 'step-1',
invocationId: 'invocation-1',
contentDigest: 'b'.repeat(64),
outputBytes: 14,
retentionPolicyDigest: 'c'.repeat(64),
retentionEligibleAtMs: 10_000,
keyId: 'key-1',
algorithm: 'aes-256-gcm',
artifactDigest: 'a'.repeat(64),
},
result: {
provider: 'provider-1',
model: 'model-1',
text: 'private output',
finishReason: 'stop',
usage: { inputTokens: 2, outputTokens: 3, totalTokens: 5 },
},
...overrides,
};
}
test('reads durable Prompt output by caller-known execution requestId', async () => {
let command;
const route = createClusterControlPluginPackagePromptExecutionOutputReadRoute({
async read(value) {
command = value;
return available(value);
},
});
assert.equal(route.operationId, 'prompt.execution.output.read');
assert.equal(route.permission, 'artifact.read');
const result = await route.handle(authorized(), parameters);
assert.equal(result.statusCode, 200);
assert.equal(
result.body.schema,
'qinglong/cluster-plugin-package-prompt-execution-output-read-response@v1',
);
assert.equal(result.body.result.text, 'private output');
assert.equal(command.executionRequestId, parameters.executionRequestId);
assert.equal(command.principal.subject.id, 'owner-1');
});
test('masks missing output and rejects malformed requests before capability', async () => {
let calls = 0;
const route = createClusterControlPluginPackagePromptExecutionOutputReadRoute({
async read(command) {
calls += 1;
return {
schema: 'qinglong/plugin-package-prompt-execution-output-read-result@v1',
status: 'not_found',
projectId: command.projectId,
packageName: command.packageName,
promptId: command.promptId,
executionRequestId: command.executionRequestId,
};
},
});
assert.deepEqual(await route.handle(authorized(), parameters), {
statusCode: 404,
body: { code: 'prompt_execution_output_not_found' },
});
assert.equal(calls, 1);
assert.equal(
(await route.handle(authorized({ widened: true }), parameters)).statusCode,
400,
);
assert.equal(calls, 1);
});
test('fails closed when capability widens or drifts from the exact target', async () => {
const route = createClusterControlPluginPackagePromptExecutionOutputReadRoute({
async read(command) {
return available(command, { packageName: 'another-package' });
},
});
assert.deepEqual(await route.handle(authorized(), parameters), {
statusCode: 503,
body: { code: 'prompt_execution_output_read_unavailable' },
});
});
@@ -0,0 +1,195 @@
const assert = require('node:assert/strict');
const { test } = require('node:test');
const {
CLUSTER_PLUGIN_PACKAGE_PROMPT_EXECUTION_REQUEST_SCHEMA,
CLUSTER_PLUGIN_PACKAGE_PROMPT_EXECUTION_RESPONSE_SCHEMA,
createClusterControlPluginPackagePromptExecutionRoute,
} = require('@qinglong/cluster-control/prompt-routes');
function authorized(body, overrides = {}) {
return {
request: {
requestId: '00000000-0000-4000-8000-000000000001',
method: 'POST',
path: '/api/v3/projects/project-1/packages/example/prompts/summary/executions',
query: {},
headers: {},
signal: new AbortController().signal,
body,
},
principal: {
subject: { type: 'api_app', id: 'app-1' },
authenticationId: 'credential-1',
authenticatedAtMs: 1,
expiresAtMs: 10_000,
assurance: 'service',
},
operationId: 'prompt.execute',
permission: 'model.invoke',
projectId: 'project-1',
policyFence: { projectVersion: 3, bindingVersion: 7 },
...overrides,
};
}
function body(overrides = {}) {
return {
schema: CLUSTER_PLUGIN_PACKAGE_PROMPT_EXECUTION_REQUEST_SCHEMA,
requestId: 'prompt-request-1',
traceId: 'trace-1',
parameters: { subject: 'private input' },
provider: 'openai-compatible',
model: 'model-a',
maxOutputTokens: 512,
temperature: 0.2,
timeoutMs: 5_000,
...overrides,
};
}
function result(status = 'executed', liveResult = { text: 'private output' }) {
return {
status,
admission: {
requestId: 'prompt-request-1',
invocationId: 'ppi:1',
runId: 'ppr:1',
stepRunId: 'pps:1',
},
finalization: { runStatus: 'succeeded' },
result: liveResult,
};
}
test('builds a bounded subject- and policy-fenced execution command', async () => {
let command;
const route = createClusterControlPluginPackagePromptExecutionRoute(
{
async execute(value) {
command = value;
return result();
},
},
{
now: () => 2_000,
maxExecutionMs: 10_000,
createEventId: () => '00000000-0000-4000-8000-000000000002',
},
);
const request = authorized(body());
const response = await route.handle(request, {
projectId: 'project-1',
packageName: 'example',
promptId: 'summary',
});
assert.equal(response.statusCode, 200);
assert.equal(response.body.schema, CLUSTER_PLUGIN_PACKAGE_PROMPT_EXECUTION_RESPONSE_SCHEMA);
assert.equal(response.body.replayed, false);
assert.equal(response.body.result.text, 'private output');
assert.deepEqual(command.principal, request.principal);
assert.equal(command.auditEventId, '00000000-0000-4000-8000-000000000002');
assert.deepEqual(command.policyFence, { projectVersion: 3, bindingVersion: 7 });
assert.equal(command.plannedAtMs, 2_000);
assert.equal(command.deadlineAtMs, 7_000);
assert.equal(command.signal, request.request.signal);
assert.equal('publication' in command, false);
assert.equal('publicationDigest' in command, false);
});
test('returns an explicit content-free replay receipt', async () => {
const route = createClusterControlPluginPackagePromptExecutionRoute({
async execute() {
return result('existing', null);
},
});
const response = await route.handle(authorized(body()), {
projectId: 'project-1',
packageName: 'example',
promptId: 'summary',
});
assert.equal(response.statusCode, 200);
assert.equal(response.body.replayed, true);
assert.equal(response.body.result, null);
});
test('strictly carries durable output intent and returns only its reference on replay', async () => {
let command;
const outputArtifact = {
schema: 'qinglong/plugin-package-prompt-output-artifact-reference@v1',
artifactId: 'pao:artifact-1',
artifactDigest: 'b'.repeat(64),
};
const route = createClusterControlPluginPackagePromptExecutionRoute({
async execute(value) {
command = value;
return { ...result('existing', null), outputArtifact };
},
});
const output = {
mode: 'durable_artifact',
retentionPolicy: {
revision: 'cluster-prompt-output-v1',
retentionMs: 86_400_000,
},
};
const response = await route.handle(authorized(body({ output })), {
projectId: 'project-1',
packageName: 'example',
promptId: 'summary',
});
assert.equal(response.statusCode, 200);
assert.deepEqual(command.output, output);
assert.equal(response.body.result, null);
assert.deepEqual(response.body.outputArtifact, outputArtifact);
});
test('rejects malformed or over-timeout bodies before the capability', async () => {
let calls = 0;
const route = createClusterControlPluginPackagePromptExecutionRoute(
{ async execute() { calls += 1; return result(); } },
{ maxExecutionMs: 1_000 },
);
for (const invalid of [
body({ timeoutMs: 1_001 }),
body({ publication: {} }),
body({ publicationDigest: 'a'.repeat(64) }),
body({ parameters: { bad: 7 } }),
body({ output: { mode: 'durable_artifact', retentionPolicy: {
revision: 'cluster-prompt-output-v1', retentionMs: 1,
} } }),
body({ output: { mode: 'live_only', unexpected: true } }),
]) {
const response = await route.handle(authorized(invalid), {
projectId: 'project-1',
packageName: 'example',
promptId: 'summary',
});
assert.equal(response.statusCode, 400);
assert.deepEqual(response.body, { code: 'invalid_prompt_execution_request' });
}
assert.equal(calls, 0);
});
test('maps internal errors to low-sensitive stable transport codes', async () => {
for (const [internal, statusCode, external] of [
['PLUGIN_PACKAGE_PROMPT_ADMISSION_NOT_ALLOWED', 409, 'prompt_execution_conflict'],
['MODEL_GATEWAY_BUSY', 429, 'prompt_execution_capacity_exceeded'],
['MODEL_POLICY_DENIED', 422, 'prompt_execution_policy_rejected'],
['MODEL_INVOCATION_DEADLINE_EXCEEDED', 504, 'prompt_execution_deadline_exceeded'],
['MODEL_PROVIDER_UNAVAILABLE', 503, 'prompt_execution_unavailable'],
]) {
const route = createClusterControlPluginPackagePromptExecutionRoute({
async execute() {
throw Object.assign(new Error('private provider detail'), { code: internal });
},
});
const response = await route.handle(authorized(body()), {
projectId: 'project-1',
packageName: 'example',
promptId: 'summary',
});
assert.equal(response.statusCode, statusCode, internal);
assert.deepEqual(response.body, { code: external });
assert.equal(JSON.stringify(response).includes('private provider detail'), false);
}
});
@@ -0,0 +1,128 @@
const assert = require('node:assert/strict');
const test = require('node:test');
const {
createClusterControlPluginPackagePromptOutputReadRoute,
} = require('@qinglong/cluster-control/prompt-routes');
const DIGEST = 'a'.repeat(64);
const CONTENT_DIGEST = 'b'.repeat(64);
const RETENTION_DIGEST = 'c'.repeat(64);
const ARTIFACT_ID = 'pao:1234';
function authorized(query = { artifact_digest: [DIGEST] }, body = null) {
return {
request: {
requestId: 'request-1',
method: 'GET',
path: '/unused',
query,
headers: {},
signal: new AbortController().signal,
body,
},
principal: {
subject: { type: 'user', id: 'user-1' },
authenticationId: 'auth-1',
authenticatedAtMs: 1,
expiresAtMs: 10_000,
assurance: 'multi_factor',
},
operationId: 'prompt.output.read',
permission: 'artifact.read',
projectId: 'project-1',
policyFence: { projectVersion: 1, bindingVersion: 1 },
};
}
function available(command, overrides = {}) {
return {
schema: 'qinglong/plugin-package-prompt-output-read-result@v1',
status: 'available',
reference: {
schema: 'qinglong/plugin-package-prompt-output-artifact-reference@v1',
artifactId: command.artifactId,
projectId: command.projectId,
runId: command.runId,
stepRunId: 'step-1',
invocationId: 'invocation-1',
contentDigest: CONTENT_DIGEST,
outputBytes: 14,
retentionPolicyDigest: RETENTION_DIGEST,
retentionEligibleAtMs: 10_000,
keyId: 'key-1',
algorithm: 'aes-256-gcm',
artifactDigest: command.artifactDigest,
},
result: {
provider: 'openai-compatible',
model: 'model-1',
text: 'durable output',
finishReason: 'stop',
usage: { inputTokens: 2, outputTokens: 3, totalTokens: 5 },
},
...overrides,
};
}
test('returns one bounded Prompt output after the reviewed read capability', async () => {
let command;
const route = createClusterControlPluginPackagePromptOutputReadRoute({
async read(value) {
command = value;
return available(value);
},
});
const result = await route.handle(authorized(), {
projectId: 'project-1',
runId: 'run-1',
artifactId: ARTIFACT_ID,
});
assert.equal(result.statusCode, 200);
assert.equal(result.body.schema,
'qinglong/cluster-plugin-package-prompt-output-read-response@v1');
assert.equal(result.body.result.text, 'durable output');
assert.equal(command.principal.subject.id, 'user-1');
assert.equal(command.artifactDigest, DIGEST);
});
test('masks product not-found and rejects malformed requests before capability', async () => {
let calls = 0;
const route = createClusterControlPluginPackagePromptOutputReadRoute({
async read() {
calls += 1;
return {
schema: 'qinglong/plugin-package-prompt-output-read-result@v1',
status: 'not_found',
};
},
});
assert.equal((await route.handle(authorized(), {
projectId: 'project-1', runId: 'run-1', artifactId: ARTIFACT_ID,
})).statusCode, 404);
assert.equal(calls, 1);
assert.equal((await route.handle(authorized({ artifact_digest: ['bad'] }), {
projectId: 'project-1', runId: 'run-1', artifactId: ARTIFACT_ID,
})).statusCode, 400);
assert.equal(calls, 1);
});
test('fails closed when capability widens or drifts from the requested identity', async () => {
const route = createClusterControlPluginPackagePromptOutputReadRoute({
async read(command) {
return available(command, {
reference: {
...available(command).reference,
projectId: 'project-other',
},
});
},
});
const result = await route.handle(authorized(), {
projectId: 'project-1', runId: 'run-1', artifactId: ARTIFACT_ID,
});
assert.equal(result.statusCode, 503);
assert.deepEqual(result.body, { code: 'prompt_output_read_unavailable' });
});
@@ -0,0 +1,819 @@
const assert = require('node:assert/strict');
const { test } = require('node:test');
const {
createInitialPluginPackageAutomationPublication,
} = require('@qinglong/runtime-core/plugin-package-automation-publication');
const {
createPluginPackageWorkflowAdmissionBundle,
} = require('@qinglong/runtime-core/plugin-package-workflow-execution-plan');
const {
pluginPackageTaskReconciliationFixture,
} = require('../../../test/contracts/pluginPackageTaskReconciliationRepositoryContract.cjs');
const {
createClusterPluginPackageWorkflowAdministrationCapability,
} = require('@qinglong/cluster-control/workflow-administration');
const {
createClusterControlPluginPackageWorkflowRoutes,
} = require('@qinglong/cluster-control/workflow-routes');
const IDS = Object.freeze({
planId: '123e4567-e89b-42d3-a456-426614174000',
runId: '123e4567-e89b-42d3-a456-426614174001',
collect: '123e4567-e89b-42d3-a456-426614174002',
summarize: '123e4567-e89b-42d3-a456-426614174003',
});
function productFixture() {
const value = pluginPackageTaskReconciliationFixture('cluster-product', {
workflows: [
{
schema: 'qinglong/plugin-package-workflow-resource@v1',
id: 'daily',
name: 'Daily workflow',
enabled: true,
steps: [
{ id: 'collect', task: 'alpha', needs: [] },
{ id: 'summarize', task: 'beta', needs: ['collect'] },
],
},
],
});
return {
...value,
publication: createInitialPluginPackageAutomationPublication(
value.revision,
value.registry,
2_000,
),
};
}
function principal(now = 3_000) {
return Object.freeze({
subject: { type: 'api_app', id: 'workflow-operator' },
authenticationId: 'api_credential:workflow-product:1',
authenticatedAtMs: now - 1,
expiresAtMs: now + 60_000,
assurance: 'service',
});
}
test('derives the cluster Workflow plan from current server publications and exactly replays it', async () => {
const value = productFixture();
let storedPlan = null;
let cancellationCommand;
let inspectionCommand;
let runListCommand;
let stepListCommand;
let runEventListCommand;
const admissions = [];
const capability = createClusterPluginPackageWorkflowAdministrationCapability(
{
async findCurrent(projectId, packageName) {
assert.equal(projectId, value.projectId);
assert.equal(packageName, value.packageName);
return value.publication;
},
},
{
async find(generationDigest) {
assert.equal(
generationDigest,
value.revision.generation.generationDigest,
);
return value.revision;
},
},
{
async findPlanByPlanId(planId) {
assert.equal(planId, IDS.planId);
return storedPlan;
},
async admitAuthorized(admission) {
admissions.push(admission);
const bundle = createPluginPackageWorkflowAdmissionBundle(
admission.plan,
);
const status = storedPlan ? 'existing' : 'created';
storedPlan = admission.plan;
return { status, receipt: bundle.receipt };
},
},
{
async inspectRunAuthorized(command) {
inspectionCommand = command;
return {
schema: 'qinglong/plugin-package-workflow-run-inspection@v1',
found: false,
projectId: command.projectId,
packageName: command.packageName,
workflowId: command.workflowId,
runId: command.runId,
run: null,
stepCount: null,
stepStatusCounts: null,
};
},
},
{
async listRunsAuthorized(command) {
runListCommand = command;
return {
schema: 'qinglong/plugin-package-workflow-run-list@v1',
projectId: command.projectId,
packageName: command.packageName,
workflowId: command.workflowId,
after: command.after,
runs: [],
truncated: false,
next: null,
};
},
},
{
async listStepRunsAuthorized(command) {
stepListCommand = command;
return {
schema: 'qinglong/plugin-package-workflow-step-run-list@v1',
found: false,
projectId: command.projectId,
packageName: command.packageName,
workflowId: command.workflowId,
runId: command.runId,
stepRuns: [],
truncated: false,
next: null,
};
},
},
{
async listRunEventsAuthorized(command) {
runEventListCommand = command;
return {
schema: 'qinglong/plugin-package-workflow-run-event-list@v1',
found: false,
projectId: command.projectId,
packageName: command.packageName,
workflowId: command.workflowId,
runId: command.runId,
afterSequence: command.afterSequence,
headSequence: null,
events: [],
truncated: false,
nextAfterSequence: null,
};
},
},
{
async requestUserCancellation(command) {
cancellationCommand = command;
return {
status: 'accepted',
projectId: command.projectId,
runId: command.runId,
runStatus: 'running',
runVersion: 4,
eventSequence: 4,
cancelRequestedAtMs: 3_100,
cancelReason: 'user',
};
},
},
value.registry,
);
const listed = await capability.inspect(value.projectId, value.packageName);
assert.equal(listed.found, true);
assert.deepEqual(listed.workflows[0].steps, [
{ id: 'collect', task: 'alpha', needs: [] },
{ id: 'summarize', task: 'beta', needs: ['collect'] },
]);
const command = {
projectId: value.projectId,
packageName: value.packageName,
workflowId: 'daily',
planId: IDS.planId,
runId: IDS.runId,
stepRunIds: { collect: IDS.collect, summarize: IDS.summarize },
principal: principal(),
policyFence: { projectVersion: 3, bindingVersion: 7 },
plannedAtMs: 3_000,
};
const created = await capability.start(command);
const replay = await capability.start({ ...command, plannedAtMs: 9_000 });
assert.equal(created.status, 'created');
assert.equal(replay.status, 'existing');
assert.equal(replay.plan.planDigest, created.plan.planDigest);
assert.equal(
created.plan.target.publicationDigest,
value.publication.publicationDigest,
);
assert.equal(admissions[0].audit.eventId, IDS.planId);
assert.equal(admissions[0].audit.requestId, IDS.planId);
assert.equal(
admissions[0].audit.authenticationId,
principal().authenticationId,
);
assert.equal(admissions[1].audit.occurredAtMs, created.plan.plannedAtMs);
assert.equal(
(
await capability.cancel({
projectId: value.projectId,
packageName: value.packageName,
workflowId: 'daily',
runId: IDS.runId,
mutationId: 'workflow-cancel-mutation-1',
eventId: '018f0000-0000-7000-8000-000000000091',
principal: principal(),
policyFence: { projectVersion: 3, bindingVersion: 7 },
})
).status,
'accepted',
);
assert.deepEqual(cancellationCommand.workflowTarget, {
packageName: value.packageName,
workflowId: 'daily',
});
const inspected = await capability.inspectRun({
projectId: value.projectId,
packageName: value.packageName,
workflowId: 'daily',
runId: IDS.runId,
requestId: 'workflow-run-read-request-1',
auditEventId: '123e4567-e89b-42d3-a456-426614174093',
principal: principal(),
policyFence: { projectVersion: 3, bindingVersion: 7 },
observedAtMs: 3_200,
});
assert.equal(inspected.found, false);
assert.equal(inspectionCommand.audit.operationId, 'workflow.run.read');
assert.equal(
inspectionCommand.audit.requestId,
'workflow-run-read-request-1',
);
assert.deepEqual(inspectionCommand.fence, {
projectVersion: 3,
bindingVersion: 7,
});
const runPage = await capability.listRuns({
projectId: value.projectId,
packageName: value.packageName,
workflowId: 'daily',
limit: 16,
after: { admittedAtMs: 3_100, runId: IDS.runId },
requestId: 'workflow-run-list-request-1',
auditEventId: '123e4567-e89b-42d3-a456-426614174096',
principal: principal(),
policyFence: { projectVersion: 3, bindingVersion: 7 },
observedAtMs: 3_250,
});
assert.deepEqual(runPage.runs, []);
assert.equal(runListCommand.audit.operationId, 'workflow.run.list');
assert.equal(runListCommand.limit, 16);
assert.deepEqual(runListCommand.after, {
admittedAtMs: 3_100,
runId: IDS.runId,
});
const stepPage = await capability.listStepRuns({
projectId: value.projectId,
packageName: value.packageName,
workflowId: 'daily',
runId: IDS.runId,
limit: 16,
after: { stepKey: 'collect', id: IDS.collect },
requestId: 'workflow-step-list-request-1',
auditEventId: '123e4567-e89b-42d3-a456-426614174094',
principal: principal(),
policyFence: { projectVersion: 3, bindingVersion: 7 },
observedAtMs: 3_300,
});
assert.equal(stepPage.found, false);
assert.equal(stepListCommand.audit.operationId, 'workflow.step.list');
assert.equal(stepListCommand.limit, 16);
assert.deepEqual(stepListCommand.after, {
stepKey: 'collect',
id: IDS.collect,
});
const eventPage = await capability.listRunEvents({
projectId: value.projectId,
packageName: value.packageName,
workflowId: 'daily',
runId: IDS.runId,
limit: 16,
afterSequence: 2,
requestId: 'workflow-event-list-request-1',
auditEventId: '123e4567-e89b-42d3-a456-426614174095',
principal: principal(),
policyFence: { projectVersion: 3, bindingVersion: 7 },
observedAtMs: 3_400,
});
assert.equal(eventPage.found, false);
assert.equal(runEventListCommand.audit.operationId, 'workflow.event.list');
assert.equal(runEventListCommand.limit, 16);
assert.equal(runEventListCommand.afterSequence, 2);
});
test('publishes strict authenticated list and content-free start routes', async () => {
let startCommand;
let cancellationError;
const routes = createClusterControlPluginPackageWorkflowRoutes(
{
async inspect() {
return { found: false, publicationState: null, workflows: [] };
},
async inspectRun(command) {
return {
schema: 'qinglong/plugin-package-workflow-run-inspection@v1',
found: true,
projectId: command.projectId,
packageName: command.packageName,
workflowId: command.workflowId,
runId: command.runId,
run: {
status: 'running',
version: 4,
eventSequence: 4,
createdAtMs: 3_000,
queuedAtMs: 3_010,
startedAtMs: 3_020,
finishedAtMs: null,
cancelRequestedAtMs: null,
cancelReason: null,
},
stepCount: 1,
stepStatusCounts: {
pending: 0,
ready: 0,
waiting_approval: 0,
running: 1,
lost: 0,
succeeded: 0,
failed: 0,
skipped: 0,
cancelled: 0,
timed_out: 0,
},
};
},
async listRuns(command) {
return {
schema: 'qinglong/plugin-package-workflow-run-list@v1',
projectId: command.projectId,
packageName: command.packageName,
workflowId: command.workflowId,
after: command.after,
runs: [
{
runId: IDS.runId,
status: 'running',
version: 4,
eventSequence: 4,
stepCount: 2,
admittedAtMs: 3_000,
queuedAtMs: 3_010,
startedAtMs: 3_020,
finishedAtMs: null,
cancelRequestedAtMs: null,
cancelReason: null,
},
],
truncated: true,
next: { admittedAtMs: 3_000, runId: IDS.runId },
};
},
async listStepRuns(command) {
return {
schema: 'qinglong/plugin-package-workflow-step-run-list@v1',
found: true,
projectId: command.projectId,
packageName: command.packageName,
workflowId: command.workflowId,
runId: command.runId,
stepRuns: [
{
id: IDS.collect,
parentStepRunId: null,
stepKey: 'collect',
kind: 'task',
required: true,
status: 'running',
version: 2,
attemptCount: 1,
readyAtMs: 3_010,
startedAtMs: 3_020,
finishedAtMs: null,
resultCode: null,
createdAtMs: 3_000,
updatedAtMs: 3_020,
},
],
truncated: true,
next: { stepKey: 'collect', id: IDS.collect },
};
},
async listRunEvents(command) {
return {
schema: 'qinglong/plugin-package-workflow-run-event-list@v1',
found: true,
projectId: command.projectId,
packageName: command.packageName,
workflowId: command.workflowId,
runId: command.runId,
afterSequence: command.afterSequence,
headSequence: 4,
events: [
{
id: '123e4567-e89b-42d3-a456-426614174004',
sequence: 3,
type: 'workflow.task_attempt.running',
stepRunId: IDS.collect,
createdAtMs: 3_020,
},
],
truncated: true,
nextAfterSequence: 3,
};
},
async start(command) {
startCommand = command;
return {
status: 'created',
plan: { planId: command.planId, runId: command.runId },
receipt: { receiptDigest: 'a'.repeat(64) },
};
},
async cancel(command) {
if (cancellationError) {
throw cancellationError;
}
return {
status: 'accepted',
projectId: command.projectId,
runId: command.runId,
runStatus: 'running',
runVersion: 4,
eventSequence: 4,
cancelRequestedAtMs: 3_100,
cancelReason: 'user',
};
},
},
() => 3_000,
() => '123e4567-e89b-42d3-a456-426614174092',
);
const start = routes.find(
({ operationId }) => operationId === 'workflow.start',
);
assert.ok(start);
const authorized = {
request: {
requestId: 'transport-request-1',
body: {
schema: 'qinglong/cluster-plugin-package-workflow-start-request@v1',
planId: IDS.planId,
runId: IDS.runId,
stepRunIds: { collect: IDS.collect },
},
signal: new AbortController().signal,
},
principal: principal(),
operationId: 'workflow.start',
permission: 'run.start',
projectId: 'project-1',
policyFence: { projectVersion: 3, bindingVersion: 7 },
};
const result = await start.handle(authorized, {
packageName: 'example',
workflowId: 'daily',
});
assert.equal(result.statusCode, 201);
assert.deepEqual(Object.keys(result.body).sort(), [
'planId',
'receiptDigest',
'replayed',
'runId',
'schema',
'status',
]);
assert.equal(startCommand.principal.subject.id, 'workflow-operator');
assert.equal(startCommand.plannedAtMs, 3_000);
const inspectRun = routes.find(
({ operationId }) => operationId === 'workflow.run.read',
);
assert.ok(inspectRun);
assert.equal(inspectRun.permission, 'run.read');
const inspected = await inspectRun.handle(
{
...authorized,
operationId: 'workflow.run.read',
permission: 'run.read',
request: { ...authorized.request, body: null },
},
{
packageName: 'example',
workflowId: 'daily',
runId: IDS.runId,
},
);
assert.equal(inspected.statusCode, 200);
assert.equal(
inspected.body.schema,
'qinglong/plugin-package-workflow-run-inspection@v1',
);
assert.deepEqual(Object.keys(inspected.body.run).sort(), [
'cancelReason',
'cancelRequestedAtMs',
'createdAtMs',
'eventSequence',
'finishedAtMs',
'queuedAtMs',
'startedAtMs',
'status',
'version',
]);
const listRuns = routes.find(
({ operationId }) => operationId === 'workflow.run.list',
);
assert.ok(listRuns);
assert.equal(listRuns.permission, 'run.read');
assert.deepEqual(listRuns.allowedQuery, [
'after_admitted_at_ms',
'after_run_id',
'limit',
]);
const listedRuns = await listRuns.handle(
{
...authorized,
operationId: 'workflow.run.list',
permission: 'run.read',
request: {
...authorized.request,
body: null,
query: {
limit: ['1'],
after_admitted_at_ms: ['3100'],
after_run_id: [IDS.runId],
},
},
},
{ packageName: 'example', workflowId: 'daily' },
);
assert.equal(listedRuns.statusCode, 200);
assert.equal(
listedRuns.body.schema,
'qinglong/plugin-package-workflow-run-list@v1',
);
assert.deepEqual(Object.keys(listedRuns.body.runs[0]).sort(), [
'admittedAtMs',
'cancelReason',
'cancelRequestedAtMs',
'eventSequence',
'finishedAtMs',
'queuedAtMs',
'runId',
'startedAtMs',
'status',
'stepCount',
'version',
]);
const invalidRunCursor = await listRuns.handle(
{
...authorized,
request: {
...authorized.request,
body: null,
query: { after_admitted_at_ms: ['3100'] },
},
},
{ packageName: 'example', workflowId: 'daily' },
);
assert.equal(invalidRunCursor.statusCode, 400);
const listSteps = routes.find(
({ operationId }) => operationId === 'workflow.step.list',
);
assert.ok(listSteps);
assert.equal(listSteps.permission, 'run.read');
assert.deepEqual(listSteps.allowedQuery, [
'after_step_key',
'after_step_run_id',
'limit',
]);
const listedSteps = await listSteps.handle(
{
...authorized,
operationId: 'workflow.step.list',
permission: 'run.read',
request: {
...authorized.request,
body: null,
query: {
limit: ['1'],
after_step_key: ['collect'],
after_step_run_id: [IDS.collect],
},
},
},
{
packageName: 'example',
workflowId: 'daily',
runId: IDS.runId,
},
);
assert.equal(listedSteps.statusCode, 200);
assert.equal(
listedSteps.body.schema,
'qinglong/plugin-package-workflow-step-run-list@v1',
);
assert.deepEqual(Object.keys(listedSteps.body.stepRuns[0]).sort(), [
'attemptCount',
'createdAtMs',
'finishedAtMs',
'id',
'kind',
'parentStepRunId',
'readyAtMs',
'required',
'resultCode',
'startedAtMs',
'status',
'stepKey',
'updatedAtMs',
'version',
]);
const invalidStepCursor = await listSteps.handle(
{
...authorized,
request: {
...authorized.request,
body: null,
query: { after_step_key: ['collect'] },
},
},
{
packageName: 'example',
workflowId: 'daily',
runId: IDS.runId,
},
);
assert.equal(invalidStepCursor.statusCode, 400);
const listEvents = routes.find(
({ operationId }) => operationId === 'workflow.event.list',
);
assert.ok(listEvents);
assert.equal(listEvents.permission, 'run.read');
assert.deepEqual(listEvents.allowedQuery, ['after_sequence', 'limit']);
const listedEvents = await listEvents.handle(
{
...authorized,
operationId: 'workflow.event.list',
permission: 'run.read',
request: {
...authorized.request,
body: null,
query: { limit: ['1'], after_sequence: ['2'] },
},
},
{
packageName: 'example',
workflowId: 'daily',
runId: IDS.runId,
},
);
assert.equal(listedEvents.statusCode, 200);
assert.equal(
listedEvents.body.schema,
'qinglong/plugin-package-workflow-run-event-list@v1',
);
assert.deepEqual(Object.keys(listedEvents.body.events[0]).sort(), [
'createdAtMs',
'id',
'sequence',
'stepRunId',
'type',
]);
const invalidEventCursor = await listEvents.handle(
{
...authorized,
request: {
...authorized.request,
body: null,
query: { after_sequence: ['02'] },
},
},
{
packageName: 'example',
workflowId: 'daily',
runId: IDS.runId,
},
);
assert.equal(invalidEventCursor.statusCode, 400);
const invalid = await start.handle(
{
...authorized,
request: {
...authorized.request,
body: { ...authorized.request.body, extra: true },
},
},
{ packageName: 'example', workflowId: 'daily' },
);
assert.equal(invalid.statusCode, 400);
const cancellation = routes.find(
({ operationId }) => operationId === 'workflow.cancel',
);
assert.ok(cancellation);
const cancelled = await cancellation.handle(
{
...authorized,
operationId: 'workflow.cancel',
permission: 'run.stop',
request: {
...authorized.request,
body: {
schema: 'qinglong/run-cancellation@v1',
mutationId: 'workflow-cancel-mutation-1',
},
},
},
{
packageName: 'example',
workflowId: 'daily',
runId: IDS.runId,
},
);
assert.equal(cancelled.statusCode, 202);
assert.equal(cancelled.body.status, 'accepted');
assert.deepEqual(
Object.keys(cancelled.body).sort(),
[
'cancelReason',
'cancelRequestedAtMs',
'eventSequence',
'projectId',
'runId',
'runStatus',
'runVersion',
'schema',
'status',
].sort(),
);
const invalidCancellation = await cancellation.handle(
{
...authorized,
operationId: 'workflow.cancel',
permission: 'run.stop',
request: {
...authorized.request,
body: {
schema: 'qinglong/run-cancellation@v1',
mutationId: 'workflow-cancel-mutation-1',
reason: 'shutdown',
},
},
},
{
packageName: 'example',
workflowId: 'daily',
runId: IDS.runId,
},
);
assert.equal(invalidCancellation.statusCode, 400);
cancellationError = Object.assign(new Error('private adapter detail'), {
code: 'CLUSTER_RUN_CANCELLATION_FENCE_REJECTED',
reason: 'private_adapter_detail',
});
const closedCancellationFailure = await cancellation.handle(
{
...authorized,
operationId: 'workflow.cancel',
permission: 'run.stop',
request: {
...authorized.request,
body: {
schema: 'qinglong/run-cancellation@v1',
mutationId: 'workflow-cancel-mutation-2',
},
},
},
{
packageName: 'example',
workflowId: 'daily',
runId: IDS.runId,
},
);
assert.equal(closedCancellationFailure.statusCode, 409);
assert.deepEqual(closedCancellationFailure.body, {
code: 'workflow_cancellation_fence_rejected',
reason: 'state_mismatch',
});
});
File diff suppressed because it is too large. Load diff
@@ -0,0 +1,362 @@
const assert = require('node:assert/strict');
const { test } = require('node:test');
const {
ClusterControlProcessError,
runProductionClusterControlProcess,
} = require('@qinglong/cluster-control/process');
const BASE_ENV = Object.freeze({
QL3_CLUSTER_CONTROL_ENABLED: 'true',
QL_DEPLOYMENT_PROFILE: 'cluster-control',
QL3_CLUSTER_REPLICA_ID: 'cluster-control-0',
QL3_POSTGRES_RUNTIME_URL:
'postgresql://ql3_runtime:do-not-log@postgres-rw.internal:5432/qinglong',
QL3_POSTGRES_TLS_SERVERNAME: 'postgres-rw.internal',
QL3_API_CREDENTIAL_PEPPER: 'A'.repeat(43),
});
const NEVER_UNAVAILABLE = new Promise(() => {});
function signalSource(events, signal = 'SIGTERM') {
return {
subscribe(listener) {
events.push('subscribe');
queueMicrotask(() => listener(signal));
return () => events.push('unsubscribe');
},
};
}
test('runs one production replica and drains it on the first signal', async () => {
const events = [];
const facts = [];
const result = await runProductionClusterControlProcess({
environment: BASE_ENV,
signals: signalSource(events),
emit(record) {
facts.push(record);
},
async start(options) {
events.push('start');
assert.equal(options.config.enabled, true);
assert.equal(options.config.profile, 'cluster-control');
assert.equal(options.recovery.ownerId, 'cluster-control-0');
assert.equal(options.scheduler.ownerId, 'cluster-control-0');
await options.audit({
state: 'active',
contractName: 'qinglong-cluster-control',
contractVersion: 16,
serverMajor: 18,
migrationCount: 16,
});
options.scheduler.onDiagnostic(
Object.assign(new Error('must-not-be-logged'), {
code: 'ECONNRESET',
}),
);
return {
status: 'active',
address: { host: '0.0.0.0', port: 5800 },
evidence: {
contractName: 'qinglong-cluster-control',
contractVersion: 16,
serverMajor: 18,
migrationIds: [],
},
recovery: { safe: true, remaining: 0, failed: 0 },
unavailable: NEVER_UNAVAILABLE,
availabilityStatus: () => 'ready',
async stop() {
events.push('stop');
return 'stopped';
},
};
},
});
assert.equal(result, 'stopped');
assert.deepEqual(events, ['subscribe', 'start', 'stop', 'unsubscribe']);
assert.equal(facts.some((fact) => fact.event === 'activation'), true);
assert.equal(facts.some((fact) => fact.event === 'listening'), true);
assert.equal(
facts.some(
(fact) =>
fact.event === 'shutdown_requested' && fact.signal === 'SIGTERM',
),
true,
);
assert.equal(facts.at(-1).event, 'stopped');
assert.equal(facts.at(-1).stopResult, 'stopped');
const serialized = JSON.stringify(facts);
assert.equal(serialized.includes('do-not-log'), false);
assert.equal(serialized.includes(BASE_ENV.QL3_API_CREDENTIAL_PEPPER), false);
assert.equal(serialized.includes('must-not-be-logged'), false);
assert.equal(serialized.includes('ECONNRESET'), true);
});
test('fails closed before startup for a disabled profile or invalid replica id', async () => {
let starts = 0;
for (const environment of [
{
QL3_CLUSTER_CONTROL_ENABLED: 'false',
QL_DEPLOYMENT_PROFILE: 'standalone',
},
{ ...BASE_ENV, QL3_CLUSTER_REPLICA_ID: 'unsafe replica' },
]) {
await assert.rejects(
runProductionClusterControlProcess({
environment,
signals: { subscribe() { return () => {}; } },
emit() {},
async start() {
starts += 1;
throw new Error('must not start');
},
}),
ClusterControlProcessError,
);
}
assert.equal(starts, 0);
});
test('propagates timed-out drain and always releases signal ownership', async () => {
const events = [];
const result = await runProductionClusterControlProcess({
environment: BASE_ENV,
signals: signalSource(events, 'SIGINT'),
emit() {},
async start() {
return {
status: 'active',
address: { host: '127.0.0.1', port: 5800 },
evidence: {
contractName: 'qinglong-cluster-control',
contractVersion: 16,
serverMajor: 18,
migrationIds: [],
},
recovery: { safe: true, remaining: 0, failed: 0 },
unavailable: NEVER_UNAVAILABLE,
availabilityStatus: () => 'ready',
async stop() {
events.push('stop');
return 'timed_out';
},
};
},
});
assert.equal(result, 'timed_out');
assert.deepEqual(events, ['subscribe', 'stop', 'unsubscribe']);
});
test('starts the optional Worker listener and closes its lazy Artifact binding', async () => {
const events = [];
const facts = [];
const artifactStore = {
async put() {},
async inspect() {},
};
const environment = {
...BASE_ENV,
QL3_WORKER_INGRESS_ENABLED: 'true',
QL3_POSTGRES_WORKER_INGRESS_URL:
'postgresql://ql3_worker_ingress:secret@postgres-rw.internal:5432/qinglong',
QL3_WORKER_INGRESS_POSTGRES_TLS_SERVERNAME: 'postgres-rw.internal',
QL3_WORKER_CREDENTIAL_PEPPER: 'A'.repeat(43),
QL3_WORKER_INGRESS_TLS_PRIVATE_KEY_FILE: '/run/worker/tls.key',
QL3_WORKER_INGRESS_TLS_CERTIFICATE_FILE: '/run/worker/tls.crt',
QL3_WORKER_INGRESS_TLS_CLIENT_CA_FILE: '/run/worker/client-ca.crt',
QL3_WORKER_ARTIFACT_S3_BUCKET: 'qinglong-worker-artifacts',
QL3_WORKER_ARTIFACT_S3_REGION: 'us-east-1',
};
const result = await runProductionClusterControlProcess({
environment,
signals: signalSource(events),
emit(record) {
facts.push(record);
},
async createWorkerArtifactBinding(config) {
events.push(`artifact:${config.bucket}:${config.region}`);
return {
store: artifactStore,
async close() {
events.push('close-artifact');
},
};
},
async start(options) {
events.push('start');
assert.equal(options.workerIngress.config.enabled, true);
assert.equal(options.workerIngress.artifactStore, artifactStore);
return {
status: 'active',
address: { host: '0.0.0.0', port: 5800 },
evidence: {
contractName: 'qinglong-cluster-control',
contractVersion: 16,
serverMajor: 18,
migrationIds: [],
},
recovery: { safe: true, remaining: 0, failed: 0 },
unavailable: NEVER_UNAVAILABLE,
availabilityStatus: () => 'ready',
async stop() {
events.push('stop');
return 'stopped';
},
};
},
});
assert.equal(result, 'stopped');
assert.deepEqual(events, [
'subscribe',
'artifact:qinglong-worker-artifacts:us-east-1',
'start',
'stop',
'unsubscribe',
'close-artifact',
]);
assert.equal(
facts.some((fact) => fact.event === 'worker_ingress_listening'),
true,
);
});
test('creates the configured mounted Secret provider before Worker activation', async () => {
const events = [];
const artifactStore = {
async put() {},
async inspect() {},
};
const provider = { async resolve() {} };
const result = await runProductionClusterControlProcess({
environment: {
...BASE_ENV,
QL3_WORKER_INGRESS_ENABLED: 'true',
QL3_POSTGRES_WORKER_INGRESS_URL:
'postgresql://ql3_worker_ingress:secret@postgres-rw.internal:5432/qinglong',
QL3_WORKER_INGRESS_POSTGRES_TLS_SERVERNAME: 'postgres-rw.internal',
QL3_WORKER_CREDENTIAL_PEPPER: 'A'.repeat(43),
QL3_WORKER_INGRESS_TLS_PRIVATE_KEY_FILE: '/run/worker/tls.key',
QL3_WORKER_INGRESS_TLS_CERTIFICATE_FILE: '/run/worker/tls.crt',
QL3_WORKER_INGRESS_TLS_CLIENT_CA_FILE: '/run/worker/client-ca.crt',
QL3_WORKER_ARTIFACT_S3_BUCKET: 'qinglong-worker-artifacts',
QL3_WORKER_ARTIFACT_S3_REGION: 'us-east-1',
QL3_WORKER_SECRET_PROVIDER: 'mounted-files',
QL3_WORKER_SECRET_ROOT_DIRECTORY: '/run/worker/values',
},
signals: signalSource(events),
emit() {},
async createWorkerArtifactBinding() {
events.push('artifact');
return {
store: artifactStore,
async close() {
events.push('close-artifact');
},
};
},
async createWorkerSecretProvider(config) {
events.push(`secret:${config.provider}:${config.rootDirectory}`);
return provider;
},
async start(options) {
events.push('start');
assert.equal(options.workerIngress.secretProvider, provider);
return {
status: 'active',
address: { host: '0.0.0.0', port: 5800 },
evidence: {
contractName: 'qinglong-cluster-control',
contractVersion: 16,
serverMajor: 18,
migrationIds: [],
},
recovery: { safe: true, remaining: 0, failed: 0 },
unavailable: NEVER_UNAVAILABLE,
availabilityStatus: () => 'ready',
async stop() {
events.push('stop');
return 'stopped';
},
};
},
});
assert.equal(result, 'stopped');
assert.deepEqual(events, [
'subscribe',
'artifact',
'secret:mounted-files:/run/worker/values',
'start',
'stop',
'unsubscribe',
'close-artifact',
]);
});
test('fails the process after a database fence drains the active application', async () => {
const events = [];
const facts = [];
let reportUnavailable;
const unavailable = new Promise((resolve) => {
reportUnavailable = resolve;
});
const running = runProductionClusterControlProcess({
environment: BASE_ENV,
signals: {
subscribe() {
events.push('subscribe');
return () => events.push('unsubscribe');
},
},
emit(record) {
facts.push(record);
},
async start() {
queueMicrotask(() =>
reportUnavailable(
Object.assign(new Error('must-not-escape-database-detail'), {
code: '57P01',
}),
),
);
return {
status: 'active',
address: { host: '127.0.0.1', port: 5800 },
evidence: {
contractName: 'qinglong-cluster-control',
contractVersion: 52,
serverMajor: 18,
migrationIds: [],
},
recovery: { safe: true, remaining: 0, failed: 0 },
unavailable,
availabilityStatus: () => 'unavailable',
async stop() {
events.push('stop');
return 'stopped';
},
};
},
});
await assert.rejects(
running,
(error) => error?.code === 'CLUSTER_CONTROL_DATABASE_UNAVAILABLE',
);
assert.deepEqual(events, ['subscribe', 'stop', 'unsubscribe']);
assert.equal(
facts.some(
({ event, diagnostic }) =>
event === 'database_unavailable' &&
diagnostic?.scope === 'database' &&
diagnostic?.code === '57P01',
),
true,
);
assert.equal(facts.some(({ event }) => event === 'shutdown_requested'), false);
assert.equal(facts.at(-1).event, 'stopped');
assert.equal(
JSON.stringify(facts).includes('must-not-escape-database-detail'),
false,
);
});
@@ -0,0 +1,896 @@
const assert = require('node:assert/strict');
const { test } = require('node:test');
const {
PRODUCTION_CLUSTER_CONTROL_ROUTE_OPERATIONS,
PRODUCTION_CLUSTER_CONTROL_OPTIONAL_ROUTE_OPERATIONS,
createProductionClusterControlApplicationStack,
startProductionClusterControlApplication,
} = require('@qinglong/cluster-control/production');
const {
createTaskDefinitionRecord,
} = require('@qinglong/runtime-core/task-definition');
const EVENT_ID = '123e4567-e89b-42d3-a456-426614174092';
function metadata(path, method = 'GET', body = null, query = {}) {
return {
method,
path,
query,
headers: Object.freeze({ authorization: 'Bearer test' }),
remoteAddress: '127.0.0.1',
requestId: 'request-production-1',
signal: new AbortController().signal,
body,
};
}
function fixture(overrides = {}) {
const events = [];
const currentTask = createTaskDefinitionRecord(
{
projectId: 'project-1',
taskId: 'task-1',
expectedRevision: null,
mutationId: '123e4567-e89b-42d3-a456-426614174093',
name: 'Task 1',
description: 'private',
kind: 'command',
spec: {
schema: 'qinglong/command@v1',
config: { command: { kind: 'shell', command: 'private' } },
},
labels: { private: 'value' },
enabled: true,
occurredAtMs: 20,
},
10,
);
const input = {
evidence: {
contractName: 'qinglong-cluster-control',
contractVersion: 14,
serverMajor: 16,
migrationIds: [],
},
authenticator: {
authenticate() {
events.push('authenticate');
const now = Date.now();
return {
subject: { type: 'api_app', id: 'app-production' },
authenticationId: 'credential-production',
authenticatedAtMs: now - 1_000,
expiresAtMs: now + 60_000,
assurance: 'service',
};
},
},
policies: {
async resolve() {
events.push('authorize');
return {
project: {
id: 'project-1',
name: 'Production Project',
slug: 'production-project',
status: 'active',
version: 3,
createdAtMs: 1,
updatedAtMs: 2,
},
binding: {
projectId: 'project-1',
subject: { type: 'api_app', id: 'app-production' },
state: 'active',
role: 'owner',
version: 7,
mutationId: 'binding-production-1',
changedBy: { type: 'system', id: 'bootstrap' },
createdAtMs: 1,
},
};
},
},
runs: {
async findRunById(runId) {
events.push(`read:${runId}`);
return {
id: runId,
projectId: 'project-1',
taskId: 'task-1',
taskRevision: 'revision-1',
status: 'queued',
version: 2,
eventSequence: 1,
priority: 0,
executionOrigin: 'scheduled_system',
executionOwner: 'runtime',
createdAtMs: 1,
queuedAtMs: 2,
};
},
async listRunsByProject(query) {
events.push(`list:${query.projectId}:${query.limit}`);
return [
{
id: 'run-1',
projectId: query.projectId,
taskId: 'task-1',
taskRevision: 'revision-1',
status: 'queued',
version: 2,
eventSequence: 1,
priority: 0,
executionOrigin: 'scheduled_system',
executionOwner: 'runtime',
createdAtMs: 1,
queuedAtMs: 2,
},
];
},
async listEvents(runId, input) {
events.push(`events:${runId}:${input.afterSequence}:${input.limit}`);
return [
{
id: 'event-1',
runId,
sequence: 1,
type: 'run.created',
actorType: 'system',
payload: { secret: 'must-not-cross-projection' },
createdAtMs: 2,
},
];
},
},
trustedToolStorage: {
stepRuns: {
async listByRun() {
events.push('steps');
return { stepRuns: [], truncated: false };
},
},
},
runCancellation: {
async requestUserCancellation(command) {
events.push(`cancel:${command.runId}:${command.eventId}`);
return {
status: 'accepted',
projectId: command.projectId,
runId: command.runId,
cancelReason: 'user',
cancelRequestedAtMs: 20,
runStatus: 'queued',
runVersion: 3,
eventSequence: 2,
};
},
},
taskStart: {
async startTask(command) {
events.push(`task-start:${command.taskId}:${command.mutationId}`);
return {
status: 'accepted',
projectId: command.projectId,
taskId: command.taskId,
taskRevision: command.expectedRevision,
taskContentDigest: command.expectedContentDigest,
runId: command.runId,
attemptId: command.attemptId,
runStatus: 'queued',
runVersion: 2,
eventSequence: 2,
executorType: 'remote_worker',
executionRevisionDigest: 'f'.repeat(64),
createdAtMs: 20,
};
},
},
taskDefinitions: {
async findCurrentTaskDefinition(projectId, taskId) {
events.push(`task-get:${projectId}:${taskId}`);
return projectId === currentTask.projectId && taskId === currentTask.taskId
? currentTask
: null;
},
async listTaskDefinitions(query) {
events.push(`task-list:${query.projectId}:${query.limit}`);
return {
definitions: [currentTask],
truncated: false,
};
},
},
taskExecutionRevisions: {},
triggers: {},
schedules: {},
securityAudit: {
record(record) {
events.push(`audit:${record.operationId}:${record.outcome}`);
},
},
workflowAdministration: {
async inspect(projectId, packageName) {
events.push(`workflow-read:${projectId}:${packageName}`);
return { found: false, publicationState: null, workflows: [] };
},
async inspectRun(command) {
events.push(
`workflow-run-read:${command.packageName}:${command.workflowId}:${command.runId}`,
);
return {
schema: 'qinglong/plugin-package-workflow-run-inspection@v1',
found: false,
projectId: command.projectId,
packageName: command.packageName,
workflowId: command.workflowId,
runId: command.runId,
run: null,
stepCount: null,
stepStatusCounts: null,
};
},
async listRuns(command) {
events.push(
`workflow-run-list:${command.packageName}:${command.workflowId}:${command.limit}`,
);
return {
schema: 'qinglong/plugin-package-workflow-run-list@v1',
projectId: command.projectId,
packageName: command.packageName,
workflowId: command.workflowId,
after: command.after,
runs: [],
truncated: false,
next: null,
};
},
async listStepRuns(command) {
events.push(
`workflow-step-list:${command.packageName}:${command.workflowId}:${command.runId}:${command.limit}`,
);
return {
schema: 'qinglong/plugin-package-workflow-step-run-list@v1',
found: false,
projectId: command.projectId,
packageName: command.packageName,
workflowId: command.workflowId,
runId: command.runId,
stepRuns: [],
truncated: false,
next: null,
};
},
async listRunEvents(command) {
events.push(
`workflow-event-list:${command.packageName}:${command.workflowId}:${command.runId}:${command.limit}:${command.afterSequence}`,
);
return {
schema: 'qinglong/plugin-package-workflow-run-event-list@v1',
found: false,
projectId: command.projectId,
packageName: command.packageName,
workflowId: command.workflowId,
runId: command.runId,
afterSequence: command.afterSequence,
headSequence: null,
events: [],
truncated: false,
nextAfterSequence: null,
};
},
async start(command) {
events.push(`workflow-start:${command.workflowId}`);
return {
status: 'created',
plan: { planId: command.planId, runId: command.runId },
receipt: { receiptDigest: 'f'.repeat(64) },
};
},
async cancel(command) {
events.push(
`workflow-cancel:${command.packageName}:${command.workflowId}:${command.runId}:${command.eventId}`,
);
return {
status: 'accepted',
projectId: command.projectId,
runId: command.runId,
runStatus: 'running',
runVersion: 4,
eventSequence: 4,
cancelRequestedAtMs: 20,
cancelReason: 'user',
};
},
},
...overrides,
};
return { events, input };
}
async function invoke(stack, request) {
const prepared = await stack.admission.prepare(request);
return prepared.handle(request.body);
}
test('production composition exposes the reviewed Run and Workflow routes', async () => {
const { events, input } = fixture();
const stack = createProductionClusterControlApplicationStack(input, {
createEventId: () => EVENT_ID,
});
assert.deepEqual(PRODUCTION_CLUSTER_CONTROL_ROUTE_OPERATIONS, [
'task.get',
'task.list',
'task.start',
'run.get',
'run.list',
'run.events.list',
'run.steps.list',
'run.cancel',
'workflow.read',
'workflow.run.read',
'workflow.run.list',
'workflow.step.list',
'workflow.event.list',
'workflow.start',
'workflow.cancel',
]);
assert.deepEqual(await stack.reconcile(), {
safe: true,
remaining: 0,
failed: 0,
});
assert.equal(await stack.startLifecycles(), true);
const tasks = await invoke(
stack,
metadata('/api/v3/projects/project-1/tasks', 'GET', null, {
limit: ['8'],
}),
);
assert.equal(tasks.statusCode, 200);
assert.equal(tasks.body.tasks[0].taskId, 'task-1');
assert.equal(JSON.stringify(tasks).includes('private'), false);
const task = await invoke(
stack,
metadata('/api/v3/projects/project-1/tasks/task-1'),
);
assert.equal(task.statusCode, 200);
assert.equal(task.body.task.taskId, 'task-1');
assert.match(task.body.task.contentDigest, /^[0-9a-f]{64}$/);
assert.equal(JSON.stringify(task).includes('private'), false);
const read = await invoke(
stack,
metadata('/api/v3/projects/project-1/runs/run-1'),
);
assert.equal(read.statusCode, 200);
assert.equal(read.body.run.id, 'run-1');
const listed = await invoke(
stack,
metadata('/api/v3/projects/project-1/runs', 'GET', null, {
limit: ['8'],
}),
);
assert.equal(listed.statusCode, 200);
assert.equal(listed.body.runs[0].id, 'run-1');
const timeline = await invoke(
stack,
metadata('/api/v3/projects/project-1/runs/run-1/events', 'GET', null, {
after_sequence: ['0'],
limit: ['8'],
}),
);
assert.equal(timeline.statusCode, 200);
assert.equal(timeline.body.events[0].type, 'run.created');
assert.equal(JSON.stringify(timeline).includes('secret'), false);
const steps = await invoke(
stack,
metadata('/api/v3/projects/project-1/runs/run-1/steps', 'GET', null, {
limit: ['8'],
}),
);
assert.deepEqual(steps, {
statusCode: 200,
body: { steps: [], hasMore: false, next: null },
});
const cancellation = await invoke(
stack,
metadata('/api/v3/projects/project-1/runs/run-1/cancellation', 'POST', {
schema: 'qinglong/run-cancellation@v1',
mutationId: 'mutation-production-1',
}),
);
assert.equal(cancellation.statusCode, 202);
assert.equal(cancellation.body.status, 'accepted');
assert.equal(events.includes(`cancel:run-1:${EVENT_ID}`), true);
assert.equal(events.includes('audit:run.get:allowed'), true);
assert.equal(events.includes('audit:run.events.list:allowed'), true);
assert.equal(events.includes('audit:run.steps.list:allowed'), true);
assert.equal(events.includes('audit:run.cancel:allowed'), true);
const workflows = await invoke(
stack,
metadata('/api/v3/projects/project-1/packages/example/workflows'),
);
assert.equal(workflows.statusCode, 200);
assert.equal(workflows.body.found, false);
const workflowStart = await invoke(
stack,
metadata(
'/api/v3/projects/project-1/packages/example/workflows/daily/runs',
'POST',
{
schema: 'qinglong/cluster-plugin-package-workflow-start-request@v1',
planId: '123e4567-e89b-42d3-a456-426614174000',
runId: '123e4567-e89b-42d3-a456-426614174001',
stepRunIds: {
run: '123e4567-e89b-42d3-a456-426614174002',
},
},
),
);
assert.equal(workflowStart.statusCode, 201);
assert.equal(workflowStart.body.replayed, false);
assert.equal(events.includes('audit:workflow.read:allowed'), true);
assert.equal(events.includes('audit:workflow.start:allowed'), true);
const workflowRunRead = await invoke(
stack,
metadata(
'/api/v3/projects/project-1/packages/example/workflows/daily/runs/123e4567-e89b-42d3-a456-426614174001',
),
);
assert.equal(workflowRunRead.statusCode, 404);
assert.deepEqual(workflowRunRead.body, { code: 'workflow_run_not_found' });
assert.equal(
events.includes(
'workflow-run-read:example:daily:123e4567-e89b-42d3-a456-426614174001',
),
true,
);
assert.equal(events.includes('audit:workflow.run.read:allowed'), true);
const workflowRunListRequest = metadata(
'/api/v3/projects/project-1/packages/example/workflows/daily/runs',
);
const workflowRunList = await invoke(stack, {
...workflowRunListRequest,
query: { limit: ['16'] },
});
assert.equal(workflowRunList.statusCode, 200);
assert.deepEqual(workflowRunList.body.runs, []);
assert.equal(events.includes('workflow-run-list:example:daily:16'), true);
assert.equal(events.includes('audit:workflow.run.list:allowed'), true);
const workflowStepListRequest = metadata(
'/api/v3/projects/project-1/packages/example/workflows/daily/runs/123e4567-e89b-42d3-a456-426614174001/steps',
);
const workflowStepList = await invoke(stack, {
...workflowStepListRequest,
query: { limit: ['16'] },
});
assert.equal(workflowStepList.statusCode, 404);
assert.deepEqual(workflowStepList.body, { code: 'workflow_run_not_found' });
assert.equal(
events.includes(
'workflow-step-list:example:daily:123e4567-e89b-42d3-a456-426614174001:16',
),
true,
);
assert.equal(events.includes('audit:workflow.step.list:allowed'), true);
const workflowEventListRequest = metadata(
'/api/v3/projects/project-1/packages/example/workflows/daily/runs/123e4567-e89b-42d3-a456-426614174001/events',
);
const workflowEventList = await invoke(stack, {
...workflowEventListRequest,
query: { limit: ['16'], after_sequence: ['2'] },
});
assert.equal(workflowEventList.statusCode, 404);
assert.deepEqual(workflowEventList.body, { code: 'workflow_run_not_found' });
assert.equal(
events.includes(
'workflow-event-list:example:daily:123e4567-e89b-42d3-a456-426614174001:16:2',
),
true,
);
assert.equal(events.includes('audit:workflow.event.list:allowed'), true);
const workflowCancellation = await invoke(
stack,
metadata(
'/api/v3/projects/project-1/packages/example/workflows/daily/runs/123e4567-e89b-42d3-a456-426614174001/cancellation',
'POST',
{
schema: 'qinglong/run-cancellation@v1',
mutationId: 'workflow-cancel-production-1',
},
),
);
assert.equal(workflowCancellation.statusCode, 202);
assert.equal(workflowCancellation.body.status, 'accepted');
assert.equal(
events.includes(
`workflow-cancel:example:daily:123e4567-e89b-42d3-a456-426614174001:${EVENT_ID}`,
),
true,
);
assert.equal(events.includes('audit:workflow.cancel:allowed'), true);
assert.equal(await stack.stop(), 'stopped');
});
test('production composition fails closed for an unreviewed route', async () => {
const { input } = fixture();
const stack = createProductionClusterControlApplicationStack(input);
await assert.rejects(
stack.admission.prepare(
metadata('/api/v3/projects/project-1/runs/run-1/retry', 'POST'),
),
(error) => error?.statusCode === 404 && error?.code === 'route_not_found',
);
});
test('optionally exposes Prompt execution behind shared admission and policy', async () => {
const { events, input } = fixture();
let command;
const stack = createProductionClusterControlApplicationStack(input, {
promptExecution: {
now: () => 2_000,
maxExecutionMs: 10_000,
capability: {
async execute(value) {
command = value;
return {
status: 'executed',
admission: {
requestId: value.requestId,
invocationId: 'ppi:1',
runId: 'ppr:1',
stepRunId: 'pps:1',
},
finalization: { runStatus: 'succeeded' },
result: { text: 'live output' },
};
},
},
},
});
assert.deepEqual(PRODUCTION_CLUSTER_CONTROL_OPTIONAL_ROUTE_OPERATIONS, [
'prompt.read',
'prompt.execute',
'prompt.execution.read',
'prompt.execution.output.read',
'prompt.output.read',
]);
const response = await invoke(
stack,
metadata(
'/api/v3/projects/project-1/packages/example/prompts/summary/executions',
'POST',
{
schema: 'qinglong/cluster-plugin-package-prompt-execution-request@v2',
requestId: 'prompt-request-1',
traceId: 'trace-1',
parameters: { subject: 'private input' },
provider: 'openai-compatible',
model: 'model-a',
maxOutputTokens: 256,
timeoutMs: 5_000,
},
),
);
assert.equal(response.statusCode, 200);
assert.equal(command.projectId, 'project-1');
assert.deepEqual(command.policyFence, {
projectVersion: 3,
bindingVersion: 7,
});
assert.equal(events.includes('audit:prompt.execute:allowed'), true);
});
test('optionally exposes the redacted Prompt catalog behind shared admission and policy', async () => {
const { events, input } = fixture();
const stack = createProductionClusterControlApplicationStack(input, {
promptCatalog: {
capability: {
async inspect(projectId, packageName) {
return {
schema: 'qinglong/plugin-package-prompt-catalog@v1',
projectId,
packageName,
found: true,
publicationState: 'active',
prompts: [
{
id: 'summary',
name: 'Summary',
description: null,
parameters: [],
},
],
};
},
},
},
});
const result = await invoke(
stack,
metadata('/api/v3/projects/project-1/packages/example/prompts'),
);
assert.equal(result.statusCode, 200);
assert.equal(result.body.prompts[0].id, 'summary');
assert.equal(JSON.stringify(result).includes('template'), false);
assert.equal(events.includes('audit:prompt.read:allowed'), true);
});
test('optionally inspects one Prompt execution behind shared admission and policy', async () => {
const { events, input } = fixture();
let command;
const stack = createProductionClusterControlApplicationStack(input, {
createEventId: () => '00000000-0000-4000-8000-000000000011',
promptExecutionInspection: {
now: () => 2_000,
capability: {
async inspectAuthorized(value) {
command = value;
return {
schema: 'qinglong/plugin-package-prompt-execution-inspection@v1',
found: true,
projectId: value.projectId,
packageName: value.packageName,
promptId: value.promptId,
executionRequestId: value.executionRequestId,
execution: {
invocationId: 'invocation-1',
runId: '00000000-0000-4000-8000-000000000010',
stepRunId: 'step-1',
runStatus: 'running',
runVersion: 2,
eventSequence: 2,
stepStatus: 'running',
stepVersion: 2,
admittedAtMs: 1_000,
startedAtMs: 1_000,
finishedAtMs: null,
finalizedAtMs: null,
},
};
},
},
},
});
const result = await invoke(
stack,
metadata(
'/api/v3/projects/project-1/packages/example/prompts/summary/executions/execution-request-1',
),
);
assert.equal(result.statusCode, 200);
assert.equal(command.executionRequestId, 'execution-request-1');
assert.equal(command.audit.operationId, 'prompt.execution.read');
assert.equal(events.includes('audit:prompt.execution.read:allowed'), true);
});
test('optionally exposes Prompt output read behind shared admission and policy', async () => {
const { events, input } = fixture();
let command;
const stack = createProductionClusterControlApplicationStack(input, {
promptOutputRead: {
capability: {
async read(value) {
command = value;
return {
schema: 'qinglong/plugin-package-prompt-output-read-result@v1',
status: 'not_found',
};
},
},
},
});
const request = metadata(
'/api/v3/projects/project-1/runs/run-1/prompt-output-artifacts/pao:1',
);
const result = await invoke(stack, {
...request,
query: { artifact_digest: ['a'.repeat(64)] },
});
assert.equal(result.statusCode, 404);
assert.equal(command.projectId, 'project-1');
assert.equal(command.runId, 'run-1');
assert.equal(command.artifactId, 'pao:1');
assert.equal(command.principal.subject.id, 'app-production');
assert.equal(events.includes('audit:prompt.output.read:allowed'), true);
});
test('optionally recovers Prompt output by execution requestId behind artifact.read', async () => {
const { events, input } = fixture();
let command;
const stack = createProductionClusterControlApplicationStack(input, {
promptExecutionOutputRead: {
capability: {
async read(value) {
command = value;
return {
schema:
'qinglong/plugin-package-prompt-execution-output-read-result@v1',
status: 'not_found',
projectId: value.projectId,
packageName: value.packageName,
promptId: value.promptId,
executionRequestId: value.executionRequestId,
};
},
},
},
});
const result = await invoke(
stack,
metadata(
'/api/v3/projects/project-1/packages/example/prompts/summary/executions/execution-request-1/output',
),
);
assert.equal(result.statusCode, 404);
assert.equal(command.projectId, 'project-1');
assert.equal(command.packageName, 'example');
assert.equal(command.promptId, 'summary');
assert.equal(command.executionRequestId, 'execution-request-1');
assert.equal(command.principal.subject.id, 'app-production');
assert.equal(
events.includes('audit:prompt.execution.output.read:allowed'),
true,
);
});
test('production start requires an enabled configuration before owning resources', () => {
assert.throws(
() =>
startProductionClusterControlApplication({
config: { enabled: false, profile: 'standalone' },
recovery: { ownerId: 'production-test' },
audit() {},
}),
/database binding requires an enabled cluster-control config/,
);
});
test('production composition rejects an invalid event ID factory', () => {
const { input } = fixture();
assert.throws(
() =>
createProductionClusterControlApplicationStack(input, {
createEventId: 'invalid',
}),
/event ID factory is invalid/,
);
});
test('starts and stops Worker ingress through the injected runtime port', async () => {
const events = [];
const runtime = Object.freeze({
offers: { claimNext() {} },
activation: {
acknowledgeStarting() {},
acknowledgeRunning() {},
failStart() {},
},
artifacts: { upload() {} },
completion: { complete() {} },
leaseControl: { control() {} },
});
const { input } = fixture({ workerRuntime: runtime });
const config = {
enabled: true,
profile: 'cluster-control',
http: { host: '127.0.0.1', port: 5801 },
transport: {},
database: {},
security: { workerCredentialPepper: 'A'.repeat(43) },
artifact: {},
};
const stack = createProductionClusterControlApplicationStack(input, {
workerIngress: { config },
async startWorkerIngress(options) {
events.push('start-worker-ingress');
assert.equal(options.config, config);
assert.equal(options.runtime, runtime);
return {
status: 'active',
protocol: 'https',
transport: 'mutual-tls',
address: { host: '127.0.0.1', port: 5801 },
evidence: input.evidence,
reloadTransport() {
return 1;
},
async stop() {
events.push('stop-worker-ingress');
return 'stopped';
},
};
},
});
assert.equal(await stack.startLifecycles(), true);
assert.equal(await stack.startLifecycles(), true);
assert.equal(await stack.stop(), 'stopped');
assert.equal(await stack.stop(), 'stopped');
assert.deepEqual(events, ['start-worker-ingress', 'stop-worker-ingress']);
});
test('fails closed when Worker ingress has no runtime service port', async () => {
const { input } = fixture();
const stack = createProductionClusterControlApplicationStack(input, {
workerIngress: {
config: {
enabled: true,
profile: 'cluster-control',
},
},
async startWorkerIngress() {
throw new Error('must not start');
},
});
await assert.rejects(
stack.startLifecycles(),
/requires an injected runtime service port/,
);
});
test('drains a Worker listener when its Pool fails during activation', async () => {
let stops = 0;
const diagnostics = [];
const { input } = fixture({
workerRuntime: {
offers: { claimNext() {} },
activation: {
acknowledgeStarting() {},
acknowledgeRunning() {},
failStart() {},
},
artifacts: { upload() {} },
completion: { complete() {} },
leaseControl: { control() {} },
},
});
const stack = createProductionClusterControlApplicationStack(input, {
workerIngress: {
config: { enabled: true, profile: 'cluster-control' },
onDiagnostic(error) {
diagnostics.push(error);
},
},
async startWorkerIngress(options) {
options.onPoolError(new Error('worker database unavailable'));
return {
status: 'active',
protocol: 'https',
transport: 'mutual-tls',
address: { host: '127.0.0.1', port: 5801 },
evidence: input.evidence,
reloadTransport() {
return 1;
},
async stop() {
stops += 1;
return 'stopped';
},
};
},
});
await assert.rejects(
stack.startLifecycles(),
/became unavailable during activation/,
);
assert.equal(stops, 1);
assert.equal(diagnostics.length, 1);
});
@@ -0,0 +1,76 @@
const assert = require('node:assert/strict');
const { test } = require('node:test');
const {
ClusterRemoteRunActivationService,
} = require('@qinglong/cluster-control/remote-activation');
const SESSION_ID = '018f5c64-9b9d-7f1a-8c2d-1234567890ac';
const EVENT_IDS = [
'018f5c64-9b9d-7f1a-8c2d-1234567890a1',
'018f5c64-9b9d-7f1a-8c2d-1234567890a2',
'018f5c64-9b9d-7f1a-8c2d-1234567890a3',
'018f5c64-9b9d-7f1a-8c2d-1234567890a4',
'018f5c64-9b9d-7f1a-8c2d-1234567890a5',
];
function command() {
return {
runId: 'run-1',
attemptId: 'attempt-1',
workerSessionId: SESSION_ID,
workerGeneration: 2,
offerId: 'offer-1',
leaseGeneration: 3,
leaseToken: 'worker_generated_lease_capability_0000000000000001',
expectedLeaseVersion: 4,
};
}
test('binds Worker principal and creates server-owned event IDs', async () => {
const observed = [];
const repository = {
async acknowledgeStarting(value) {
observed.push(['starting', value]);
return { status: 'applied', snapshot: {} };
},
async acknowledgeRunning(value) {
observed.push(['running', value]);
return { status: 'applied', snapshot: {} };
},
async failStart(value) {
observed.push(['failed', value]);
return { status: 'applied', snapshot: {} };
},
};
let sequence = 0;
const service = new ClusterRemoteRunActivationService(repository, {
createEventId: () => EVENT_IDS[sequence++],
});
const principal = { workerId: 'edge-1' };
await service.acknowledgeStarting(principal, command());
await service.acknowledgeRunning(principal, {
...command(),
executorHandle: 'remote:handle-1',
callbackSequence: 1,
callbackTokenDigest: 'a'.repeat(64),
});
await service.failStart(principal, command());
assert.deepEqual(observed, [
['starting', { ...command(), workerId: 'edge-1', eventId: EVENT_IDS[0] }],
['running', {
...command(),
executorHandle: 'remote:handle-1',
callbackSequence: 1,
callbackTokenDigest: 'a'.repeat(64),
workerId: 'edge-1',
attemptEventId: EVENT_IDS[1],
runEventId: EVENT_IDS[2],
}],
['failed', {
...command(),
workerId: 'edge-1',
attemptEventId: EVENT_IDS[3],
runEventId: EVENT_IDS[4],
}],
]);
});
@@ -0,0 +1,258 @@
'use strict';
const assert = require('node:assert/strict');
const { createHash } = require('node:crypto');
const { test } = require('node:test');
const {
RemoteWorkerCompletionFenceRejectedError,
RemoteWorkerCompletionUnavailableError,
createRemoteWorkerArtifactUploadPreamble,
} = require('@qinglong/runtime-core/remote-worker-completion');
const {
ClusterRemoteWorkerArtifactService,
ClusterRemoteWorkerCompletionService,
} = require('@qinglong/cluster-control/remote-completion');
const SESSION_ID = '018f0000-0000-7000-8000-000000000001';
const LEASE_TOKEN = 'worker_generated_lease_capability_0000000000000001';
const LOG_ARTIFACT_ID = `wlog-${'a'.repeat(30)}`;
const CALLBACK_TOKEN_DIGEST = 'b'.repeat(64);
function fence() {
return {
workerId: 'worker-1',
workerSessionId: SESSION_ID,
workerGeneration: 2,
projectId: 'project-1',
runId: 'run-1',
attemptId: 'attempt-1',
offerId: 'offer-1',
leaseGeneration: 3,
leaseToken: LEASE_TOKEN,
expectedLeaseVersion: 4,
};
}
function uploadCommand(content, overrides = {}) {
return {
...fence(),
logArtifactId: LOG_ARTIFACT_ID,
byteLength: content.byteLength,
truncated: false,
...overrides,
};
}
function completionCommand(content, overrides = {}) {
return {
...fence(),
callbackSequence: 1,
callbackTokenDigest: CALLBACK_TOKEN_DIGEST,
result: {
outcome: 'succeeded',
startedAtMs: 100,
finishedAtMs: 200,
exitCode: 0,
},
artifact: {
logArtifactId: LOG_ARTIFACT_ID,
byteLength: content.byteLength,
sha256: createHash('sha256').update(content).digest('hex'),
truncated: false,
},
...overrides,
};
}
function split(bytes, sizes) {
return (async function* () {
let offset = 0;
for (const size of sizes) {
yield bytes.subarray(offset, offset + size);
offset += size;
}
if (offset < bytes.byteLength) yield bytes.subarray(offset);
})();
}
test('authorizes a framed upload before storing exact capability-free bytes', async () => {
const content = Buffer.from('worker-log');
const command = uploadCommand(content);
const preamble = createRemoteWorkerArtifactUploadPreamble(command);
const envelope = Buffer.concat([preamble, content]);
const observations = [];
const service = new ClusterRemoteWorkerArtifactService(
{
async authorizeArtifactUpload(value) {
observations.push({ kind: 'authority', value });
},
},
{
async put(target, chunks) {
const stored = [];
for await (const chunk of chunks) stored.push(Buffer.from(chunk));
const bytes = Buffer.concat(stored);
observations.push({ kind: 'store', target, bytes });
return {
status: 'stored',
...target,
sha256: createHash('sha256').update(bytes).digest('hex'),
};
},
async inspect() { return undefined; },
},
);
const receipt = await service.upload({
workerId: command.workerId,
workerSessionId: command.workerSessionId,
contentLength: envelope.byteLength,
chunks: split(envelope, [1, 2, 1, 3, 5]),
});
assert.equal(receipt.sha256, createHash('sha256').update(content).digest('hex'));
assert.deepEqual(observations.map(({ kind }) => kind), ['authority', 'store']);
assert.deepEqual(observations[0].value, command);
assert.equal('leaseToken' in observations[1].target, false);
assert.equal('workerId' in observations[1].target, false);
assert.deepEqual(observations[1].bytes, content);
});
test('rejects envelope drift before authority or storage access', async () => {
const content = Buffer.from('log');
const command = uploadCommand(content);
const preamble = createRemoteWorkerArtifactUploadPreamble(command);
const envelope = Buffer.concat([preamble, content]);
let authorityCalls = 0;
let storeCalls = 0;
const service = new ClusterRemoteWorkerArtifactService(
{
async authorizeArtifactUpload() { authorityCalls += 1; },
},
{
async put() { storeCalls += 1; throw new Error('must not store'); },
async inspect() { return undefined; },
},
);
await assert.rejects(
service.upload({
workerId: command.workerId,
workerSessionId: command.workerSessionId,
contentLength: envelope.byteLength + 1,
chunks: split(envelope, [4]),
}),
/envelope length does not match/,
);
assert.equal(authorityCalls, 0);
assert.equal(storeCalls, 0);
});
test('fails closed when a store does not consume or drifts from the command', async () => {
const content = Buffer.from('log');
const command = uploadCommand(content);
const preamble = createRemoteWorkerArtifactUploadPreamble(command);
const envelope = Buffer.concat([preamble, content]);
const service = new ClusterRemoteWorkerArtifactService(
{ async authorizeArtifactUpload() {} },
{
async put(target) {
return { status: 'stored', ...target, sha256: 'c'.repeat(64) };
},
async inspect() { return undefined; },
},
);
await assert.rejects(
service.upload({
workerId: command.workerId,
workerSessionId: command.workerSessionId,
contentLength: envelope.byteLength,
chunks: split(envelope, [4]),
}),
RemoteWorkerCompletionUnavailableError,
);
});
test('inspects immutable Artifact evidence before one server-ID completion', async () => {
const content = Buffer.from('worker-log');
const command = completionCommand(content);
const calls = [];
const ids = [
'018f0000-0000-7000-8000-000000000011',
'018f0000-0000-7000-8000-000000000012',
];
const service = new ClusterRemoteWorkerCompletionService(
{
async complete(value) {
calls.push({ kind: 'repository', value });
return {
status: 'applied',
runId: value.runId,
attemptId: value.attemptId,
callbackSequence: value.callbackSequence,
};
},
},
{
async inspect(lookup) {
calls.push({ kind: 'store', lookup });
return {
status: 'already_stored',
...lookup,
byteLength: content.byteLength,
sha256: command.artifact.sha256,
truncated: false,
};
},
},
{ createEventId: () => ids.shift() },
);
assert.deepEqual(await service.complete(command), {
status: 'applied',
runId: 'run-1',
attemptId: 'attempt-1',
callbackSequence: 1,
});
assert.deepEqual(calls.map(({ kind }) => kind), ['store', 'repository']);
assert.equal(calls[1].value.attemptEventId.endsWith('11'), true);
assert.equal(calls[1].value.runEventId.endsWith('12'), true);
});
test('fences missing or digest-drifted Artifact evidence before completion', async () => {
const content = Buffer.from('worker-log');
const command = completionCommand(content);
let repositoryCalls = 0;
const repository = {
async complete() { repositoryCalls += 1; throw new Error('must not run'); },
};
const missing = new ClusterRemoteWorkerCompletionService(
repository,
{ async inspect() { return undefined; } },
);
await assert.rejects(
missing.complete(command),
(error) =>
error instanceof RemoteWorkerCompletionFenceRejectedError &&
error.reason === 'state_mismatch',
);
const drifted = new ClusterRemoteWorkerCompletionService(
repository,
{
async inspect(lookup) {
return {
status: 'stored',
...lookup,
byteLength: content.byteLength,
sha256: 'd'.repeat(64),
truncated: false,
};
},
},
);
await assert.rejects(
drifted.complete(command),
(error) =>
error instanceof RemoteWorkerCompletionFenceRejectedError &&
error.reason === 'replay_mismatch',
);
assert.equal(repositoryCalls, 0);
});
@@ -0,0 +1,139 @@
const assert = require('node:assert/strict');
const { test } = require('node:test');
const {
canonicalRemoteWorkerCapabilities,
} = require('@qinglong/runtime-core/remote-dispatch');
const {
createClusterTaskExecutionRevision,
} = require('@qinglong/runtime-core/cluster-execution-revision');
const {
digestRunDispatchLeaseToken,
} = require('@qinglong/runtime-core');
const {
ClusterRemoteWorkerOfferClaimService,
ClusterRemoteWorkerOfferFenceRejectedError,
} = require('../dist/remote-execution/remoteWorkerDispatcher');
const SESSION = '018f0000-0000-7000-8000-000000000001';
const TOKEN = 'worker_generated_lease_capability_0000000000000001';
const SOURCE_DIGEST = 'a'.repeat(64);
const TASK_REVISION = `qltd:v1:1:${SOURCE_DIGEST}`;
function candidate() {
return {
runId: 'run-1', attemptId: 'attempt-1', projectId: 'project-1',
taskId: 'task-1', taskRevision: TASK_REVISION, priority: 2,
queuedAtMs: 10, attemptCreatedAtMs: 11, attemptNumber: 1,
executorType: 'remote_worker',
};
}
function revision() {
return createClusterTaskExecutionRevision({
projectId: 'project-1', taskId: 'task-1', taskRevision: TASK_REVISION,
sourceRevision: 1, sourceContentDigest: SOURCE_DIGEST,
executorType: 'remote_worker', planSchema: 'qinglong/command-execution@v1',
command: { kind: 'argv', file: '/usr/bin/node', args: ['job.js'] },
environment: [],
placement: { required: { architectures: ['arm64'] } },
createdAtMs: 1,
});
}
function worker() {
const capabilities = canonicalRemoteWorkerCapabilities({
architecture: 'arm64', executors: ['remote-worker'],
});
return {
workerId: 'edge-1', sessionId: SESSION, generation: 2,
status: 'online', version: 1,
capabilitiesJson: capabilities.json, capabilitiesHash: capabilities.hash,
maxConcurrentRuns: 1, availableSlots: 1,
registeredAtMs: 1, lastHeartbeatAtMs: 10,
leaseExpiresAtMs: 60_000, updatedAtMs: 10,
};
}
function lease() {
return {
attemptId: 'attempt-1', runId: 'run-1', status: 'leased', version: 0,
leaseGeneration: 1, workerId: 'edge-1', workerSessionId: SESSION,
workerGeneration: 2, leaseTokenDigest: digestRunDispatchLeaseToken(TOKEN),
acquiredAtMs: 1000, renewedAtMs: 1000, expiresAtMs: 31_000,
updatedAtMs: 1000,
};
}
function service(overrides = {}) {
const calls = [];
const source = overrides.source ?? {
async findClusterDispatchRecovery() { return null; },
async listClusterDispatchCandidates() {
calls.push('candidates');
return { observedAtMs: 1000, candidates: [candidate()], truncated: false };
},
};
const value = new ClusterRemoteWorkerOfferClaimService(
source,
overrides.workers ?? { async findById() { calls.push('worker'); return worker(); } },
overrides.revisions ?? {
async resolveClusterTaskExecutionRevision() { calls.push('revision'); return revision(); },
},
overrides.leases ?? {
async claim(command) { calls.push(`claim:${command.offerId}`); return { status: 'claimed', lease: lease() }; },
},
{ createEventId: () => 'event-1' },
);
return { value, calls };
}
const command = {
workerSessionId: SESSION,
workerGeneration: 2,
offerId: 'offer-1',
leaseToken: TOKEN,
};
test('pulls one bounded candidate, applies Placement and atomically returns a fenced offer', async () => {
const { value, calls } = service();
const result = await value.claimNext({ workerId: 'edge-1' }, command);
assert.equal(result.status, 'offered');
assert.equal(result.offer.deliveryKind, 'new_claim');
assert.equal(result.offer.worker.sessionId, SESSION);
assert.equal(result.offer.executionRevision.placement.required.executors[0], 'remote-worker');
assert.deepEqual(calls, ['candidates', 'worker', 'revision', 'claim:offer-1']);
});
test('rebuilds a lost response only for the same Worker-provided offer capability', async () => {
const { value } = service({
source: {
async findClusterDispatchRecovery() {
return {
observedAtMs: 2000,
candidate: candidate(),
lease: lease(),
workerCurrent: true,
};
},
async listClusterDispatchCandidates() { throw new Error('must not list'); },
},
});
const result = await value.claimNext({ workerId: 'edge-1' }, command);
assert.equal(result.status, 'offered');
assert.equal(result.offer.deliveryKind, 'lease_recovery');
await assert.rejects(
value.claimNext({ workerId: 'edge-1' }, { ...command, leaseToken: `${TOKEN}x` }),
ClusterRemoteWorkerOfferFenceRejectedError,
);
});
test('returns low-cardinality idle evidence when the authenticated Worker does not match', async () => {
const { value } = service({
workers: { async findById() { return { ...worker(), sessionId: '018f0000-0000-7000-8000-000000000002' }; } },
});
const result = await value.claimNext({ workerId: 'edge-1' }, command);
assert.deepEqual(
{ status: result.status, reason: result.reason },
{ status: 'idle', reason: 'worker_unavailable' },
);
});
@@ -0,0 +1,93 @@
'use strict';
const assert = require('node:assert/strict');
const { test } = require('node:test');
const {
ClusterRemoteWorkerLeaseControlService,
} = require('@qinglong/cluster-control/lease-control');
const SESSION_ID = '018f0000-0000-7000-8000-000000000001';
const LEASE_TOKEN = 'worker_generated_lease_capability_0000000000000001';
function command() {
return {
workerId: 'worker-1',
workerSessionId: SESSION_ID,
workerGeneration: 2,
projectId: 'project-1',
runId: 'run-1',
attemptId: 'attempt-1',
offerId: 'offer-1',
leaseGeneration: 3,
leaseToken: LEASE_TOKEN,
expectedLeaseVersion: 4,
};
}
test('adds server-owned renewal duration and timeout Event authority', async () => {
let observed;
const service = new ClusterRemoteWorkerLeaseControlService({
async control(value) {
observed = value;
return {
status: 'renewed',
projectId: value.projectId,
runId: value.runId,
attemptId: value.attemptId,
offerId: value.offerId,
leaseGeneration: value.leaseGeneration,
leaseVersion: value.expectedLeaseVersion + 1,
renewedAtMs: 10_000,
expiresAtMs: 55_000,
};
},
}, {
leaseDurationMs: 45_000,
createEventId: () => '018f0000-0000-7000-8000-000000000011',
});
assert.deepEqual(await service.control(command()), {
status: 'renewed',
projectId: 'project-1',
runId: 'run-1',
attemptId: 'attempt-1',
offerId: 'offer-1',
leaseGeneration: 3,
leaseVersion: 5,
renewedAtMs: 10_000,
expiresAtMs: 55_000,
});
assert.deepEqual(observed, {
...command(),
leaseDurationMs: 45_000,
timeoutEventId: '018f0000-0000-7000-8000-000000000011',
});
});
test('fails closed before repository access for invalid server Event IDs', async () => {
let calls = 0;
const service = new ClusterRemoteWorkerLeaseControlService({
async control() { calls += 1; throw new Error('must not run'); },
}, { createEventId: () => '' });
await assert.rejects(service.control(command()), /unavailable/);
assert.equal(calls, 0);
});
test('rejects a repository response that drifts from the wire contract', async () => {
const service = new ClusterRemoteWorkerLeaseControlService({
async control(value) {
return {
status: 'renewed',
projectId: value.projectId,
runId: value.runId,
attemptId: value.attemptId,
offerId: value.offerId,
leaseGeneration: value.leaseGeneration,
leaseVersion: value.expectedLeaseVersion + 1,
renewedAtMs: 10_000,
expiresAtMs: 10_000,
};
},
});
await assert.rejects(service.control(command()), /invalid/);
});
@@ -0,0 +1,133 @@
'use strict';
const assert = require('node:assert/strict');
const { test } = require('node:test');
const {
RemoteWorkerSecretDeliveryFenceRejectedError,
} = require('@qinglong/runtime-core/remote-secret-delivery');
const { createSecretRef } = require('@qinglong/runtime-core/secret-reference');
const {
ClusterRemoteWorkerSecretDeliveryService,
} = require('../dist/remote-execution/remoteWorkerSecretDeliveryService');
const SESSION_ID = '018f0000-0000-7000-8000-000000000001';
const SECRET_REF = createSecretRef({ projectId: 'project-1', name: 'token' });
const DIGEST = 'a'.repeat(64);
function command() {
return {
workerSessionId: SESSION_ID, workerGeneration: 2,
runId: 'run-1', attemptId: 'attempt-1', projectId: 'project-1',
taskId: 'task-1', taskRevision: 'revision-1', executionDigest: DIGEST,
offerId: 'offer-1', leaseGeneration: 3,
leaseToken: 'worker_generated_lease_capability_0000000000000001',
expectedLeaseVersion: 4, secretRefs: [SECRET_REF],
};
}
function authority(input) {
const { leaseToken: _leaseToken, expectedLeaseVersion, ...rest } = input;
return {
workerId: 'edge-1', ...rest, leaseVersion: expectedLeaseVersion,
};
}
test('resolves plaintext only after repository authority succeeds', async () => {
const events = [];
let authorized;
const service = new ClusterRemoteWorkerSecretDeliveryService({
async authorize(input) {
events.push('authorize');
authorized = input;
return authority(input);
},
}, {
async resolve(input) {
events.push('resolve');
assert.equal('leaseToken' in input, false);
return {
values: [{ secretRef: SECRET_REF, value: 'resolved-value' }],
dispose() { events.push('dispose'); },
};
},
});
const result = await service.deliver({ workerId: 'edge-1' }, command());
assert.equal(authorized.workerId, 'edge-1');
assert.deepEqual(result.values, [
{ secretRef: SECRET_REF, value: 'resolved-value' },
]);
assert.deepEqual(events, ['authorize', 'resolve']);
await result.dispose();
assert.deepEqual(events, ['authorize', 'resolve', 'dispose']);
});
test('never calls the plaintext provider for fenced or replayed authority', async () => {
let resolutions = 0;
const service = new ClusterRemoteWorkerSecretDeliveryService({
async authorize() {
throw new RemoteWorkerSecretDeliveryFenceRejectedError('authority_mismatch');
},
}, {
async resolve() { resolutions += 1; },
});
await assert.rejects(
service.deliver({ workerId: 'edge-1' }, command()),
/authority_mismatch/,
);
assert.equal(resolutions, 0);
});
test('never calls plaintext provider when an injected repository widens authority', async () => {
let resolutions = 0;
const service = new ClusterRemoteWorkerSecretDeliveryService({
async authorize(input) {
return { ...authority(input), taskId: 'task-other' };
},
}, {
async resolve() { resolutions += 1; },
});
await assert.rejects(
service.deliver({ workerId: 'edge-1' }, command()),
/unavailable/,
);
assert.equal(resolutions, 0);
});
test('disposes malformed provider output and converts it to unavailable', async () => {
let disposed = 0;
const service = new ClusterRemoteWorkerSecretDeliveryService({
async authorize(input) { return authority(input); },
}, {
async resolve() {
return {
values: [{ secretRef: SECRET_REF, value: 'x'.repeat(17 * 1024) }],
dispose() { disposed += 1; },
};
},
});
await assert.rejects(
service.deliver({ workerId: 'edge-1' }, command()),
/unavailable/,
);
assert.equal(disposed, 1);
});
test('rejects extensible provider output and still invokes valid cleanup', async () => {
let disposed = 0;
const service = new ClusterRemoteWorkerSecretDeliveryService({
async authorize(input) { return authority(input); },
}, {
async resolve() {
return {
values: [{ secretRef: SECRET_REF, value: 'resolved-value' }],
dispose() { disposed += 1; },
diagnostic: 'must-not-cross-boundary',
};
},
});
await assert.rejects(
service.deliver({ workerId: 'edge-1' }, command()),
/unavailable/,
);
assert.equal(disposed, 1);
});
@@ -0,0 +1,184 @@
const assert = require('node:assert/strict');
const { test } = require('node:test');
const {
CLUSTER_CONTROL_ROUTE_REGISTRY_LIMITS,
ClusterControlRouteRegistryConfigurationError,
ClusterControlRouteResolutionError,
createClusterControlRouteRegistry,
isClusterControlRouteRegistry,
} = require('@qinglong/cluster-control/routes');
function metadata(overrides = {}) {
return Object.freeze({
requestId: 'request-1',
method: 'POST',
path: '/api/v3/projects/prj_default/runs',
query: Object.freeze({}),
headers: Object.freeze({}),
signal: new AbortController().signal,
...overrides,
});
}
function definition(overrides = {}) {
return {
method: 'POST',
path: '/api/v3/projects/{projectId}/runs',
operationId: 'run.create',
permission: 'run.start',
projectParameter: 'projectId',
handle(request, parameters) {
return {
statusCode: 202,
body: {
projectId: request.projectId,
parameter: parameters.projectId,
},
};
},
...overrides,
};
}
test('compiles one immutable reviewed route and owns its Project scope', async () => {
const source = definition({ allowedQuery: ['dry_run'] });
const registry = createClusterControlRouteRegistry([source]);
source.operationId = 'forged.operation';
assert.equal(isClusterControlRouteRegistry(registry), true);
assert.equal(isClusterControlRouteRegistry({ ...registry }), false);
assert.equal(Object.isFrozen(registry), true);
assert.equal(registry.contractVersion, 1);
assert.equal(registry.size, 1);
const route = registry.resolve(
metadata({ query: Object.freeze({ dry_run: Object.freeze(['true']) }) }),
);
assert.equal(route.operationId, 'run.create');
assert.equal(route.permission, 'run.start');
assert.equal(route.projectId, 'prj_default');
assert.equal(Object.isFrozen(route), true);
assert.deepEqual(
await route.handle({
request: { ...metadata(), body: { taskId: 'task-1' } },
principal: {
subject: { type: 'user', id: 'usr_primary' },
authenticationId: 'session:1',
authenticatedAtMs: 1,
expiresAtMs: 2,
assurance: 'multi_factor',
},
operationId: route.operationId,
permission: route.permission,
projectId: route.projectId,
policyFence: { projectVersion: 1, bindingVersion: 1 },
}),
{
statusCode: 202,
body: { projectId: 'prj_default', parameter: 'prj_default' },
},
);
});
test('rejects widened, ambiguous and unbounded route definitions at startup', () => {
const invalidSets = [
[definition({ extra: true })],
[definition({ path: '/api/v3/projects/{projectId}/' })],
[definition({ path: '/api/v3/projects/%7BprojectId%7D/runs' })],
[definition({ projectParameter: 'missing' })],
[definition(), definition({ operationId: 'run.create' })],
[
definition(),
definition({
path: '/api/v3/projects/fixed/runs',
operationId: 'run.create.fixed',
}),
],
];
for (const definitions of invalidSets) {
assert.throws(
() => createClusterControlRouteRegistry(definitions),
ClusterControlRouteRegistryConfigurationError,
);
}
const tooMany = Array.from(
{ length: CLUSTER_CONTROL_ROUTE_REGISTRY_LIMITS.maxRoutes + 1 },
(_, index) =>
definition({
path: `/api/v3/routes/route-${index}`,
operationId: `route.operation:${index}`,
projectParameter: null,
}),
);
assert.throws(
() => createClusterControlRouteRegistry(tooMany),
ClusterControlRouteRegistryConfigurationError,
);
});
test('rejects non-canonical paths and unknown query before returning a route', () => {
const registry = createClusterControlRouteRegistry([
definition({ allowedQuery: ['dry_run'] }),
]);
for (const path of [
'/api/v3/projects/prj_default/runs/',
'/api/v3/projects//runs',
'/api/v3/projects/%2e%2e/runs',
'/api/v3/projects/prj_default\\runs',
]) {
assert.throws(
() => registry.resolve(metadata({ path })),
(error) =>
error instanceof ClusterControlRouteResolutionError &&
error.statusCode === 400 &&
error.code === 'invalid_route_path',
);
}
assert.throws(
() =>
registry.resolve(
metadata({ query: Object.freeze({ debug: Object.freeze(['1']) }) }),
),
(error) =>
error instanceof ClusterControlRouteResolutionError &&
error.code === 'invalid_route_query',
);
assert.equal(
registry.resolve(metadata({ method: 'GET' })),
null,
'method is part of the reviewed route identity',
);
assert.equal(
registry.resolve(metadata({ path: '/api/v3/projects/prj_default/tasks' })),
null,
);
});
test('bounds repeated query values and rejects control characters', () => {
const registry = createClusterControlRouteRegistry([
definition({ allowedQuery: ['cursor'] }),
]);
for (const values of [
[],
Array.from(
{
length:
CLUSTER_CONTROL_ROUTE_REGISTRY_LIMITS.maxQueryValuesPerParameter + 1,
},
() => 'value',
),
['unsafe\u0000value'],
['x'.repeat(CLUSTER_CONTROL_ROUTE_REGISTRY_LIMITS.maxQueryValueBytes + 1)],
]) {
assert.throws(
() =>
registry.resolve(
metadata({ query: Object.freeze({ cursor: Object.freeze(values) }) }),
),
(error) =>
error instanceof ClusterControlRouteResolutionError &&
error.code === 'invalid_route_query',
);
}
});
@@ -0,0 +1,57 @@
'use strict';
const assert = require('node:assert/strict');
const { test } = require('node:test');
const {
ClusterRunCancellationConvergenceLifecycle,
} = require('../dist/run/runCancellationLifecycle');
function summary() {
return {
pages: 1,
scanned: 1,
settledRuns: 1,
settledAttempts: 0,
blocked: 0,
hasMore: false,
remaining: false,
stopReason: 'complete',
};
}
test('coalesces one bounded cycle and drains without owning per-Run timers', async () => {
let release;
let calls = 0;
const lifecycle = new ClusterRunCancellationConvergenceLifecycle({
async reconcile() {
calls += 1;
await new Promise((resolve) => { release = resolve; });
return summary();
},
}, { intervalMs: 10_000, stopTimeoutMs: 1_000 });
assert.equal(lifecycle.start(), 'started');
const first = lifecycle.runOnce();
const second = lifecycle.runOnce();
assert.equal(first, second);
while (!release) await new Promise((resolve) => setImmediate(resolve));
release();
assert.deepEqual(await first, summary());
assert.equal(calls, 1);
assert.deepEqual(await lifecycle.stopAndDrain(), { status: 'stopped' });
await assert.rejects(lifecycle.runOnce(), /stopping/);
});
test('reports a bounded drain timeout without cancelling database authority', async () => {
const lifecycle = new ClusterRunCancellationConvergenceLifecycle({
reconcile: () => new Promise(() => {}),
}, { intervalMs: 10_000, stopTimeoutMs: 100 });
lifecycle.start();
void lifecycle.runOnce();
assert.deepEqual(await lifecycle.stopAndDrain(), { status: 'timed_out' });
});
test('rejects an unbounded cadence configuration', () => {
assert.throws(() => new ClusterRunCancellationConvergenceLifecycle({
async reconcile() { return summary(); },
}, { intervalMs: 249, stopTimeoutMs: 1_000 }));
});
@@ -0,0 +1,206 @@
'use strict';
const assert = require('node:assert/strict');
const { test } = require('node:test');
const {
CLUSTER_RUN_CANCELLATION_SCHEMA,
ClusterRunCancellationFenceRejectedError,
ClusterRunCancellationNotFoundError,
ClusterRunCancellationUnavailableError,
} = require('@qinglong/runtime-core/cluster-run-cancellation');
const {
createClusterControlAdmissionPipeline,
} = require('@qinglong/cluster-control/admission');
const {
createClusterControlRouteRegistry,
} = require('@qinglong/cluster-control/routes');
const {
CLUSTER_CONTROL_RUN_CANCELLATION_ROUTE,
createClusterControlRunCancellationRoute,
} = require('@qinglong/cluster-control/run-routes');
const EVENT_ID = '018f0000-0000-7000-8000-000000000001';
const PRINCIPAL = Object.freeze({
subject: Object.freeze({ type: 'user', id: 'user-1' }),
authenticationId: 'session:user-1',
authenticatedAtMs: 9_000,
expiresAtMs: 11_000,
assurance: 'single_factor',
});
const METADATA = Object.freeze({
requestId: 'request-cancel-run',
method: 'POST',
path: '/api/v3/projects/project-1/runs/run-1/cancellation',
query: Object.freeze({}),
headers: Object.freeze({ authorization: 'Bearer opaque' }),
signal: new AbortController().signal,
});
function accepted(overrides = {}) {
return {
status: 'accepted',
projectId: 'project-1',
runId: 'run-1',
runStatus: 'running',
runVersion: 5,
eventSequence: 7,
cancelRequestedAtMs: 10_000,
cancelReason: 'user',
...overrides,
};
}
function pipeline(repository, events = [], policyFence = {
projectVersion: 2,
bindingVersion: 3,
}) {
return createClusterControlAdmissionPipeline({
routes: createClusterControlRouteRegistry([
createClusterControlRunCancellationRoute(repository, () => EVENT_ID),
]),
authenticator: {
authenticate() {
events.push('authenticate');
return PRINCIPAL;
},
},
policy: {
authorize(request) {
events.push(`authorize:${request.permission}:${request.projectId}`);
return { effect: 'allow', reasons: ['role_grant'], fence: policyFence };
},
},
audit: {
record(record) {
events.push(`audit:${record.outcome}:${record.operationId}`);
},
},
now: () => 10_000,
});
}
test('publishes one reviewed run.stop mutation route', () => {
const route = createClusterControlRunCancellationRoute({
async requestUserCancellation() { return accepted(); },
}, () => EVENT_ID);
assert.deepEqual(CLUSTER_CONTROL_RUN_CANCELLATION_ROUTE, {
method: 'POST',
path: '/api/v3/projects/{projectId}/runs/{runId}/cancellation',
operationId: 'run.cancel',
permission: 'run.stop',
projectParameter: 'projectId',
});
assert.equal(Object.isFrozen(route), true);
});
test('authenticates, authorizes and audits before committing cancellation', async () => {
const events = [];
let observed;
const prepared = await pipeline({
async requestUserCancellation(command) {
events.push('repository');
observed = command;
return accepted();
},
}, events).prepare(METADATA);
assert.deepEqual(events, [
'authenticate',
'authorize:run.stop:project-1',
'audit:allowed:run.cancel',
]);
assert.deepEqual(await prepared.handle({
schema: CLUSTER_RUN_CANCELLATION_SCHEMA,
mutationId: 'mutation-1',
}), {
statusCode: 202,
body: {
schema: CLUSTER_RUN_CANCELLATION_SCHEMA,
...accepted(),
},
});
assert.deepEqual(observed, {
projectId: 'project-1',
runId: 'run-1',
mutationId: 'mutation-1',
eventId: EVENT_ID,
subject: PRINCIPAL.subject,
policyFence: { projectVersion: 2, bindingVersion: 3 },
});
assert.equal(events.at(-1), 'repository');
});
test('rejects caller-selected reasons and missing policy fences', async () => {
let calls = 0;
const repository = {
async requestUserCancellation() { calls += 1; return accepted(); },
};
const prepared = await pipeline(repository).prepare(METADATA);
assert.deepEqual(await prepared.handle({
schema: CLUSTER_RUN_CANCELLATION_SCHEMA,
mutationId: 'mutation-1',
reason: 'shutdown',
}), {
statusCode: 400,
body: {
code: 'invalid_run_cancellation_request',
schema: CLUSTER_RUN_CANCELLATION_SCHEMA,
},
});
const unfenced = await pipeline(repository, [], null).prepare(METADATA);
assert.deepEqual(await unfenced.handle({
schema: CLUSTER_RUN_CANCELLATION_SCHEMA,
mutationId: 'mutation-1',
}), {
statusCode: 503,
body: { code: 'run_cancellation_unavailable' },
});
assert.equal(calls, 0);
});
test('maps replay, terminal, missing, fenced and unavailable outcomes', async () => {
for (const [outcome, expected] of [
[accepted({ status: 'already_requested' }), 200],
[{
status: 'already_terminal',
projectId: 'project-1',
runId: 'run-1',
runStatus: 'succeeded',
runVersion: 6,
eventSequence: 8,
}, 200],
]) {
const prepared = await pipeline({
async requestUserCancellation() { return outcome; },
}).prepare(METADATA);
const result = await prepared.handle({
schema: CLUSTER_RUN_CANCELLATION_SCHEMA,
mutationId: 'mutation-1',
});
assert.equal(result.statusCode, expected);
}
const errors = [
[new ClusterRunCancellationNotFoundError(), 404, 'run_not_found'],
[
new ClusterRunCancellationFenceRejectedError('authorization_changed'),
409,
'run_cancellation_fence_rejected',
],
[
new ClusterRunCancellationUnavailableError(),
503,
'run_cancellation_unavailable',
],
];
for (const [error, statusCode, code] of errors) {
const prepared = await pipeline({
async requestUserCancellation() { throw error; },
}).prepare(METADATA);
const result = await prepared.handle({
schema: CLUSTER_RUN_CANCELLATION_SCHEMA,
mutationId: 'mutation-1',
});
assert.equal(result.statusCode, statusCode);
assert.equal(result.body.code, code);
}
});
@@ -0,0 +1,146 @@
const assert = require('node:assert/strict');
const { test } = require('node:test');
const {
CLUSTER_CONTROL_RUN_EVENT_LIST_ROUTE,
createClusterControlRunEventListRoute,
} = require('@qinglong/cluster-control/run-routes');
const {
createClusterControlAdmissionPipeline,
} = require('@qinglong/cluster-control/admission');
const {
createClusterControlRouteRegistry,
} = require('@qinglong/cluster-control/routes');
function run(projectId = 'prj_default') {
return { id: 'run-1', projectId };
}
function event(sequence, overrides = {}) {
return {
id: `event-${sequence}`,
runId: 'run-1',
sequence,
type: `run.event.${sequence}`,
actorType: 'system',
actorId: 'private-actor',
payload: { secret: 'must-not-cross-projection' },
createdAtMs: 1_000 + sequence,
...overrides,
};
}
function authorized(query = {}, body = null) {
return {
projectId: 'prj_default',
request: { query, body },
};
}
test('publishes one reviewed bounded Run event list route', () => {
assert.deepEqual(CLUSTER_CONTROL_RUN_EVENT_LIST_ROUTE, {
method: 'GET',
path: '/api/v3/projects/{projectId}/runs/{runId}/events',
operationId: 'run.events.list',
permission: 'run.read',
projectParameter: 'projectId',
allowedQuery: ['after_sequence', 'limit'],
});
assert.throws(() => createClusterControlRunEventListRoute({}), TypeError);
});
test('returns the shared projection with exact sequence keyset input', async () => {
const calls = [];
const route = createClusterControlRunEventListRoute({
async findRunById(runId) {
calls.push(['run', runId]);
return run();
},
async listEvents(runId, input) {
calls.push(['events', runId, input]);
return [event(3), event(4)];
},
});
const result = await route.handle(
authorized({ after_sequence: ['2'], limit: ['1'] }),
{ runId: 'run-1' },
);
assert.deepEqual(calls, [
['run', 'run-1'],
['events', 'run-1', { afterSequence: 2, limit: 2 }],
]);
assert.deepEqual(result, {
statusCode: 200,
body: {
events: [
{
sequence: 3,
type: 'run.event.3',
actorType: 'system',
createdAtMs: 1_003,
},
],
hasMore: true,
nextAfterSequence: 3,
},
});
assert.equal(JSON.stringify(result).includes('private'), false);
assert.equal(JSON.stringify(result).includes('secret'), false);
});
test('masks Project mismatch and rejects malformed query before authentication', async () => {
const route = createClusterControlRunEventListRoute({
async findRunById() {
return run('prj_other');
},
async listEvents() {
throw new Error('must not read');
},
});
assert.deepEqual(await route.handle(authorized(), { runId: 'run-1' }), {
statusCode: 404,
body: { code: 'run_not_found' },
});
let authentications = 0;
const pipeline = createClusterControlAdmissionPipeline({
routes: createClusterControlRouteRegistry([route]),
authenticator: {
authenticate() {
authentications += 1;
return null;
},
},
policy: {
authorize() {
throw new Error('must not authorize');
},
},
audit: {
record() {
throw new Error('must not audit');
},
},
now: () => 10_000,
});
for (const query of [
{ after_sequence: ['02'] },
{ after_sequence: ['-1'] },
{ limit: ['65'] },
{ limit: ['1', '2'] },
]) {
await assert.rejects(
pipeline.prepare({
requestId: 'request-invalid-run-event-list',
method: 'GET',
path: '/api/v3/projects/prj_default/runs/run-1/events',
query,
headers: {},
signal: new AbortController().signal,
}),
(error) =>
error.statusCode === 400 && error.code === 'invalid_route_query',
);
}
assert.equal(authentications, 0);
});
@@ -0,0 +1,135 @@
const assert = require('node:assert/strict');
const { test } = require('node:test');
const {
CLUSTER_CONTROL_RUN_LIST_ROUTE,
createClusterControlRunListRoute,
} = require('@qinglong/cluster-control/run-routes');
const {
createClusterControlAdmissionPipeline,
} = require('@qinglong/cluster-control/admission');
const {
createClusterControlRouteRegistry,
} = require('@qinglong/cluster-control/routes');
function run(id, createdAtMs, overrides = {}) {
return {
id,
projectId: 'prj_default',
taskId: `task-${id}`,
taskRevision: 'revision-1',
triggerType: 'manual',
executionOrigin: 'manual',
executionOwner: 'runtime',
status: 'running',
version: 0,
eventSequence: 1,
priority: 0,
createdAtMs,
...overrides,
};
}
function authorized(query = {}, body = null) {
return {
projectId: 'prj_default',
request: { query, body },
};
}
test('publishes one reviewed bounded Run list route', () => {
assert.deepEqual(CLUSTER_CONTROL_RUN_LIST_ROUTE, {
method: 'GET',
path: '/api/v3/projects/{projectId}/runs',
operationId: 'run.list',
permission: 'run.read',
projectParameter: 'projectId',
allowedQuery: ['after_created_at_ms', 'after_run_id', 'limit'],
});
assert.throws(() => createClusterControlRunListRoute({}), TypeError);
});
test('parses an exact keyset page and returns the shared projection', async () => {
const calls = [];
const route = createClusterControlRunListRoute({
async listRunsByProject(query) {
calls.push(query);
return [run('run-a', 90)];
},
});
const result = await route.handle(
authorized({
limit: ['8'],
after_created_at_ms: ['100'],
after_run_id: ['run-b'],
}),
{},
);
assert.equal(result.statusCode, 200);
assert.equal(result.body.runs[0].id, 'run-a');
assert.deepEqual(calls, [
{
projectId: 'prj_default',
limit: 9,
after: { createdAtMs: 100, runId: 'run-b' },
},
]);
});
test('rejects malformed query and body and masks repository failures', async () => {
const route = createClusterControlRunListRoute({
async listRunsByProject() { throw new Error('offline'); },
});
for (const query of [
{ limit: ['08'] },
{ limit: ['65'] },
{ limit: ['8', '9'] },
{ after_run_id: ['run-a'] },
{ after_created_at_ms: ['-1'], after_run_id: ['run-a'] },
]) {
assert.deepEqual(await route.handle(authorized(query), {}), {
statusCode: 400,
body: { code: 'invalid_run_list_query' },
});
}
assert.deepEqual(await route.handle(authorized({}, { value: true }), {}), {
statusCode: 400,
body: { code: 'invalid_request_body' },
});
assert.deepEqual(await route.handle(authorized({}), {}), {
statusCode: 503,
body: { code: 'run_list_unavailable' },
});
});
test('rejects non-canonical pagination before authentication', async () => {
let authentications = 0;
const pipeline = createClusterControlAdmissionPipeline({
routes: createClusterControlRouteRegistry([
createClusterControlRunListRoute({
async listRunsByProject() { return []; },
}),
]),
authenticator: {
authenticate() {
authentications += 1;
return null;
},
},
policy: { authorize() { throw new Error('must not authorize'); } },
audit: { record() { throw new Error('must not audit'); } },
now: () => 10_000,
});
await assert.rejects(
pipeline.prepare({
requestId: 'request-invalid-run-list',
method: 'GET',
path: '/api/v3/projects/prj_default/runs',
query: { limit: ['08'] },
headers: {},
signal: new AbortController().signal,
}),
(error) => error.statusCode === 400 && error.code === 'invalid_route_query',
);
assert.equal(authentications, 0);
});
@@ -0,0 +1,300 @@
const assert = require('node:assert/strict');
const http = require('node:http');
const { test } = require('node:test');
const {
createClusterControlAdmissionPipeline,
} = require('@qinglong/cluster-control/admission');
const {
createClusterControlRouteRegistry,
} = require('@qinglong/cluster-control/routes');
const {
CLUSTER_CONTROL_RUN_READ_ROUTE,
createClusterControlRunReadRoute,
} = require('@qinglong/cluster-control/run-routes');
const {
startClusterControlHttpSurface,
} = require('@qinglong/cluster-control/http');
const NOW = 10_000;
const PRINCIPAL = Object.freeze({
subject: Object.freeze({ type: 'user', id: 'usr_viewer' }),
authenticationId: 'session:viewer',
authenticatedAtMs: 9_000,
expiresAtMs: 11_000,
assurance: 'single_factor',
});
const METADATA = Object.freeze({
requestId: 'request-run-read',
method: 'GET',
path: '/api/v3/projects/prj_default/runs/run_123',
query: Object.freeze({}),
headers: Object.freeze({ authorization: 'Bearer opaque' }),
signal: new AbortController().signal,
});
const EVIDENCE = Object.freeze({
contractName: 'control-core',
contractVersion: 5,
serverMajor: 16,
migrationIds: Object.freeze(['pg-0001', 'pg-0002']),
});
function httpRequest(address, path) {
return new Promise((resolve, reject) => {
const outgoing = http.request(
{
host: address.host,
port: address.port,
path,
headers: {
authorization: 'Bearer opaque',
connection: 'close',
},
},
(response) => {
const chunks = [];
response.on('data', (chunk) => chunks.push(chunk));
response.on('end', () => {
resolve({
statusCode: response.statusCode,
body: JSON.parse(Buffer.concat(chunks).toString('utf8')),
});
});
},
);
outgoing.once('error', reject);
outgoing.end();
});
}
function run(overrides = {}) {
return {
id: 'run_123',
projectId: 'prj_default',
taskId: 'task_1',
taskRevision: 'revision_7',
taskName: 'must not cross the wire',
taskSnapshotRef: 'secret-adjacent-ref',
triggerType: 'manual',
executionOrigin: 'manual',
executionOwner: 'runtime',
triggeredBy: 'private-user-id',
requestId: 'private-request-id',
status: 'running',
version: 4,
eventSequence: 6,
priority: 10,
inputRef: 'private-input-ref',
outputRef: 'private-output-ref',
createdAtMs: 1_000,
queuedAtMs: 2_000,
startedAtMs: 3_000,
errorCode: 'private-error-code',
errorSummary: 'private error detail',
...overrides,
};
}
function admission(repository, events = [], overrides = {}) {
return createClusterControlAdmissionPipeline({
routes: createClusterControlRouteRegistry([
createClusterControlRunReadRoute(repository),
]),
authenticator: {
authenticate() {
events.push('authenticate');
return PRINCIPAL;
},
},
policy: {
authorize(request) {
events.push(`authorize:${request.permission}:${request.projectId}`);
return {
effect: 'allow',
reasons: ['role_grant'],
fence: { projectVersion: 2, bindingVersion: 3 },
};
},
},
audit: {
record(record) {
events.push(`audit:${record.outcome}:${record.operationId}`);
},
},
now: () => NOW,
...overrides,
});
}
test('publishes one immutable reviewed Run read route', () => {
const route = createClusterControlRunReadRoute({
async findRunById() {
return null;
},
});
assert.deepEqual(CLUSTER_CONTROL_RUN_READ_ROUTE, {
method: 'GET',
path: '/api/v3/projects/{projectId}/runs/{runId}',
operationId: 'run.get',
permission: 'run.read',
projectParameter: 'projectId',
});
assert.equal(Object.isFrozen(route), true);
assert.throws(() => createClusterControlRunReadRoute({}), TypeError);
});
test('authenticates, authorizes and audits before one bounded Run lookup', async () => {
const events = [];
const pipeline = admission(
{
async findRunById(runId) {
events.push(`repository:${runId}`);
return run({ version: 0 });
},
},
events,
);
const prepared = await pipeline.prepare(METADATA);
assert.deepEqual(events, [
'authenticate',
'authorize:run.read:prj_default',
'audit:allowed:run.get',
]);
assert.deepEqual(await prepared.handle(null), {
statusCode: 200,
body: {
run: {
id: 'run_123',
projectId: 'prj_default',
taskId: 'task_1',
taskRevision: 'revision_7',
status: 'running',
version: 0,
eventSequence: 6,
priority: 10,
executionOrigin: 'manual',
executionOwner: 'runtime',
createdAtMs: 1_000,
queuedAtMs: 2_000,
startedAtMs: 3_000,
finishedAtMs: null,
},
},
});
assert.deepEqual(events.slice(-1), ['repository:run_123']);
assert.equal(
JSON.stringify(await prepared.handle(null)).includes('private'),
false,
);
});
test('serves the reviewed Run projection through the bounded HTTP surface', async (t) => {
const events = [];
const surface = await startClusterControlHttpSurface({
host: '127.0.0.1',
port: 0,
});
t.after(() => surface.close());
const dispose = surface.installAdmission(
EVIDENCE,
admission(
{
async findRunById(runId) {
events.push(`repository:${runId}`);
return run({ status: 'succeeded', finishedAtMs: 4_000 });
},
},
events,
),
);
t.after(() => dispose());
const result = await httpRequest(
surface.address,
'/api/v3/projects/prj_default/runs/run_123',
);
assert.equal(result.statusCode, 200);
assert.equal(result.body.run.id, 'run_123');
assert.equal(result.body.run.projectId, 'prj_default');
assert.equal(result.body.run.status, 'succeeded');
assert.equal(result.body.run.finishedAtMs, 4_000);
assert.equal(JSON.stringify(result).includes('private'), false);
assert.deepEqual(events, [
'authenticate',
'authorize:run.read:prj_default',
'audit:allowed:run.get',
'repository:run_123',
]);
});
test('does not query storage when authentication fails', async () => {
let queries = 0;
const pipeline = admission(
{
async findRunById() {
queries += 1;
return run();
},
},
[],
{ authenticator: { authenticate: () => null } },
);
await assert.rejects(
pipeline.prepare(METADATA),
(error) =>
error.statusCode === 401 && error.code === 'authentication_required',
);
assert.equal(queries, 0);
});
test('masks absent, cross-Project, corrupt and unavailable Run records', async () => {
for (const [record, expected] of [
[null, { statusCode: 404, body: { code: 'run_not_found' } }],
[
run({ projectId: 'prj_other' }),
{ statusCode: 404, body: { code: 'run_not_found' } },
],
[
run({ taskRevision: '\ncorrupt' }),
{ statusCode: 503, body: { code: 'run_query_unavailable' } },
],
[
{ id: 'run_123' },
{ statusCode: 503, body: { code: 'run_query_unavailable' } },
],
]) {
const prepared = await admission({
async findRunById() {
return record;
},
}).prepare(METADATA);
assert.deepEqual(await prepared.handle(null), expected);
}
const unavailable = await admission({
async findRunById() {
throw new Error('postgresql secret detail');
},
}).prepare(METADATA);
const response = await unavailable.handle(null);
assert.deepEqual(response, {
statusCode: 503,
body: { code: 'run_query_unavailable' },
});
assert.equal(JSON.stringify(response).includes('postgresql'), false);
});
test('rejects a GET body without touching the Run repository', async () => {
let queries = 0;
const prepared = await admission({
async findRunById() {
queries += 1;
return run();
},
}).prepare(METADATA);
assert.deepEqual(await prepared.handle({ unexpected: true }), {
statusCode: 400,
body: { code: 'invalid_request_body' },
});
assert.equal(queries, 0);
});
@@ -0,0 +1,156 @@
const assert = require('node:assert/strict');
const { test } = require('node:test');
const {
CLUSTER_CONTROL_RUN_STEP_LIST_ROUTE,
createClusterControlRunStepListRoute,
} = require('@qinglong/cluster-control/run-routes');
const {
createClusterControlAdmissionPipeline,
} = require('@qinglong/cluster-control/admission');
const {
createClusterControlRouteRegistry,
} = require('@qinglong/cluster-control/routes');
const {
createStepRunRecord,
} = require('../../ql3-runtime-core/dist/run/stepRun.js');
function run(projectId = 'prj_default') {
return { id: 'run-1', projectId };
}
function step(id, stepKey) {
return createStepRunRecord({
id,
runId: 'run-1',
parentStepRunId: 'step-parent',
stepKey,
kind: 'tool',
definitionRef: 'tool:private.internal@1.0.0',
definitionDigest: 'a'.repeat(64),
required: true,
initialStatus: 'ready',
inputRef: 'artifact:private-input',
mutationId: `create-${id}`,
createdAtMs: 1_000,
});
}
function authorized(query = {}, body = null) {
return { projectId: 'prj_default', request: { query, body } };
}
test('publishes one reviewed bounded Run Step list route', () => {
assert.deepEqual(CLUSTER_CONTROL_RUN_STEP_LIST_ROUTE, {
method: 'GET',
path: '/api/v3/projects/{projectId}/runs/{runId}/steps',
operationId: 'run.steps.list',
permission: 'run.read',
projectParameter: 'projectId',
allowedQuery: ['after_step_key', 'after_step_run_id', 'limit'],
});
assert.throws(() => createClusterControlRunStepListRoute({}, {}), TypeError);
});
test('returns the shared projection with the paired Step keyset cursor', async () => {
const calls = [];
const first = step('step-1', 'build');
const second = step('step-2', 'deploy');
const route = createClusterControlRunStepListRoute(
{
async findRunById(runId) {
calls.push(['run', runId]);
return run();
},
},
{
async listByRun(query) {
calls.push(['steps', query]);
return {
stepRuns: [first, second],
truncated: true,
next: { stepKey: second.stepKey, id: second.id },
};
},
},
);
const result = await route.handle(
authorized({
after_step_key: ['admit'],
after_step_run_id: ['step-0'],
limit: ['2'],
}),
{ runId: 'run-1' },
);
assert.deepEqual(calls[1], [
'steps',
{
runId: 'run-1',
limit: 2,
after: { stepKey: 'admit', id: 'step-0' },
},
]);
assert.equal(result.statusCode, 200);
assert.equal(result.body.steps.length, 2);
assert.deepEqual(result.body.next, {
stepKey: 'deploy',
stepRunId: 'step-2',
});
assert.equal(JSON.stringify(result).includes('private'), false);
});
test('rejects an unpaired or malformed cursor before authentication', async () => {
const route = createClusterControlRunStepListRoute(
{
async findRunById() {
return run();
},
},
{
async listByRun() {
return { stepRuns: [], truncated: false };
},
},
);
let authentications = 0;
const pipeline = createClusterControlAdmissionPipeline({
routes: createClusterControlRouteRegistry([route]),
authenticator: {
authenticate() {
authentications += 1;
return null;
},
},
policy: {
authorize() {
throw new Error('must not authorize');
},
},
audit: {
record() {
throw new Error('must not audit');
},
},
now: () => 10_000,
});
for (const query of [
{ after_step_key: ['build'] },
{ after_step_run_id: ['step-1'] },
{ after_step_key: ['bad value'], after_step_run_id: ['step-1'] },
{ after_step_key: ['build'], after_step_run_id: ['step-1'], limit: ['65'] },
]) {
await assert.rejects(
pipeline.prepare({
requestId: 'request-invalid-run-step-list',
method: 'GET',
path: '/api/v3/projects/prj_default/runs/run-1/steps',
query,
headers: {},
signal: new AbortController().signal,
}),
(error) =>
error.statusCode === 400 && error.code === 'invalid_route_query',
);
}
assert.equal(authentications, 0);
});
@@ -0,0 +1,115 @@
'use strict';
const assert = require('node:assert/strict');
const { test } = require('node:test');
const {
ClusterRuntimeSchedulerCoordinator,
} = require('../dist/scheduling/runtimeScheduler');
function schedulerSummary() {
return Object.freeze({
firstClaimAcquiredAtMs: null,
lastClaimAcquiredAtMs: null,
claimed: 0,
initialized: 0,
skipped: 0,
admitted: 0,
raced: 0,
saturated: false,
});
}
test('orders recovery and lost retry before the existing scheduler cadence', async () => {
const calls = [];
const coordinator = new ClusterRuntimeSchedulerCoordinator(
{
async reconcile() {
calls.push('recovery');
return { safe: true, remaining: 0, failed: 0 };
},
},
{
async reconcile() {
calls.push('lost-retry');
return {
scanned: 1,
scheduled: 1,
requeued: 0,
failed: 0,
raced: 0,
hasMore: false,
};
},
},
{
async scheduleOnce() {
calls.push('schedule');
return schedulerSummary();
},
},
);
assert.deepEqual(await coordinator.scheduleOnce(), schedulerSummary());
assert.deepEqual(calls, ['recovery', 'lost-retry', 'schedule']);
assert.deepEqual(coordinator.latestMaintenanceSummary(), {
recovery: { safe: true, remaining: 0, failed: 0 },
lostRetry: {
scanned: 1,
scheduled: 1,
requeued: 0,
failed: 0,
raced: 0,
hasMore: false,
},
});
});
test('coalesces overlapping cadence calls and fails closed before scheduling', async () => {
let release;
let recoveryCalls = 0;
let schedulerCalls = 0;
const coordinator = new ClusterRuntimeSchedulerCoordinator(
{
async reconcile() {
recoveryCalls += 1;
await new Promise((resolve) => {
release = resolve;
});
throw new Error('recovery unavailable');
},
},
{
async reconcile() {
throw new Error('lost retry must not run');
},
},
{
async scheduleOnce() {
schedulerCalls += 1;
return schedulerSummary();
},
},
);
const first = coordinator.scheduleOnce();
const second = coordinator.scheduleOnce();
assert.equal(first, second);
while (!release) await new Promise((resolve) => setImmediate(resolve));
release();
await assert.rejects(first, /recovery unavailable/);
assert.equal(recoveryCalls, 1);
assert.equal(schedulerCalls, 0);
assert.equal(coordinator.latestMaintenanceSummary(), undefined);
});
test('rejects incomplete maintenance capabilities', () => {
assert.throws(
() =>
new ClusterRuntimeSchedulerCoordinator(
{},
{ reconcile() {} },
{ scheduleOnce() {} },
),
/runtime scheduler coordinator is invalid/,
);
});
@@ -0,0 +1,98 @@
'use strict';
const assert = require('node:assert/strict');
const { createHash } = require('node:crypto');
const { test } = require('node:test');
const {
CreateBucketCommand,
DeleteBucketCommand,
DeleteObjectsCommand,
ListObjectsV2Command,
S3Client,
} = require('@aws-sdk/client-s3');
const {
S3ClusterRemoteWorkerArtifactStore,
S3ClusterRemoteWorkerArtifactStoreError,
} = require('@qinglong/cluster-control/s3-artifact-store');
const endpoint = process.env.QL3_TEST_S3_ENDPOINT;
const accessKeyId = process.env.QL3_TEST_S3_ACCESS_KEY_ID;
const secretAccessKey = process.env.QL3_TEST_S3_SECRET_ACCESS_KEY;
test('real S3-compatible service preserves immutable Artifact evidence', {
skip: endpoint && accessKeyId && secretAccessKey
? false
: 'requires QL3_TEST_S3_ENDPOINT and credentials',
}, async () => {
const client = new S3Client({
endpoint,
region: 'us-east-1',
forcePathStyle: true,
credentials: { accessKeyId, secretAccessKey },
});
const bucket = `ql3-artifact-${process.pid}-${Date.now()}`.slice(0, 63);
const command = Object.freeze({
projectId: 'project-s3-integration',
runId: 'run-s3-integration',
attemptId: 'attempt-s3-integration',
logArtifactId: `wlog-${'c'.repeat(30)}`,
byteLength: 17,
truncated: true,
});
const content = Buffer.from('real object bytes');
const body = (value) => Object.freeze({
async *[Symbol.asyncIterator]() {
yield value.subarray(0, 4);
yield value.subarray(4);
},
});
try {
await client.send(new CreateBucketCommand({ Bucket: bucket }));
const store = new S3ClusterRemoteWorkerArtifactStore({
client,
bucket,
prefix: 'qinglong/integration',
encryption: { mode: 's3' },
});
const stored = await store.put(command, body(content));
assert.equal(stored.status, 'stored');
assert.equal(
stored.sha256,
createHash('sha256').update(content).digest('hex'),
);
const replay = await store.put(command, body(content));
assert.equal(replay.status, 'already_stored');
await assert.rejects(
store.put(command, body(Buffer.from('REAL OBJECT BYTES'))),
(error) =>
error instanceof S3ClusterRemoteWorkerArtifactStoreError &&
error.reason === 'integrity_mismatch',
);
const objects = await client.send(new ListObjectsV2Command({
Bucket: bucket,
Prefix: 'qinglong/integration/',
}));
assert.equal(objects.KeyCount, 1);
assert.match(objects.Contents[0].Key, /\/objects\//);
} finally {
try {
const objects = await client.send(new ListObjectsV2Command({
Bucket: bucket,
}));
if (objects.Contents?.length) {
await client.send(new DeleteObjectsCommand({
Bucket: bucket,
Delete: {
Objects: objects.Contents.map(({ Key }) => ({ Key })),
Quiet: true,
},
}));
}
await client.send(new DeleteBucketCommand({ Bucket: bucket }));
} catch {
// Preserve the integration assertion; the ephemeral container is removed.
}
client.destroy();
}
});
@@ -0,0 +1,388 @@
'use strict';
const assert = require('node:assert/strict');
const { createHash } = require('node:crypto');
const { test } = require('node:test');
const {
CopyObjectCommand,
DeleteObjectCommand,
HeadObjectCommand,
PutObjectCommand,
} = require('@aws-sdk/client-s3');
const {
S3ClusterRemoteWorkerArtifactStore,
S3ClusterRemoteWorkerArtifactStoreError,
} = require('@qinglong/cluster-control/s3-artifact-store');
const TEMPORARY_ID = '018f62f6-7b41-4e4f-8cf8-6f38888629a2';
const COMMAND = Object.freeze({
projectId: 'project-1',
runId: 'run-1',
attemptId: 'attempt-1',
logArtifactId: `wlog-${'a'.repeat(30)}`,
byteLength: 11,
truncated: false,
});
const CONTENT = Buffer.from('hello world');
const CONTENT_SHA256 = createHash('sha256').update(CONTENT).digest('hex');
const LOOKUP = Object.freeze({
projectId: COMMAND.projectId,
runId: COMMAND.runId,
attemptId: COMMAND.attemptId,
logArtifactId: COMMAND.logArtifactId,
});
function checksum(content) {
return createHash('sha256').update(content).digest('base64');
}
function notFound() {
const error = new Error('not found');
error.name = 'NotFound';
error.$metadata = { httpStatusCode: 404 };
return error;
}
class MemoryS3Client {
constructor(options = {}) {
this.options = options;
this.objects = new Map();
this.commands = [];
}
async send(command) {
this.commands.push(command);
const input = command.input;
if (command instanceof HeadObjectCommand) {
const object = this.objects.get(input.Key);
if (!object) throw notFound();
const metadata = { ...object.metadata };
if (this.options.corruptFinalMetadata && input.Key.includes('/objects/')) {
metadata['ql3-content-sha256'] = '0'.repeat(64);
}
return {
ContentLength: object.content.byteLength,
ContentType: object.contentType,
ChecksumSHA256: this.options.corruptFinalChecksum &&
input.Key.includes('/objects/')
? Buffer.alloc(32, 9).toString('base64')
: checksum(object.content),
Metadata: metadata,
};
}
if (command instanceof PutObjectCommand) {
assert.equal(input.IfNoneMatch, '*');
assert.equal(input.ChecksumAlgorithm, 'SHA256');
assert.equal(
input.ServerSideEncryption,
this.options.expectedEncryption ?? 'AES256',
);
if (this.options.expectedKmsKeyId) {
assert.equal(input.SSEKMSKeyId, this.options.expectedKmsKeyId);
}
if (this.objects.has(input.Key)) {
const error = new Error('precondition failed');
error.$metadata = { httpStatusCode: 412 };
throw error;
}
const chunks = [];
for await (const chunk of input.Body) chunks.push(Buffer.from(chunk));
const content = Buffer.concat(chunks);
this.objects.set(input.Key, {
content,
contentType: input.ContentType,
metadata: { ...input.Metadata },
});
if (this.options.throwAfterPut) throw new Error('lost put response');
return { ChecksumSHA256: checksum(content) };
}
if (command instanceof CopyObjectCommand) {
assert.equal(input.IfNoneMatch, '*');
assert.equal(input.MetadataDirective, 'REPLACE');
assert.equal(input.ChecksumAlgorithm, 'SHA256');
const sourceKey = decodeURIComponent(input.CopySource)
.split('/')
.slice(1)
.join('/');
const source = this.objects.get(sourceKey);
if (!source) throw notFound();
const final = {
content: Buffer.from(source.content),
contentType: input.ContentType,
metadata: { ...input.Metadata },
};
if (this.options.raceOnCopy && !this.objects.has(input.Key)) {
this.objects.set(input.Key, final);
const error = new Error('conditional request conflict');
error.$metadata = { httpStatusCode: 409 };
throw error;
}
if (this.objects.has(input.Key)) {
const error = new Error('precondition failed');
error.$metadata = { httpStatusCode: 412 };
throw error;
}
this.objects.set(input.Key, final);
if (this.options.throwAfterCopy) throw new Error('lost copy response');
return { CopyObjectResult: { ChecksumSHA256: checksum(final.content) } };
}
if (command instanceof DeleteObjectCommand) {
if (this.options.failDelete) throw new Error('delete unavailable');
this.objects.delete(input.Key);
return {};
}
throw new Error(`unexpected command: ${command.constructor.name}`);
}
}
function store(client, overrides = {}) {
return new S3ClusterRemoteWorkerArtifactStore({
client,
bucket: 'ql3-artifacts-test',
prefix: 'tenant-a/worker-artifacts',
encryption: { mode: 's3' },
createTemporaryId: () => TEMPORARY_ID,
...overrides,
});
}
function chunks(content = CONTENT, observed) {
return Object.freeze({
async *[Symbol.asyncIterator]() {
yield content.subarray(0, 3);
yield content.subarray(3, 7);
yield content.subarray(7);
if (observed) observed.complete = true;
},
});
}
function permanentKey(client) {
return [...client.objects.keys()].find((key) => key.includes('/objects/'));
}
test('streams to a checksummed temporary object then conditionally promotes it', async () => {
const client = new MemoryS3Client();
const adapter = store(client);
const receipt = await adapter.put(COMMAND, chunks());
assert.deepEqual(receipt, {
status: 'stored',
...COMMAND,
sha256: CONTENT_SHA256,
});
assert.deepEqual(
client.commands.map((command) => command.constructor.name),
[
'HeadObjectCommand',
'PutObjectCommand',
'HeadObjectCommand',
'CopyObjectCommand',
'HeadObjectCommand',
'DeleteObjectCommand',
],
);
const key = permanentKey(client);
assert.match(key, /^tenant-a\/worker-artifacts\/objects\/[a-f0-9]{2}\/[a-f0-9]{64}$/);
assert.equal(key.includes(COMMAND.runId), false);
assert.equal(client.objects.size, 1);
const copy = client.commands.find((command) => command instanceof CopyObjectCommand);
assert.equal(copy.input.Metadata['ql3-content-sha256'], CONTENT_SHA256);
assert.equal(JSON.stringify(copy.input.Metadata).includes(COMMAND.projectId), false);
assert.equal(JSON.stringify(copy.input.Metadata).includes(COMMAND.runId), false);
const inspected = await adapter.inspect(LOOKUP);
assert.deepEqual(inspected, { ...receipt, status: 'already_stored' });
});
test('exact replay consumes and hashes the whole body without another write', async () => {
const client = new MemoryS3Client();
const adapter = store(client);
await adapter.put(COMMAND, chunks());
client.commands.length = 0;
const observed = { complete: false };
const replay = await adapter.put(COMMAND, chunks(CONTENT, observed));
assert.equal(replay.status, 'already_stored');
assert.equal(observed.complete, true);
assert.deepEqual(
client.commands.map((command) => command.constructor.name),
['HeadObjectCommand'],
);
await assert.rejects(
adapter.put(COMMAND, chunks(Buffer.from('HELLO WORLD'))),
(error) =>
error instanceof S3ClusterRemoteWorkerArtifactStoreError &&
error.reason === 'integrity_mismatch',
);
});
test('resolves a concurrent conditional-copy winner by immutable inspect', async () => {
const client = new MemoryS3Client({ raceOnCopy: true });
const receipt = await store(client).put(COMMAND, chunks());
assert.equal(receipt.status, 'already_stored');
assert.equal(receipt.sha256, CONTENT_SHA256);
assert.equal(client.objects.size, 1);
});
test('recovers lost put and copy responses only from checksum evidence', async () => {
for (const [option, expectedStatus] of [
['throwAfterPut', 'stored'],
['throwAfterCopy', 'already_stored'],
]) {
const client = new MemoryS3Client({ [option]: true });
const receipt = await store(client).put(COMMAND, chunks());
assert.equal(receipt.status, expectedStatus);
assert.equal(receipt.sha256, CONTENT_SHA256);
assert.equal(client.objects.size, 1);
}
});
test('rejects corrupt metadata, checksum, short and oversized content', async () => {
for (const option of ['corruptFinalMetadata', 'corruptFinalChecksum']) {
const client = new MemoryS3Client({ [option]: true });
await assert.rejects(
store(client).put(COMMAND, chunks()),
(error) =>
error instanceof S3ClusterRemoteWorkerArtifactStoreError &&
error.reason === 'integrity_mismatch',
);
}
for (const content of [Buffer.from('short'), Buffer.from('hello world!')]) {
const client = new MemoryS3Client();
await assert.rejects(
store(client).put(COMMAND, chunks(content)),
(error) => error instanceof S3ClusterRemoteWorkerArtifactStoreError,
);
assert.equal(permanentKey(client), undefined);
}
});
test('temporary cleanup failure is diagnostic and never reverses promotion', async () => {
const diagnostics = [];
const client = new MemoryS3Client({ failDelete: true });
const receipt = await store(client, {
onDiagnostic(error, context) {
diagnostics.push([error.message, context.operation]);
},
}).put(COMMAND, chunks());
assert.equal(receipt.status, 'stored');
assert.deepEqual(diagnostics, [[
'delete unavailable',
'temporary_object_cleanup',
]]);
assert.equal(client.objects.size, 2);
});
test('requires exact bucket, prefix, encryption and temporary ID configuration', async () => {
const client = new MemoryS3Client();
assert.throws(
() => new S3ClusterRemoteWorkerArtifactStore({
client,
bucket: 'Invalid_Bucket',
encryption: { mode: 's3' },
}),
/bucket is invalid/,
);
assert.throws(
() => new S3ClusterRemoteWorkerArtifactStore({
client,
bucket: 'valid-bucket',
prefix: '../escape',
encryption: { mode: 's3' },
}),
/prefix is invalid/,
);
assert.throws(
() => new S3ClusterRemoteWorkerArtifactStore({
client,
bucket: 'valid-bucket',
encryption: { mode: 'kms' },
}),
/encryption is invalid/,
);
await assert.rejects(
store(client, { createTemporaryId: () => '../invalid' }).put(
COMMAND,
chunks(),
),
(error) =>
error instanceof S3ClusterRemoteWorkerArtifactStoreError &&
error.reason === 'unavailable',
);
});
test('supports an empty immutable Artifact without synthesizing a chunk', async () => {
const client = new MemoryS3Client();
const command = {
...COMMAND,
logArtifactId: `wlog-${'b'.repeat(30)}`,
byteLength: 0,
truncated: undefined,
};
delete command.truncated;
const receipt = await store(client).put(command, {
async *[Symbol.asyncIterator]() {},
});
assert.equal(receipt.byteLength, 0);
assert.equal(receipt.sha256, createHash('sha256').digest('hex'));
assert.equal(Object.hasOwn(receipt, 'truncated'), false);
});
test('propagates KMS and expected-owner fences to both sides of promotion', async () => {
const keyId = 'arn:aws:kms:us-east-1:123456789012:key/test';
const client = new MemoryS3Client({
expectedEncryption: 'aws:kms',
expectedKmsKeyId: keyId,
});
await store(client, {
expectedBucketOwner: '123456789012',
encryption: { mode: 'kms', keyId },
}).put(COMMAND, chunks());
for (const command of client.commands) {
assert.equal(command.input.ExpectedBucketOwner, '123456789012');
}
const copy = client.commands.find(
(command) => command instanceof CopyObjectCommand,
);
assert.equal(copy.input.CopySourceExpectedBucketOwner, '123456789012');
assert.equal(copy.input.ServerSideEncryption, 'aws:kms');
assert.equal(copy.input.SSEKMSKeyId, keyId);
});
test('never deletes a colliding temporary object it cannot prove it owns', async () => {
const client = new MemoryS3Client();
const temporaryKey =
`tenant-a/worker-artifacts/temporary/${TEMPORARY_ID}`;
client.objects.set(temporaryKey, {
content: Buffer.from('other operation'),
contentType: 'application/octet-stream',
metadata: { 'ql3-schema': 'other' },
});
await assert.rejects(
store(client).put(COMMAND, chunks()),
(error) =>
error instanceof S3ClusterRemoteWorkerArtifactStoreError &&
error.reason === 'unavailable',
);
assert.equal(client.objects.has(temporaryKey), true);
assert.equal(
client.commands.some((command) => command instanceof DeleteObjectCommand),
false,
);
});
test('a pre-aborted request performs no object-store operation', async () => {
const client = new MemoryS3Client();
const controller = new AbortController();
const reason = new Error('stopping');
controller.abort(reason);
await assert.rejects(
store(client).put(COMMAND, chunks(), controller.signal),
(error) => error === reason,
);
assert.equal(client.commands.length, 0);
});
@@ -0,0 +1,41 @@
const assert = require('node:assert/strict');
const path = require('node:path');
const { spawnSync } = require('node:child_process');
const { test } = require('node:test');
function inspectEntrypoint(specifier) {
const packageDirectory = path.resolve(__dirname, '..');
const script = `
const exported = require(${JSON.stringify(specifier)});
const loaded = Object.keys(require.cache).map((file) => file.replaceAll('\\\\', '/'));
process.stdout.write(JSON.stringify({
hasStore: typeof exported.S3ClusterRemoteWorkerArtifactStore === 'function',
loadedAwsSdk: loaded.some((file) => file.includes('/@aws-sdk/')),
}));
`;
const result = spawnSync(process.execPath, ['-e', script], {
cwd: packageDirectory,
encoding: 'utf8',
});
assert.equal(result.status, 0, result.stderr);
return JSON.parse(result.stdout);
}
test('default and production entrypoints do not load the S3 client', () => {
for (const specifier of [
'@qinglong/cluster-control',
'@qinglong/cluster-control/production',
]) {
const report = inspectEntrypoint(specifier);
assert.equal(report.hasStore, false, specifier);
assert.equal(report.loadedAwsSdk, false, specifier);
}
});
test('S3 artifact store is reachable only through its explicit subpath', () => {
const report = inspectEntrypoint(
'@qinglong/cluster-control/s3-artifact-store',
);
assert.equal(report.hasStore, true);
assert.equal(report.loadedAwsSdk, true);
});
@@ -0,0 +1,246 @@
const assert = require('node:assert/strict');
const { test } = require('node:test');
const {
ClusterSchedulerCoordinator,
ClusterSchedulerLifecycle,
} = require('../dist/scheduling/scheduler');
function nextMinute(schedule, afterMs) {
if (schedule.expression !== '* * * * *' || schedule.timezone !== 'UTC') {
throw new Error('unsupported test schedule');
}
return Math.floor(afterMs / 60_000 + 1) * 60_000;
}
function claim(overrides = {}) {
return {
projectId: 'default',
triggerId: 'trigger-1',
triggerRevision: 1,
triggerContentDigest: 'a'.repeat(64),
triggerUpdatedAtMs: 1,
taskId: 'task-1',
taskRevision: 1,
taskContentDigest: 'b'.repeat(64),
expression: '* * * * *',
timezone: 'UTC',
misfirePolicy: 'skip',
stateVersion: 1,
nextFireAtMs: 60_000,
claimOwner: 'scheduler-a',
claimToken: '019f7800-0000-7000-8000-000000000001',
claimVersion: 1,
claimAcquiredAtMs: 61_000,
claimExpiresAtMs: 91_000,
...overrides,
};
}
function idFactory() {
let value = 0;
return () => `019f7800-0000-7000-8000-${String(++value).padStart(12, '0')}`;
}
test('claims a bounded cycle and notifies only fenced admissions', async () => {
const claims = [
claim(),
claim({
triggerId: 'trigger-2',
claimToken: '019f7800-0000-7000-8000-000000000002',
claimAcquiredAtMs: 62_000,
claimExpiresAtMs: 92_000,
}),
];
const claimCommands = [];
const commits = [];
const notified = [];
const coordinator = new ClusterSchedulerCoordinator(
{
async claimNextClusterSchedule(command) {
claimCommands.push(command);
const next = claims.shift();
return next
? {
...next,
claimOwner: command.ownerId,
claimToken: command.claimToken,
}
: null;
},
async commitClusterScheduleDecision(command) {
commits.push(command);
if (commits.length === 2) return { status: 'raced' };
return {
status: 'admitted',
disposition: 'admit',
runId: command.runId,
attemptId: command.attemptId,
};
},
},
{
ownerId: 'scheduler-a',
claimLeaseMs: 30_000,
maxClaimsPerCycle: 4,
misfireGraceMs: 5_000,
nextOccurrence: nextMinute,
createId: idFactory(),
onAdmitted: (runId, attemptId) => notified.push([runId, attemptId]),
},
);
assert.deepEqual(await coordinator.scheduleOnce(), {
firstClaimAcquiredAtMs: 61_000,
lastClaimAcquiredAtMs: 62_000,
claimed: 2,
initialized: 0,
skipped: 0,
admitted: 1,
raced: 1,
saturated: false,
});
assert.equal(claimCommands.length, 3);
assert.equal(
claimCommands.every(({ ownerId }) => ownerId === 'scheduler-a'),
true,
);
assert.equal(commits.length, 2);
assert.deepEqual(notified, [[commits[0].runId, commits[0].attemptId]]);
});
test('does not allocate Run identities for a skipped occurrence', async () => {
let claimed = false;
const commands = [];
let allocations = 0;
const skipped = claim({
nextFireAtMs: 60_000,
claimAcquiredAtMs: 900_000,
claimExpiresAtMs: 930_000,
});
const coordinator = new ClusterSchedulerCoordinator(
{
async claimNextClusterSchedule(command) {
if (claimed) return null;
claimed = true;
return {
...skipped,
claimOwner: command.ownerId,
claimToken: command.claimToken,
};
},
async commitClusterScheduleDecision(command) {
commands.push(command);
return { status: 'advanced', disposition: 'skip' };
},
},
{
ownerId: 'scheduler-a',
misfireGraceMs: 0,
nextOccurrence: nextMinute,
createId() {
allocations += 1;
return `019f7800-0000-7000-8000-${String(allocations).padStart(
12,
'0',
)}`;
},
},
);
const summary = await coordinator.scheduleOnce();
assert.equal(summary.skipped, 1);
assert.equal(allocations, 2);
assert.equal(commands[0].runId, undefined);
assert.equal(commands[0].attemptId, undefined);
});
test('marks a cycle saturated at its hard claim budget', async () => {
let version = 0;
const coordinator = new ClusterSchedulerCoordinator(
{
async claimNextClusterSchedule(command) {
version += 1;
return claim({
stateVersion: version,
claimVersion: version,
claimOwner: command.ownerId,
claimToken: command.claimToken,
});
},
async commitClusterScheduleDecision(command) {
return {
status: 'admitted',
disposition: 'admit',
runId: command.runId,
attemptId: command.attemptId,
};
},
},
{
ownerId: 'scheduler-a',
maxClaimsPerCycle: 2,
nextOccurrence: nextMinute,
createId: idFactory(),
},
);
const summary = await coordinator.scheduleOnce();
assert.equal(summary.claimed, 2);
assert.equal(summary.saturated, true);
});
test('rejects a node-local clock as scheduler authority', () => {
assert.throws(
() =>
new ClusterSchedulerCoordinator(
{
async claimNextClusterSchedule() {
return null;
},
async commitClusterScheduleDecision() {
return { status: 'raced' };
},
},
{
ownerId: 'scheduler-a',
clock: () => 1,
},
),
/options are invalid/,
);
});
test('lifecycle coalesces work and drains without overlapping cycles', async () => {
let calls = 0;
let release;
const pending = new Promise((resolve) => {
release = resolve;
});
const summary = {
firstClaimAcquiredAtMs: null,
lastClaimAcquiredAtMs: null,
claimed: 0,
initialized: 0,
skipped: 0,
admitted: 0,
raced: 0,
saturated: false,
};
const lifecycle = new ClusterSchedulerLifecycle(
{
async scheduleOnce() {
calls += 1;
await pending;
return summary;
},
},
{ intervalMs: 250, stopTimeoutMs: 1_000 },
);
assert.equal(lifecycle.start(), 'started');
const first = lifecycle.runOnce();
assert.equal(lifecycle.runOnce(), first);
const stopping = lifecycle.stopAndDrain();
release();
assert.deepEqual(await first, summary);
assert.deepEqual(await stopping, { status: 'stopped' });
assert.equal(calls, 1);
await assert.rejects(lifecycle.runOnce(), /stopping/);
});
@@ -0,0 +1,155 @@
const assert = require('node:assert/strict');
const { test } = require('node:test');
const {
CLUSTER_CONTROL_TASK_LIST_ROUTE,
createClusterControlTaskListRoute,
} = require('@qinglong/cluster-control/task-routes');
const {
createClusterControlAdmissionPipeline,
} = require('@qinglong/cluster-control/admission');
const {
createClusterControlRouteRegistry,
} = require('@qinglong/cluster-control/routes');
function task(taskId, overrides = {}) {
return {
projectId: 'prj_default',
taskId,
revision: 2,
name: `Task ${taskId}`,
description: 'secret-adjacent',
kind: 'command',
spec: { schema: 'qinglong/command@v1', config: { command: ['private'] } },
labels: { private: 'value' },
enabled: true,
mutationId: 'mutation-private',
contentDigest: 'digest-private',
createdAtMs: 10,
updatedAtMs: 20,
...overrides,
};
}
function authorized(query = {}, body = null) {
return {
projectId: 'prj_default',
request: { query, body },
};
}
test('publishes one reviewed bounded Task list route', () => {
assert.deepEqual(CLUSTER_CONTROL_TASK_LIST_ROUTE, {
method: 'GET',
path: '/api/v3/projects/{projectId}/tasks',
operationId: 'task.list',
permission: 'task.read',
projectParameter: 'projectId',
allowedQuery: ['after_task_id', 'limit'],
});
assert.throws(() => createClusterControlTaskListRoute({}), TypeError);
});
test('parses an exact keyset page and returns the shared projection', async () => {
const calls = [];
const route = createClusterControlTaskListRoute({
async listTaskDefinitions(query) {
calls.push(query);
return {
definitions: [task('task-b', { enabled: false })],
truncated: true,
next: { taskId: 'task-b' },
};
},
});
const result = await route.handle(
authorized({ limit: ['8'], after_task_id: ['task-a'] }),
{},
);
assert.deepEqual(calls, [
{
projectId: 'prj_default',
limit: 8,
after: { taskId: 'task-a' },
},
]);
assert.deepEqual(result, {
statusCode: 200,
body: {
tasks: [
{
taskId: 'task-b',
revision: 2,
name: 'Task task-b',
kind: 'command',
specSchema: 'qinglong/command@v1',
enabled: false,
updatedAtMs: 20,
},
],
hasMore: true,
next: { taskId: 'task-b' },
},
});
assert.equal(JSON.stringify(result).includes('secret-adjacent'), false);
assert.equal(JSON.stringify(result).includes('private'), false);
});
test('rejects malformed query and body and masks repository failures', async () => {
const route = createClusterControlTaskListRoute({
async listTaskDefinitions() { throw new Error('offline'); },
});
for (const query of [
{ limit: ['08'] },
{ limit: ['65'] },
{ limit: ['8', '9'] },
{ after_task_id: ['-bad'] },
]) {
assert.deepEqual(await route.handle(authorized(query), {}), {
statusCode: 400,
body: { code: 'invalid_task_list_query' },
});
}
assert.deepEqual(await route.handle(authorized({}, { value: true }), {}), {
statusCode: 400,
body: { code: 'invalid_request_body' },
});
assert.deepEqual(await route.handle(authorized({}), {}), {
statusCode: 503,
body: { code: 'task_list_unavailable' },
});
});
test('rejects non-canonical pagination before authentication', async () => {
let authentications = 0;
const pipeline = createClusterControlAdmissionPipeline({
routes: createClusterControlRouteRegistry([
createClusterControlTaskListRoute({
async listTaskDefinitions() {
return { definitions: [], truncated: false };
},
}),
]),
authenticator: {
authenticate() {
authentications += 1;
return null;
},
},
policy: { authorize() { throw new Error('must not authorize'); } },
audit: { record() { throw new Error('must not audit'); } },
now: () => 10_000,
});
await assert.rejects(
pipeline.prepare({
requestId: 'request-invalid-task-list',
method: 'GET',
path: '/api/v3/projects/prj_default/tasks',
query: { limit: ['08'] },
headers: {},
signal: new AbortController().signal,
}),
(error) => error.statusCode === 400 && error.code === 'invalid_route_query',
);
assert.equal(authentications, 0);
});
@@ -0,0 +1,150 @@
const assert = require('node:assert/strict');
const { test } = require('node:test');
const {
CLUSTER_CONTROL_TASK_READ_ROUTE,
createClusterControlTaskReadRoute,
} = require('@qinglong/cluster-control/task-routes');
const {
createClusterControlAdmissionPipeline,
} = require('@qinglong/cluster-control/admission');
const {
createClusterControlRouteRegistry,
} = require('@qinglong/cluster-control/routes');
const {
createTaskDefinitionRecord,
} = require('@qinglong/runtime-core/task-definition');
function task(overrides = {}) {
return createTaskDefinitionRecord(
{
projectId: 'prj_default',
taskId: 'task-a',
expectedRevision: null,
mutationId: '123e4567-e89b-42d3-a456-426614174201',
name: 'Task A',
description: 'secret-adjacent',
kind: 'command',
spec: {
schema: 'qinglong/command@v1',
config: { command: { kind: 'shell', command: 'private' } },
},
labels: { private: 'value' },
enabled: true,
occurredAtMs: 20,
...overrides,
},
10,
);
}
function authorized(body = null, query = {}) {
return {
projectId: 'prj_default',
request: { body, query },
};
}
test('publishes one reviewed current Task route', () => {
assert.deepEqual(CLUSTER_CONTROL_TASK_READ_ROUTE, {
method: 'GET',
path: '/api/v3/projects/{projectId}/tasks/{taskId}',
operationId: 'task.get',
permission: 'task.read',
projectParameter: 'projectId',
});
assert.throws(() => createClusterControlTaskReadRoute({}), TypeError);
});
test('returns the shared projection and masks absent or cross-Project Tasks', async () => {
const definition = task({ enabled: false });
const calls = [];
const route = createClusterControlTaskReadRoute({
async findCurrentTaskDefinition(projectId, taskId) {
calls.push([projectId, taskId]);
return taskId === 'task-a' ? definition : null;
},
});
const result = await route.handle(authorized(), { taskId: 'task-a' });
assert.deepEqual(calls, [['prj_default', 'task-a']]);
assert.equal(result.statusCode, 200);
assert.deepEqual(result.body.task, {
taskId: 'task-a',
revision: 1,
name: 'Task A',
kind: 'command',
specSchema: 'qinglong/command@v1',
enabled: false,
contentDigest: definition.contentDigest,
createdAtMs: 10,
updatedAtMs: 20,
});
assert.equal(JSON.stringify(result).includes('private'), false);
assert.deepEqual(
await route.handle(authorized(), { taskId: 'task-absent' }),
{ statusCode: 404, body: { code: 'task_not_found' } },
);
const crossProject = createClusterControlTaskReadRoute({
async findCurrentTaskDefinition() { return task({ projectId: 'other' }); },
});
assert.deepEqual(
await crossProject.handle(authorized(), { taskId: 'task-a' }),
{ statusCode: 404, body: { code: 'task_not_found' } },
);
});
test('rejects body and fails closed on corrupt or unavailable storage', async () => {
const definition = task();
const corrupt = createClusterControlTaskReadRoute({
async findCurrentTaskDefinition() {
return { ...definition, contentDigest: '0'.repeat(64) };
},
});
assert.deepEqual(
await corrupt.handle(authorized(), { taskId: 'task-a' }),
{ statusCode: 503, body: { code: 'task_query_unavailable' } },
);
assert.deepEqual(
await corrupt.handle(authorized({ invalid: true }), { taskId: 'task-a' }),
{ statusCode: 400, body: { code: 'invalid_request_body' } },
);
const unavailable = createClusterControlTaskReadRoute({
async findCurrentTaskDefinition() { throw new Error('offline'); },
});
assert.deepEqual(
await unavailable.handle(authorized(), { taskId: 'task-a' }),
{ statusCode: 503, body: { code: 'task_query_unavailable' } },
);
});
test('rejects query before authentication', async () => {
let authentications = 0;
const pipeline = createClusterControlAdmissionPipeline({
routes: createClusterControlRouteRegistry([
createClusterControlTaskReadRoute({
async findCurrentTaskDefinition() { return null; },
}),
]),
authenticator: {
authenticate() {
authentications += 1;
return null;
},
},
policy: { authorize() { throw new Error('must not authorize'); } },
audit: { record() { throw new Error('must not audit'); } },
now: () => 10_000,
});
await assert.rejects(
pipeline.prepare({
requestId: 'request-invalid-task-get',
method: 'GET',
path: '/api/v3/projects/prj_default/tasks/task-a',
query: { expanded: ['true'] },
headers: {},
signal: new AbortController().signal,
}),
(error) => error.statusCode === 400 && error.code === 'invalid_route_query',
);
assert.equal(authentications, 0);
});
@@ -0,0 +1,174 @@
'use strict';
const assert = require('node:assert/strict');
const { test } = require('node:test');
const {
TASK_START_SCHEMA,
TaskStartFenceRejectedError,
TaskStartNotFoundError,
TaskStartUnavailableError,
} = require('@qinglong/runtime-core/task-start');
const {
createClusterControlAdmissionPipeline,
} = require('@qinglong/cluster-control/admission');
const {
createClusterControlRouteRegistry,
} = require('@qinglong/cluster-control/routes');
const {
CLUSTER_CONTROL_TASK_START_ROUTE,
createClusterControlTaskStartRoute,
} = require('@qinglong/cluster-control/task-routes');
const IDS = [
'019f7300-0000-7000-8000-000000000601',
'019f7300-0000-7000-8000-000000000602',
'019f7300-0000-7000-8000-000000000603',
'019f7300-0000-7000-8000-000000000604',
];
const MUTATION_ID = '019f7300-0000-7000-8000-000000000600';
const DIGEST = 'a'.repeat(64);
const PRINCIPAL = Object.freeze({
subject: Object.freeze({ type: 'user', id: 'user-1' }),
authenticationId: 'session:user-1',
authenticatedAtMs: 9_000,
expiresAtMs: 11_000,
assurance: 'single_factor',
});
const METADATA = Object.freeze({
requestId: 'request-task-start',
method: 'POST',
path: '/api/v3/projects/project-1/tasks/task-1/runs',
query: Object.freeze({}),
headers: Object.freeze({ authorization: 'Bearer opaque' }),
signal: new AbortController().signal,
});
function receipt(overrides = {}) {
return {
status: 'accepted',
projectId: 'project-1',
taskId: 'task-1',
taskRevision: 3,
taskContentDigest: DIGEST,
runId: IDS[0],
attemptId: IDS[1],
runStatus: 'queued',
runVersion: 2,
eventSequence: 2,
executorType: 'remote_worker',
executionRevisionDigest: 'b'.repeat(64),
createdAtMs: 10_000,
...overrides,
};
}
function pipeline(repository, events = [], fence = {
projectVersion: 2,
bindingVersion: 3,
}) {
let index = 0;
return createClusterControlAdmissionPipeline({
routes: createClusterControlRouteRegistry([
createClusterControlTaskStartRoute(repository, () => IDS[index++]),
]),
authenticator: {
authenticate() {
events.push('authenticate');
return PRINCIPAL;
},
},
policy: {
authorize(request) {
events.push(`authorize:${request.permission}:${request.projectId}`);
return { effect: 'allow', reasons: ['role_grant'], fence };
},
},
audit: {
record(record) {
events.push(`audit:${record.outcome}:${record.operationId}`);
},
},
now: () => 10_000,
});
}
function body(overrides = {}) {
return {
schema: TASK_START_SCHEMA,
mutationId: MUTATION_ID,
expectedRevision: 3,
expectedContentDigest: DIGEST,
...overrides,
};
}
test('publishes one reviewed run.start Task route', () => {
assert.deepEqual(CLUSTER_CONTROL_TASK_START_ROUTE, {
method: 'POST',
path: '/api/v3/projects/{projectId}/tasks/{taskId}/runs',
operationId: 'task.start',
permission: 'run.start',
projectParameter: 'projectId',
});
});
test('authenticates, authorizes and audits before starting the exact Task', async () => {
const events = [];
let observed;
const prepared = await pipeline({
async startTask(command) {
events.push('repository');
observed = command;
return receipt();
},
}, events).prepare(METADATA);
assert.deepEqual(events, [
'authenticate',
'authorize:run.start:project-1',
'audit:allowed:task.start',
]);
assert.deepEqual(await prepared.handle(body()), {
statusCode: 202,
body: { schema: TASK_START_SCHEMA, ...receipt() },
});
assert.deepEqual(observed, {
projectId: 'project-1',
taskId: 'task-1',
mutationId: MUTATION_ID,
expectedRevision: 3,
expectedContentDigest: DIGEST,
runId: IDS[0],
attemptId: IDS[1],
createdEventId: IDS[2],
queuedEventId: IDS[3],
subject: PRINCIPAL.subject,
policyFence: { projectVersion: 2, bindingVersion: 3 },
});
});
test('rejects command injection and maps replay plus stable failures', async () => {
let calls = 0;
const invalid = await pipeline({
async startTask() { calls += 1; return receipt(); },
}).prepare(METADATA);
assert.equal((await invalid.handle(body({ command: '/bin/sh' }))).statusCode, 400);
assert.equal(calls, 0);
const replay = await pipeline({
async startTask() { return receipt({ status: 'existing' }); },
}).prepare(METADATA);
assert.equal((await replay.handle(body())).statusCode, 200);
for (const [error, statusCode, code] of [
[new TaskStartNotFoundError(), 404, 'task_not_found'],
[new TaskStartFenceRejectedError('definition_changed'), 409, 'task_start_fence_rejected'],
[new TaskStartUnavailableError(), 503, 'task_start_unavailable'],
]) {
const prepared = await pipeline({
async startTask() { throw error; },
}).prepare(METADATA);
const result = await prepared.handle(body());
assert.equal(result.statusCode, statusCode);
assert.equal(result.body.code, code);
}
});
@@ -0,0 +1,104 @@
const assert = require('node:assert/strict');
const { test } = require('node:test');
const {
WorkerCredentialUnavailableError,
} = require('@qinglong/runtime-core/worker-credential');
const {
workerCredentialSecretDigest,
} = require('@qinglong/runtime-core/worker-credential-token');
const {
createWorkerCredentialAuthenticator,
} = require('@qinglong/cluster-control/worker-ingress');
const NOW = 10_000;
const PEPPER = Buffer.alloc(32, 1).toString('base64url');
const SECRET = Buffer.alloc(32, 2).toString('base64url');
const CREDENTIAL_ID = 'worker_primary';
function metadata(authorization = `Worker ql3w_${CREDENTIAL_ID}_${SECRET}`) {
return {
requestId: 'request-1',
method: 'POST',
path: '/api/v3/worker-ingress/workers/edge-1/sessions/018f5c64-9b9d-7f1a-8c2d-1234567890ac/heartbeat',
query: Object.freeze({}),
headers: Object.freeze({ authorization }),
signal: new AbortController().signal,
};
}
function credential(overrides = {}) {
return {
credentialId: CREDENTIAL_ID,
version: 2,
state: 'active',
workerId: 'edge-1',
secretDigest: workerCredentialSecretDigest(PEPPER, CREDENTIAL_ID, SECRET),
createdAtMs: 1,
notBeforeAtMs: 1,
expiresAtMs: 100_000,
...overrides,
};
}
function authenticator(value = credential(), overrides = {}) {
return createWorkerCredentialAuthenticator(
{ async resolve(id) { assert.equal(id, CREDENTIAL_ID); return value; } },
PEPPER,
{ now: () => NOW, ...overrides },
);
}
test('authenticates a ql3w credential as its bound short-lived Worker', async () => {
assert.deepEqual(await authenticator().authenticate(metadata()), {
workerId: 'edge-1',
credentialId: CREDENTIAL_ID,
credentialVersion: 2,
authenticationId: `worker_credential:${CREDENTIAL_ID}:2`,
authenticatedAtMs: NOW,
expiresAtMs: 70_000,
});
});
test('rejects malformed, mismatched, inactive and expired Worker credentials', async () => {
let calls = 0;
const strict = createWorkerCredentialAuthenticator(
{ async resolve() { calls += 1; return credential(); } },
PEPPER,
{ now: () => NOW },
);
for (const authorization of [
undefined,
'Bearer ql3w_worker_primary_invalid',
`Worker ql3w_${CREDENTIAL_ID}_${Buffer.alloc(32, 3).toString('base64url')}`,
]) {
const request = metadata();
request.headers = Object.freeze(authorization ? { authorization } : {});
assert.equal(await strict.authenticate(request), null);
}
assert.equal(calls, 1);
for (const value of [
null,
credential({ state: 'revoked' }),
credential({ notBeforeAtMs: NOW + 1 }),
credential({ expiresAtMs: NOW }),
]) assert.equal(await authenticator(value).authenticate(metadata()), null);
});
test('maps storage, corrupt records and cancellation to unavailable', async () => {
const unavailable = createWorkerCredentialAuthenticator(
{ async resolve() { throw new Error('database unavailable'); } },
PEPPER,
{ now: () => NOW },
);
await assert.rejects(unavailable.authenticate(metadata()), WorkerCredentialUnavailableError);
await assert.rejects(
authenticator(credential({ secretDigest: 'corrupt' })).authenticate(metadata()),
WorkerCredentialUnavailableError,
);
const controller = new AbortController();
controller.abort();
await assert.rejects(
authenticator().authenticate({ ...metadata(), signal: controller.signal }),
WorkerCredentialUnavailableError,
);
});
@@ -0,0 +1,83 @@
const assert = require('node:assert/strict');
const { readFileSync } = require('node:fs');
const path = require('node:path');
const { test } = require('node:test');
const {
startClusterWorkerIngressApplication,
} = require('@qinglong/cluster-control/worker-ingress');
const FIXTURES = path.join(__dirname, 'fixtures', 'mtls');
const MUTUAL_TLS = Object.freeze({
privateKey: readFileSync(path.join(FIXTURES, 'server-key.pem')),
certificateChain: readFileSync(path.join(FIXTURES, 'server-cert.pem')),
clientCertificateAuthorities: Object.freeze([
readFileSync(path.join(FIXTURES, 'ca-cert.pem')),
]),
});
const EVIDENCE = Object.freeze({
contractName: 'control-core',
contractVersion: 14,
serverMajor: 16,
migrationIds: Object.freeze([]),
});
test('enabled Worker ingress rejects plaintext before binding or opening storage', async () => {
let databaseOpens = 0;
await assert.rejects(
startClusterWorkerIngressApplication({
enabled: true,
profile: 'cluster-control',
workerCredentialPepper: 'A'.repeat(43),
openDatabase: async () => {
databaseOpens += 1;
throw new Error('must not open');
},
create() {
throw new Error('must not assemble');
},
http: { host: '127.0.0.1', port: 0 },
}),
/requires mutual TLS/,
);
assert.equal(databaseOpens, 0);
});
test('exposes explicit transport reload only for an active mTLS ingress', async (t) => {
let databaseCloses = 0;
const application = await startClusterWorkerIngressApplication({
enabled: true,
profile: 'cluster-control',
workerCredentialPepper: 'A'.repeat(43),
openDatabase: async () => ({
client: {},
async close() {
databaseCloses += 1;
},
}),
create() {
return {
evidence: EVIDENCE,
pipeline: {
async prepare() {
return {
handle() {
return { statusCode: 204 };
},
};
},
},
};
},
http: {
host: '127.0.0.1',
port: 0,
mutualTls: MUTUAL_TLS,
},
});
t.after(() => application.stop());
assert.equal(application.status, 'active');
assert.equal(application.reloadTransport(MUTUAL_TLS), 2);
assert.equal(await application.stop(), 'stopped');
assert.equal(databaseCloses, 1);
});
@@ -0,0 +1,375 @@
const assert = require('node:assert/strict');
const { mkdtemp, readFile, rm, writeFile } = require('node:fs/promises');
const os = require('node:os');
const path = require('node:path');
const { test } = require('node:test');
const {
loadPostgresCertificateAuthorityFile,
} = require('@qinglong/cluster-postgres/runtime');
const {
ClusterWorkerIngressConfigError,
createClusterWorkerIngressDatabaseOpener,
createClusterWorkerIngressHttpOptions,
loadClusterWorkerIngressMutualTls,
loadClusterWorkerIngressConfig,
} = require('@qinglong/cluster-control/worker-ingress-config');
const FIXTURES = path.join(__dirname, 'fixtures', 'mtls');
const POSTGRES_CA_FILE = path.join(FIXTURES, 'ca-cert.pem');
const POSTGRES_CA_BUNDLE =
loadPostgresCertificateAuthorityFile(POSTGRES_CA_FILE);
const BASE_ENV = Object.freeze({
QL3_WORKER_INGRESS_ENABLED: 'true',
QL_DEPLOYMENT_PROFILE: 'cluster-control',
QL3_POSTGRES_WORKER_INGRESS_URL:
'postgresql://ql3_worker_ingress:secret@database.internal:5432/qinglong',
QL3_WORKER_INGRESS_POSTGRES_TLS_SERVERNAME: 'database.internal',
QL3_WORKER_CREDENTIAL_PEPPER: 'A'.repeat(43),
QL3_WORKER_ARTIFACT_S3_BUCKET: 'qinglong-worker-artifacts',
QL3_WORKER_ARTIFACT_S3_REGION: 'us-east-1',
QL3_WORKER_INGRESS_TLS_PRIVATE_KEY_FILE: path.join(
FIXTURES,
'server-key.pem',
),
QL3_WORKER_INGRESS_TLS_CERTIFICATE_FILE: path.join(
FIXTURES,
'server-cert.pem',
),
QL3_WORKER_INGRESS_TLS_CLIENT_CA_FILE: path.join(FIXTURES, 'ca-cert.pem'),
});
test('disabled Worker ingress does not read database, pepper or TLS paths', () => {
const reads = [];
const environment = new Proxy(
{
QL3_WORKER_INGRESS_ENABLED: 'false',
QL_DEPLOYMENT_PROFILE: 'edge',
},
{
get(target, property, receiver) {
reads.push(property);
if (
String(property).includes('POSTGRES') ||
String(property).includes('TLS') ||
String(property).includes('WORKER_SECRET')
) {
throw new Error('disabled ingress read protected configuration');
}
return Reflect.get(target, property, receiver);
},
},
);
assert.deepEqual(loadClusterWorkerIngressConfig(environment), {
enabled: false,
profile: 'edge',
});
assert.equal(
reads.some((name) => String(name).includes('POSTGRES')),
false,
);
assert.equal(
reads.some((name) => String(name).includes('TLS')),
false,
);
assert.equal(
reads.some((name) => String(name).includes('WORKER_SECRET')),
false,
);
});
test('builds exact bounded Worker ingress and least-privilege Pool config', async () => {
const config = loadClusterWorkerIngressConfig({
...BASE_ENV,
QL3_WORKER_INGRESS_HOST: '127.0.0.1',
QL3_WORKER_INGRESS_PORT: '5901',
QL3_WORKER_INGRESS_MAX_IN_FLIGHT: '32',
QL3_WORKER_INGRESS_AUTH_RATE_PER_PEER: '20',
QL3_WORKER_INGRESS_POSTGRES_MAX_CONNECTIONS: '6',
QL3_WORKER_INGRESS_POSTGRES_TLS_SERVERNAME: 'database.internal',
QL3_WORKER_INGRESS_POSTGRES_TLS_CA_FILE: POSTGRES_CA_FILE,
});
assert.equal(config.enabled, true);
assert.deepEqual(config.http, {
host: '127.0.0.1',
port: 5901,
maxBodyBytes: 65_536,
maxResponseBytes: 65_536,
maxInFlightRequests: 32,
authenticationRateWindowMs: 60_000,
authenticationRatePerPeer: 20,
authenticationRateGlobal: 1_200,
authenticationRateMaxPeers: 4_096,
requestTimeoutMs: 15_000,
drainTimeoutMs: 10_000,
});
assert.deepEqual(config.database, {
connection: {
connectionString: BASE_ENV.QL3_POSTGRES_WORKER_INGRESS_URL,
tls: {
mode: 'verify-full',
ca: POSTGRES_CA_BUNDLE,
servername: 'database.internal',
},
},
pool: {
applicationName: 'qinglong-worker-ingress',
maxConnections: 6,
connectionTimeoutMs: 5_000,
},
});
assert.deepEqual(config.artifact, {
bucket: 'qinglong-worker-artifacts',
region: 'us-east-1',
forcePathStyle: false,
encryption: { mode: 's3' },
});
const http = await createClusterWorkerIngressHttpOptions(
config,
Date.UTC(2030, 0, 1),
);
assert.equal(Buffer.isBuffer(http.mutualTls.privateKey), true);
assert.equal(Buffer.isBuffer(http.mutualTls.certificateChain), true);
assert.equal(http.mutualTls.clientCertificateAuthorities.length, 1);
const open = createClusterWorkerIngressDatabaseOpener(config, () => {});
const database = await open();
await database.close();
});
test('enables only the explicit mounted-files Secret provider', () => {
const rootDirectory = path.join(
os.tmpdir(),
'ql3-worker-secret-values',
);
const enabled = loadClusterWorkerIngressConfig({
...BASE_ENV,
QL3_WORKER_SECRET_PROVIDER: 'mounted-files',
QL3_WORKER_SECRET_ROOT_DIRECTORY: rootDirectory,
});
assert.deepEqual(enabled.secret, {
provider: 'mounted-files',
rootDirectory,
});
const disabled = loadClusterWorkerIngressConfig({
...BASE_ENV,
QL3_WORKER_SECRET_PROVIDER: 'disabled',
});
assert.equal(disabled.secret, undefined);
});
test('loads discrete operator-managed Worker ingress credentials', () => {
const {
QL3_POSTGRES_WORKER_INGRESS_URL: _connectionString,
...withoutConnectionString
} = BASE_ENV;
const config = loadClusterWorkerIngressConfig({
...withoutConnectionString,
QL3_POSTGRES_WORKER_INGRESS_HOST: 'ql3-postgres-rw.qinglong3-system.svc',
QL3_POSTGRES_WORKER_INGRESS_PORT: '5432',
QL3_POSTGRES_WORKER_INGRESS_DATABASE: 'qinglong',
QL3_POSTGRES_WORKER_INGRESS_USER: 'ql3_worker_ingress',
QL3_POSTGRES_WORKER_INGRESS_PASSWORD: 'operator-secret',
});
assert.deepEqual(config.database.connection, {
host: 'ql3-postgres-rw.qinglong3-system.svc',
port: 5432,
database: 'qinglong',
user: 'ql3_worker_ingress',
password: 'operator-secret',
tls: {
mode: 'verify-full',
servername: 'database.internal',
},
});
});
test('requires explicit mTLS files and a second gate for insecure PostgreSQL', () => {
for (const environment of [
{ ...BASE_ENV, QL3_WORKER_INGRESS_TLS_PRIVATE_KEY_FILE: 'relative.pem' },
{
...BASE_ENV,
QL3_WORKER_INGRESS_POSTGRES_TLS_SERVERNAME: undefined,
},
{
...BASE_ENV,
QL3_WORKER_INGRESS_POSTGRES_TLS_SERVERNAME: '127.0.0.1',
},
{ ...BASE_ENV, QL3_WORKER_INGRESS_TLS_CLIENT_CRL_FILE: 'relative.pem' },
{ ...BASE_ENV, QL3_WORKER_CREDENTIAL_PEPPER: 'weak' },
{ ...BASE_ENV, QL3_WORKER_INGRESS_MAX_IN_FLIGHT: '257' },
{ ...BASE_ENV, QL3_WORKER_INGRESS_POSTGRES_MAX_CONNECTIONS: '17' },
{
...BASE_ENV,
QL3_WORKER_INGRESS_POSTGRES_TLS_CA_FILE: 'relative-ca.pem',
},
{
...BASE_ENV,
QL3_WORKER_INGRESS_POSTGRES_TLS_MODE: 'disable',
},
{
...BASE_ENV,
QL3_POSTGRES_WORKER_INGRESS_URL:
'postgresql://database/qinglong?sslmode=disable',
},
{
...BASE_ENV,
QL3_POSTGRES_WORKER_INGRESS_HOST: 'database.internal',
},
{ ...BASE_ENV, QL3_WORKER_ARTIFACT_S3_BUCKET: 'Invalid_Bucket' },
{ ...BASE_ENV, QL3_WORKER_ARTIFACT_S3_REGION: 'invalid region' },
{
...BASE_ENV,
QL3_WORKER_ARTIFACT_S3_ENDPOINT: 'http://minio.internal:9000',
},
{
...BASE_ENV,
QL3_WORKER_ARTIFACT_S3_ENCRYPTION: 'kms',
},
{
...BASE_ENV,
QL3_WORKER_ARTIFACT_S3_KMS_KEY_ID: 'unexpected',
},
{
...BASE_ENV,
QL3_WORKER_SECRET_PROVIDER: 'vault',
},
{
...BASE_ENV,
QL3_WORKER_SECRET_PROVIDER: 'mounted-files',
},
{
...BASE_ENV,
QL3_WORKER_SECRET_PROVIDER: 'mounted-files',
QL3_WORKER_SECRET_ROOT_DIRECTORY: 'relative/secrets',
},
]) {
assert.throws(
() => loadClusterWorkerIngressConfig(environment),
ClusterWorkerIngressConfigError,
);
}
const config = loadClusterWorkerIngressConfig({
...BASE_ENV,
QL3_WORKER_INGRESS_POSTGRES_TLS_MODE: 'disable',
QL3_WORKER_INGRESS_POSTGRES_ALLOW_INSECURE: 'true',
});
assert.deepEqual(config.database.connection.tls, { mode: 'disable' });
const minio = loadClusterWorkerIngressConfig({
...BASE_ENV,
QL3_WORKER_ARTIFACT_S3_ENDPOINT: 'http://minio.internal:9000',
QL3_WORKER_ARTIFACT_S3_ALLOW_INSECURE: 'true',
QL3_WORKER_ARTIFACT_S3_FORCE_PATH_STYLE: 'true',
QL3_WORKER_ARTIFACT_S3_PREFIX: 'tenant-a/worker-artifacts',
QL3_WORKER_ARTIFACT_S3_ENCRYPTION: 'kms',
QL3_WORKER_ARTIFACT_S3_KMS_KEY_ID: 'alias/qinglong-worker-artifacts',
});
assert.deepEqual(minio.artifact, {
bucket: 'qinglong-worker-artifacts',
region: 'us-east-1',
prefix: 'tenant-a/worker-artifacts',
endpoint: 'http://minio.internal:9000',
forcePathStyle: true,
encryption: {
mode: 'kms',
keyId: 'alias/qinglong-worker-artifacts',
},
});
assert.throws(
() =>
loadClusterWorkerIngressConfig({
...BASE_ENV,
QL3_WORKER_INGRESS_POSTGRES_TLS_MODE: 'disable',
QL3_WORKER_INGRESS_POSTGRES_ALLOW_INSECURE: 'true',
QL3_WORKER_INGRESS_POSTGRES_TLS_CA_FILE: POSTGRES_CA_FILE,
}),
ClusterWorkerIngressConfigError,
);
});
test('loads bounded CA rollover bundles and optional CRL material', async (t) => {
const directory = await mkdtemp(path.join(os.tmpdir(), 'ql3-mtls-config-'));
t.after(() => rm(directory, { recursive: true, force: true }));
const authority = await readFile(path.join(FIXTURES, 'ca-cert.pem'));
const authorityBundle = path.join(directory, 'client-ca-bundle.pem');
await writeFile(authorityBundle, Buffer.concat([authority, authority]));
const config = loadClusterWorkerIngressConfig({
...BASE_ENV,
QL3_WORKER_INGRESS_TLS_CLIENT_CA_FILE: authorityBundle,
QL3_WORKER_INGRESS_TLS_CLIENT_CRL_FILE: path.join(
FIXTURES,
'empty-crl.pem',
),
});
const mutualTls = await loadClusterWorkerIngressMutualTls(
config,
Date.UTC(2030, 0, 1),
);
assert.equal(mutualTls.clientCertificateAuthorities.length, 2);
assert.equal(mutualTls.certificateRevocationLists.length, 1);
await writeFile(
authorityBundle,
Buffer.concat([authority, Buffer.from('unexpected trailing data')]),
);
await assert.rejects(
loadClusterWorkerIngressMutualTls(config, Date.UTC(2030, 0, 1)),
/contains unsupported data/,
);
await writeFile(
authorityBundle,
Buffer.concat(Array.from({ length: 17 }, () => authority)),
);
await assert.rejects(
loadClusterWorkerIngressMutualTls(config, Date.UTC(2030, 0, 1)),
/must contain 1 to 16 PEM certificates/,
);
});
test('rejects unavailable, mismatched and non-CA TLS material', async () => {
const unavailable = loadClusterWorkerIngressConfig({
...BASE_ENV,
QL3_WORKER_INGRESS_TLS_CERTIFICATE_FILE: '/definitely/missing.pem',
});
await assert.rejects(
createClusterWorkerIngressHttpOptions(unavailable, Date.UTC(2030, 0, 1)),
ClusterWorkerIngressConfigError,
);
const mismatched = loadClusterWorkerIngressConfig({
...BASE_ENV,
QL3_WORKER_INGRESS_TLS_PRIVATE_KEY_FILE: path.join(
FIXTURES,
'client-key.pem',
),
});
await assert.rejects(
createClusterWorkerIngressHttpOptions(mismatched, Date.UTC(2030, 0, 1)),
/does not match/,
);
const nonCa = loadClusterWorkerIngressConfig({
...BASE_ENV,
QL3_WORKER_INGRESS_TLS_CLIENT_CA_FILE: path.join(
FIXTURES,
'client-cert.pem',
),
});
await assert.rejects(
createClusterWorkerIngressHttpOptions(nonCa, Date.UTC(2030, 0, 1)),
/is not a CA/,
);
const malformedCrl = loadClusterWorkerIngressConfig({
...BASE_ENV,
QL3_WORKER_INGRESS_TLS_CLIENT_CRL_FILE: path.join(
FIXTURES,
'client-cert.pem',
),
});
await assert.rejects(
createClusterWorkerIngressHttpOptions(malformedCrl, Date.UTC(2030, 0, 1)),
/is not a PEM CRL/,
);
});
@@ -0,0 +1,868 @@
const assert = require('node:assert/strict');
const { test } = require('node:test');
const {
WorkerExecutionAttestationFenceRejectedError,
} = require('@qinglong/runtime-core/worker-attestation');
const {
RemoteRunActivationFenceRejectedError,
RemoteRunActivationUnavailableError,
} = require('@qinglong/runtime-core/remote-activation');
const {
createWorkerIngressAdmissionPipeline,
} = require('@qinglong/cluster-control/worker-ingress');
const {
createClusterTaskExecutionRevision,
} = require('@qinglong/runtime-core/cluster-execution-revision');
const {
digestRunDispatchLeaseToken,
} = require('@qinglong/runtime-core');
const { createSecretRef } = require('@qinglong/runtime-core/secret-reference');
const {
RemoteWorkerSecretDeliveryFenceRejectedError,
} = require('@qinglong/runtime-core/remote-secret-delivery');
const {
REMOTE_WORKER_ARTIFACT_CONTENT_TYPE,
RemoteWorkerCompletionFenceRejectedError,
createRemoteWorkerCompletionRequestBody,
} = require('@qinglong/runtime-core/remote-worker-completion');
const {
WORKER_SESSION_HEARTBEAT_SCHEMA,
WORKER_SESSION_REGISTER_SCHEMA,
WORKER_SESSION_TRANSITION_SCHEMA,
} = require('@qinglong/runtime-core/worker-session-transport');
const {
RemoteWorkerLeaseControlFenceRejectedError,
RemoteWorkerLeaseControlUnavailableError,
} = require('@qinglong/runtime-core/remote-worker-lease-control');
const SESSION_ID = '018f5c64-9b9d-7f1a-8c2d-1234567890ac';
function metadata(operation, workerId = 'edge-1') {
return {
requestId: 'request-1',
method: 'POST',
path: `/api/v3/worker-ingress/workers/${workerId}/sessions/${SESSION_ID}/${operation}`,
query: Object.freeze({}),
headers: Object.freeze({ authorization: 'Worker token' }),
signal: new AbortController().signal,
};
}
function principal(workerId = 'edge-1') {
return Object.freeze({
workerId,
credentialId: 'worker_primary',
credentialVersion: 1,
authenticationId: 'worker_credential:worker_primary:1',
authenticatedAtMs: 1,
expiresAtMs: 60_001,
});
}
function fixture(overrides = {}) {
const events = [];
const pipeline = createWorkerIngressAdmissionPipeline({
authenticator: {
async authenticate() {
events.push('authenticate');
return principal();
},
},
workers: {
async register() { throw new Error('not used'); },
async heartbeatAuthenticated(command, credential) {
events.push(
`heartbeat:${command.expectedVersion}:${credential.credentialId}:${credential.credentialVersion}`,
);
return {
workerId: command.workerId,
sessionId: command.sessionId,
generation: command.generation,
version: command.expectedVersion + 1,
status: 'online',
capabilitiesJson: '{}',
capabilitiesHash:
'44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a',
maxConcurrentRuns: 1,
availableSlots: command.availableSlots,
registeredAtMs: 1,
lastHeartbeatAtMs: 2,
leaseExpiresAtMs: 50_000,
updatedAtMs: 2,
};
},
async transitionAuthenticated() { throw new Error('not used'); },
async find() { return null; },
},
attestations: {
async submit(command) {
events.push(`attest:${command.sequence}`);
return {
status: 'created',
attestation: { ...command, receivedAtMs: 20_000 },
};
},
async findLatestExact() { return null; },
},
audit: {
async record(record) {
events.push(`audit:${record.outcome}`);
},
},
now: () => 10_000,
...overrides,
});
return { pipeline, events };
}
test('authenticates and durably audits before accepting a heartbeat body', async () => {
const { pipeline, events } = fixture();
const prepared = await pipeline.prepare(metadata('heartbeat'));
assert.deepEqual(events, ['authenticate', 'audit:allowed']);
const response = await prepared.handle({
schema: WORKER_SESSION_HEARTBEAT_SCHEMA,
generation: 2,
expectedVersion: 3,
availableSlots: 1,
leaseDurationMs: 30_000,
});
assert.equal(response.statusCode, 200);
assert.deepEqual(response.body, {
schema: WORKER_SESSION_HEARTBEAT_SCHEMA,
workerId: 'edge-1',
sessionId: SESSION_ID,
generation: 2,
version: 4,
status: 'online',
leaseExpiresAtMs: 50_000,
});
assert.deepEqual(events, [
'authenticate',
'audit:allowed',
'heartbeat:3:worker_primary:1',
]);
});
test('uses exact versioned register and transition contracts', async () => {
const baseRecord = {
workerId: 'edge-1',
sessionId: SESSION_ID,
generation: 1,
version: 0,
status: 'online',
capabilitiesJson: '{}',
capabilitiesHash:
'44136fa355b3678a1146ad16f7e8649e94fb4fc21fe77e8310c060f61caaff8a',
maxConcurrentRuns: 1,
availableSlots: 1,
registeredAtMs: 1,
lastHeartbeatAtMs: 1,
leaseExpiresAtMs: 50_000,
updatedAtMs: 1,
};
const context = fixture({
workers: {
async register(command) {
return { worker: { ...baseRecord, ...command }, replacedSession: false };
},
async heartbeatAuthenticated() { throw new Error('not used'); },
async transitionAuthenticated(command, credential) {
assert.deepEqual(credential, {
workerId: 'edge-1',
credentialId: 'worker_primary',
credentialVersion: 1,
});
return {
...baseRecord,
version: command.expectedVersion + 1,
status: command.status,
availableSlots: 0,
updatedAtMs: 2,
};
},
async findById() { return null; },
async listAvailable() { throw new Error('not used'); },
},
});
const register = await (
await context.pipeline.prepare(metadata('register'))
).handle({
schema: WORKER_SESSION_REGISTER_SCHEMA,
capabilitiesJson: '{}',
capabilitiesHash: baseRecord.capabilitiesHash,
maxConcurrentRuns: 1,
availableSlots: 1,
leaseDurationMs: 30_000,
});
assert.equal(register.statusCode, 200);
assert.equal(register.body.schema, WORKER_SESSION_REGISTER_SCHEMA);
const transition = await (
await context.pipeline.prepare(metadata('transition'))
).handle({
schema: WORKER_SESSION_TRANSITION_SCHEMA,
generation: 1,
expectedVersion: 0,
status: 'draining',
});
assert.equal(transition.body.schema, WORKER_SESSION_TRANSITION_SCHEMA);
assert.equal(transition.body.status, 'draining');
});
test('binds the credential Worker to the path and rejects before body access', async () => {
const { pipeline, events } = fixture();
await assert.rejects(
pipeline.prepare(metadata('heartbeat', 'other-worker')),
(error) => error.statusCode === 401 && error.code === 'worker_authentication_required',
);
assert.deepEqual(events, ['authenticate', 'audit:authentication_rejected']);
});
test('forwards the complete execution fence and maps stale attestations to conflict', async () => {
let observed;
const { pipeline } = fixture({
attestations: {
async submit(command) {
observed = command;
throw new WorkerExecutionAttestationFenceRejectedError('authority_mismatch');
},
async findLatestExact() { return null; },
},
});
const prepared = await pipeline.prepare(metadata('attestations'));
const body = {
attestationId: '018f5c64-9b9d-7f1a-8c2d-1234567890ab',
runId: 'run-1',
attemptId: 'attempt-1',
sequence: 1,
state: 'running',
workerGeneration: 2,
leaseTokenDigest: 'a'.repeat(64),
leaseGeneration: 3,
leaseVersion: 4,
offerId: 'offer-1',
callbackSequence: 5,
executorHandle: 'remote:handle-1',
journalRevision: 6,
};
await assert.rejects(
prepared.handle(body),
(error) => error.statusCode === 409 && error.code === 'worker_attestation_fenced',
);
assert.deepEqual(observed, {
...body,
workerId: 'edge-1',
workerSessionId: SESSION_ID,
});
});
test('fails closed when authentication or durable audit is unavailable', async () => {
const unavailableAuth = fixture({
authenticator: { async authenticate() { throw new Error('down'); } },
});
await assert.rejects(
unavailableAuth.pipeline.prepare(metadata('heartbeat')),
(error) => error.statusCode === 503 && error.code === 'worker_authentication_unavailable',
);
const unavailableAudit = fixture({
audit: { async record() { throw new Error('down'); } },
});
await assert.rejects(
unavailableAudit.pipeline.prepare(metadata('heartbeat')),
(error) => error.statusCode === 503 && error.code === 'worker_audit_unavailable',
);
});
test('binds pull-based offer claims to the authenticated Session without echoing the lease token', async () => {
let observed;
const sourceDigest = 'b'.repeat(64);
const taskRevision = `qltd:v1:1:${sourceDigest}`;
const executionRevision = createClusterTaskExecutionRevision({
projectId: 'project-1',
taskId: 'task-1',
taskRevision,
sourceRevision: 1,
sourceContentDigest: sourceDigest,
executorType: 'remote_worker',
planSchema: 'qinglong/command-execution@v1',
command: { kind: 'argv', file: '/bin/true', args: [] },
environment: [],
createdAtMs: 1,
});
const { pipeline, events } = fixture({
offers: {
async claimNext(principal, command) {
observed = { principal, command };
return {
status: 'offered',
offer: {
offerId: command.offerId,
deliveryKind: 'new_claim',
executionDigest: executionRevision.contentDigest,
candidate: {
runId: 'run-1',
attemptId: 'attempt-1',
projectId: 'project-1',
taskId: 'task-1',
taskRevision,
priority: 0,
queuedAtMs: 1,
attemptCreatedAtMs: 1,
attemptNumber: 1,
executorType: 'remote_worker',
},
worker: {
workerId: principal.workerId,
sessionId: command.workerSessionId,
generation: command.workerGeneration,
},
lease: {
attemptId: 'attempt-1',
runId: 'run-1',
status: 'leased',
version: 0,
leaseGeneration: 1,
workerId: principal.workerId,
workerSessionId: command.workerSessionId,
workerGeneration: command.workerGeneration,
leaseTokenDigest: digestRunDispatchLeaseToken(command.leaseToken),
acquiredAtMs: 10,
renewedAtMs: 10,
expiresAtMs: 30_010,
updatedAtMs: 10,
},
leaseToken: command.leaseToken,
executionRevision,
placementScore: 0,
},
stats: {
pages: 1,
candidates: 1,
plansUnavailable: 0,
placementMismatches: 0,
claimAttempts: 1,
claimRaces: 0,
},
truncated: false,
};
},
},
});
const leaseToken = 'worker_generated_lease_capability_0000000000000001';
const prepared = await pipeline.prepare(metadata('offers'));
const result = await prepared.handle({
workerGeneration: 2,
offerId: 'offer-1',
leaseToken,
});
assert.deepEqual(observed, {
principal: { workerId: 'edge-1' },
command: {
workerSessionId: SESSION_ID,
workerGeneration: 2,
offerId: 'offer-1',
leaseToken,
},
});
assert.equal(result.statusCode, 200);
assert.equal(result.body.status, 'offered');
assert.equal(result.body.schema, 'qinglong/remote-execution-offer@v1');
assert.equal('leaseToken' in result.body.offer, false);
assert.equal('leaseTokenDigest' in result.body.offer.lease, false);
assert.deepEqual(events, ['authenticate', 'audit:allowed']);
});
test('maps an internally malformed offer projection to unavailable, not a client error', async () => {
const { pipeline } = fixture({
offers: {
async claimNext() {
return {
status: 'offered',
offer: { offerId: 'broken' },
stats: {
pages: 1,
candidates: 1,
plansUnavailable: 0,
placementMismatches: 0,
claimAttempts: 1,
claimRaces: 0,
},
truncated: false,
};
},
},
});
await assert.rejects(
(await pipeline.prepare(metadata('offers'))).handle({
workerGeneration: 2,
offerId: 'offer-1',
leaseToken: 'worker_generated_lease_capability_0000000000000001',
}),
(error) =>
error.statusCode === 503 && error.code === 'worker_ingress_unavailable',
);
});
test('binds activation ACKs to the authenticated Worker and never echoes capabilities', async () => {
const observed = [];
const activation = {
async acknowledgeStarting(principal, command) {
observed.push(['starting', principal, command]);
return {
status: 'applied',
snapshot: {
runId: command.runId,
attemptId: command.attemptId,
runStatus: 'dispatching',
attemptStatus: 'starting',
leaseVersion: command.expectedLeaseVersion,
leaseGeneration: command.leaseGeneration,
callbackSequence: 0,
},
};
},
async acknowledgeRunning(principal, command) {
observed.push(['running', principal, command]);
return {
status: 'applied',
snapshot: {
runId: command.runId,
attemptId: command.attemptId,
runStatus: 'running',
attemptStatus: 'running',
leaseVersion: command.expectedLeaseVersion,
leaseGeneration: command.leaseGeneration,
callbackSequence: command.callbackSequence,
executorHandle: command.executorHandle,
startedAtMs: 20_000,
},
};
},
async failStart(principal, command) {
observed.push(['start-failure', principal, command]);
return {
status: 'already_terminal',
snapshot: {
runId: command.runId,
attemptId: command.attemptId,
runStatus: 'failed',
attemptStatus: 'failed',
leaseVersion: command.expectedLeaseVersion + 1,
leaseGeneration: command.leaseGeneration,
callbackSequence: 1,
finishedAtMs: 20_000,
errorCode: 'executor_start_rejected',
},
};
},
};
const base = {
runId: 'run-1',
attemptId: 'attempt-1',
workerGeneration: 2,
offerId: 'offer-1',
leaseGeneration: 3,
leaseToken: 'worker_generated_lease_capability_0000000000000001',
expectedLeaseVersion: 4,
};
const { pipeline } = fixture({ activation });
const starting = await (await pipeline.prepare(metadata('starting'))).handle(base);
const running = await (await pipeline.prepare(metadata('running'))).handle({
...base,
executorHandle: 'remote:handle-1',
logArtifactId: null,
callbackSequence: 1,
callbackTokenDigest: 'a'.repeat(64),
});
const failed = await (await pipeline.prepare(metadata('start-failure'))).handle(base);
assert.equal(starting.statusCode, 200);
assert.equal(running.statusCode, 200);
assert.equal(failed.statusCode, 200);
assert.deepEqual(
[starting.body.schema, running.body.schema, failed.body.schema],
Array(3).fill('qinglong/remote-run-activation@v1'),
);
assert.equal(JSON.stringify([starting.body, running.body, failed.body]).includes(base.leaseToken), false);
assert.equal(JSON.stringify([starting.body, running.body, failed.body]).includes('a'.repeat(64)), false);
assert.deepEqual(observed, [
['starting', { workerId: 'edge-1' }, {
...base, workerSessionId: SESSION_ID,
}],
['running', { workerId: 'edge-1' }, {
...base,
workerSessionId: SESSION_ID,
executorHandle: 'remote:handle-1',
callbackSequence: 1,
callbackTokenDigest: 'a'.repeat(64),
}],
['start-failure', { workerId: 'edge-1' }, {
...base, workerSessionId: SESSION_ID,
}],
]);
});
test('maps stale activation authority to conflict', async () => {
const fenced = async () => {
throw new RemoteRunActivationFenceRejectedError('attempt-1', 'version_mismatch');
};
const { pipeline } = fixture({
activation: {
acknowledgeStarting: fenced,
acknowledgeRunning: fenced,
failStart: fenced,
},
});
await assert.rejects(
(await pipeline.prepare(metadata('starting'))).handle({
runId: 'run-1',
attemptId: 'attempt-1',
workerGeneration: 2,
offerId: 'offer-1',
leaseGeneration: 3,
leaseToken: 'worker_generated_lease_capability_0000000000000001',
expectedLeaseVersion: 4,
}),
(error) => error.statusCode === 409 && error.code === 'worker_activation_fenced',
);
});
test('maps activation storage failures to unavailable', async () => {
const unavailable = async () => {
throw new RemoteRunActivationUnavailableError();
};
const { pipeline } = fixture({
activation: {
acknowledgeStarting: unavailable,
acknowledgeRunning: unavailable,
failStart: unavailable,
},
});
await assert.rejects(
(await pipeline.prepare(metadata('starting'))).handle({
runId: 'run-1',
attemptId: 'attempt-1',
workerGeneration: 2,
offerId: 'offer-1',
leaseGeneration: 3,
leaseToken: 'worker_generated_lease_capability_0000000000000001',
expectedLeaseVersion: 4,
}),
(error) => error.statusCode === 503 && error.code === 'worker_ingress_unavailable',
);
});
test('binds one Secret batch to path identity and never echoes capabilities', async () => {
const secretRef = createSecretRef({ projectId: 'project-1', name: 'token' });
const executionDigest = 'c'.repeat(64);
let observed;
let disposed = 0;
const { pipeline } = fixture({
secrets: {
async deliver(principal, command) {
observed = { principal, command };
return {
runId: command.runId,
attemptId: command.attemptId,
offerId: command.offerId,
executionDigest: command.executionDigest,
values: [{ secretRef, value: 'resolved-value' }],
dispose() { disposed += 1; },
};
},
},
});
const leaseToken = 'worker_generated_lease_capability_0000000000000001';
const body = {
schema: 'qinglong/remote-secret-delivery@v1',
runId: 'run-1', attemptId: 'attempt-1', projectId: 'project-1',
taskId: 'task-1', taskRevision: 'revision-1', executionDigest,
workerGeneration: 2, offerId: 'offer-1', leaseGeneration: 3,
leaseToken, expectedLeaseVersion: 4, secretRefs: [secretRef],
};
const result = await (await pipeline.prepare(metadata('secrets'))).handle(body);
assert.equal(result.statusCode, 200);
assert.equal(result.body.schema, 'qinglong/remote-secret-delivery@v1');
assert.deepEqual(result.body.values, [
{ secretRef, value: 'resolved-value' },
]);
assert.equal(JSON.stringify(result.body).includes(leaseToken), false);
const { schema: _schema, ...commandBody } = body;
assert.deepEqual(observed, {
principal: { workerId: 'edge-1' },
command: {
...commandBody,
workerSessionId: SESSION_ID,
},
});
assert.equal(disposed, 1);
});
test('maps stale Secret delivery authority to conflict before any response', async () => {
const secretRef = createSecretRef({ projectId: 'project-1', name: 'token' });
const { pipeline } = fixture({
secrets: {
async deliver() {
throw new RemoteWorkerSecretDeliveryFenceRejectedError('authority_mismatch');
},
},
});
await assert.rejects(
(await pipeline.prepare(metadata('secrets'))).handle({
schema: 'qinglong/remote-secret-delivery@v1',
runId: 'run-1', attemptId: 'attempt-1', projectId: 'project-1',
taskId: 'task-1', taskRevision: 'revision-1',
executionDigest: 'c'.repeat(64), workerGeneration: 2,
offerId: 'offer-1', leaseGeneration: 3,
leaseToken: 'worker_generated_lease_capability_0000000000000001',
expectedLeaseVersion: 4, secretRefs: [secretRef],
}),
(error) =>
error.statusCode === 409 && error.code === 'worker_secret_delivery_fenced',
);
});
test('rejects a Secret service response whose authority drifts', async () => {
const secretRef = createSecretRef({ projectId: 'project-1', name: 'token' });
const { pipeline } = fixture({
secrets: {
async deliver(command) {
return {
runId: 'run-other', attemptId: 'attempt-1', offerId: 'offer-1',
executionDigest: 'c'.repeat(64),
values: [{ secretRef, value: 'must-not-escape' }],
};
},
},
});
await assert.rejects(
(await pipeline.prepare(metadata('secrets'))).handle({
schema: 'qinglong/remote-secret-delivery@v1',
runId: 'run-1', attemptId: 'attempt-1', projectId: 'project-1',
taskId: 'task-1', taskRevision: 'revision-1',
executionDigest: 'c'.repeat(64), workerGeneration: 2,
offerId: 'offer-1', leaseGeneration: 3,
leaseToken: 'worker_generated_lease_capability_0000000000000001',
expectedLeaseVersion: 4, secretRefs: [secretRef],
}),
(error) =>
error.statusCode === 503 && error.code === 'worker_ingress_unavailable',
);
});
test('authenticates and audits before exposing one bounded Artifact stream', async () => {
const content = Buffer.from('worker-log');
let observed;
const { pipeline, events } = fixture({
artifacts: {
async upload(input) {
const chunks = [];
for await (const chunk of input.chunks) chunks.push(Buffer.from(chunk));
observed = { ...input, chunks: undefined, content: Buffer.concat(chunks) };
return {
status: 'stored',
projectId: 'project-1',
runId: 'run-1',
attemptId: 'attempt-1',
logArtifactId: `wlog-${'a'.repeat(30)}`,
byteLength: content.byteLength,
sha256: 'b'.repeat(64),
truncated: false,
};
},
},
});
const request = metadata('artifacts');
const prepared = await pipeline.prepare(request);
assert.deepEqual(events, ['authenticate', 'audit:allowed']);
assert.equal(prepared.bodyMode, 'stream');
assert.equal(prepared.contentType, REMOTE_WORKER_ARTIFACT_CONTENT_TYPE);
assert.equal(prepared.maximumBodyBytes, 64 * 1024 * 1024 + 4 * 1024 + 4);
const result = await prepared.handleStream({
contentLength: content.byteLength,
contentType: REMOTE_WORKER_ARTIFACT_CONTENT_TYPE,
chunks: (async function* () { yield content; })(),
});
assert.equal(result.statusCode, 200);
assert.equal(result.body.schema, 'qinglong/remote-worker-artifact-upload@v1');
assert.equal(result.body.sha256, 'b'.repeat(64));
assert.equal(observed.workerId, 'edge-1');
assert.equal(observed.workerSessionId, SESSION_ID);
assert.equal(observed.contentLength, content.byteLength);
assert.equal(observed.signal, request.signal);
assert.deepEqual(observed.content, content);
});
test('binds completion JSON to path identity and maps stale authority', async () => {
const command = {
workerId: 'edge-1',
workerSessionId: SESSION_ID,
workerGeneration: 2,
projectId: 'project-1',
runId: 'run-1',
attemptId: 'attempt-1',
offerId: 'offer-1',
leaseGeneration: 3,
leaseToken: 'worker_generated_lease_capability_0000000000000001',
expectedLeaseVersion: 4,
callbackSequence: 1,
callbackTokenDigest: 'c'.repeat(64),
result: {
outcome: 'succeeded',
startedAtMs: 100,
finishedAtMs: 200,
exitCode: 0,
},
artifact: {
logArtifactId: `wlog-${'a'.repeat(30)}`,
byteLength: 10,
sha256: 'b'.repeat(64),
truncated: false,
},
};
let observed;
const { pipeline } = fixture({
completion: {
async complete(value, signal) {
observed = { value, signal };
return {
status: 'applied',
runId: value.runId,
attemptId: value.attemptId,
callbackSequence: value.callbackSequence,
};
},
},
});
const request = metadata('completion');
const result = await (await pipeline.prepare(request)).handle(
createRemoteWorkerCompletionRequestBody(command),
);
assert.equal(result.statusCode, 200);
assert.deepEqual(result.body, {
schema: 'qinglong/remote-worker-completion@v1',
status: 'applied',
runId: 'run-1',
attemptId: 'attempt-1',
callbackSequence: 1,
});
assert.deepEqual(observed.value, command);
assert.equal(observed.signal, request.signal);
const fenced = fixture({
completion: {
async complete() {
throw new RemoteWorkerCompletionFenceRejectedError(
'attempt-1',
'authority_mismatch',
);
},
},
});
await assert.rejects(
(await fenced.pipeline.prepare(metadata('completion'))).handle(
createRemoteWorkerCompletionRequestBody(command),
),
(error) =>
error.statusCode === 409 && error.code === 'worker_completion_fenced',
);
});
test('binds lease control to path authority and returns a capability-free response', async () => {
const leaseToken = 'worker_generated_lease_capability_0000000000000001';
let observed;
const { pipeline } = fixture({
leaseControl: {
async control(command) {
observed = command;
return {
status: 'stop_requested',
projectId: command.projectId,
runId: command.runId,
attemptId: command.attemptId,
offerId: command.offerId,
leaseGeneration: command.leaseGeneration,
leaseVersion: command.expectedLeaseVersion + 1,
renewedAtMs: 20_000,
expiresAtMs: 50_000,
stop: { reason: 'timeout', requestedAtMs: 19_000 },
};
},
},
});
const result = await (await pipeline.prepare(metadata('lease-control'))).handle({
schema: 'qinglong/remote-worker-lease-control@v1',
workerGeneration: 2,
projectId: 'project-1',
runId: 'run-1',
attemptId: 'attempt-1',
offerId: 'offer-1',
leaseGeneration: 3,
leaseToken,
expectedLeaseVersion: 4,
});
assert.deepEqual(observed, {
workerId: 'edge-1',
workerSessionId: SESSION_ID,
workerGeneration: 2,
projectId: 'project-1',
runId: 'run-1',
attemptId: 'attempt-1',
offerId: 'offer-1',
leaseGeneration: 3,
leaseToken,
expectedLeaseVersion: 4,
});
assert.deepEqual(result, {
statusCode: 200,
body: {
schema: 'qinglong/remote-worker-lease-control@v1',
status: 'stop_requested',
projectId: 'project-1',
runId: 'run-1',
attemptId: 'attempt-1',
offerId: 'offer-1',
leaseGeneration: 3,
leaseVersion: 5,
renewedAtMs: 20_000,
expiresAtMs: 50_000,
stop: { reason: 'timeout', requestedAtMs: 19_000 },
terminalStatus: null,
},
});
assert.equal(JSON.stringify(result).includes(leaseToken), false);
});
test('maps fenced and unavailable lease control without leaking authority', async () => {
const body = {
schema: 'qinglong/remote-worker-lease-control@v1',
workerGeneration: 2,
projectId: 'project-1',
runId: 'run-1',
attemptId: 'attempt-1',
offerId: 'offer-1',
leaseGeneration: 3,
leaseToken: 'worker_generated_lease_capability_0000000000000001',
expectedLeaseVersion: 4,
};
const fenced = fixture({
leaseControl: {
async control() {
throw new RemoteWorkerLeaseControlFenceRejectedError(
'attempt-1', 'version_mismatch',
);
},
},
});
await assert.rejects(
(await fenced.pipeline.prepare(metadata('lease-control'))).handle(body),
(error) => error.statusCode === 409 && error.code === 'worker_lease_control_fenced',
);
const unavailable = fixture({
leaseControl: {
async control() { throw new RemoteWorkerLeaseControlUnavailableError(); },
},
});
await assert.rejects(
(await unavailable.pipeline.prepare(metadata('lease-control'))).handle(body),
(error) => error.statusCode === 503 && error.code === 'worker_ingress_unavailable',
);
});
@@ -0,0 +1,191 @@
'use strict';
const assert = require('node:assert/strict');
const { test } = require('node:test');
const {
ClusterWorkflowSchedulerCoordinator,
} = require('@qinglong/cluster-control/workflow-scheduler');
const DIGEST_A = 'a'.repeat(64);
const DIGEST_B = 'b'.repeat(64);
function schedulerSummary() {
return Object.freeze({
firstClaimAcquiredAtMs: null,
lastClaimAcquiredAtMs: null,
claimed: 0,
initialized: 0,
skipped: 0,
admitted: 0,
raced: 0,
saturated: false,
});
}
test('advances Workflow frontier and admits Tasks inside one existing scheduler cadence', async () => {
const calls = [];
const scheduler = {
async scheduleOnce() {
calls.push('schedule');
return schedulerSummary();
},
};
const frontier = {
async listCandidates(query) {
calls.push(`frontier:list:${query.after?.planDigest ?? 'start'}`);
if (!query.after) {
return {
candidates: [
{ runId: 'run-a' },
{ runId: 'run-b' },
],
truncated: true,
next: { admittedAtMs: 2, planDigest: DIGEST_A },
};
}
return {
candidates: [{ runId: 'run-c' }],
truncated: false,
};
},
async advance(runId) {
calls.push(`frontier:advance:${runId}`);
return { status: 'advanced' };
},
};
const taskAttempts = {
async listCandidates(query) {
calls.push(`attempt:list:${query.after?.stepRunId ?? 'start'}`);
if (!query.after) {
return {
candidates: [
{ runId: 'run-a', stepRunId: 'step-a' },
{ runId: 'run-b', stepRunId: 'step-b' },
],
truncated: true,
next: { readyAtMs: 3, stepRunId: 'step-b' },
};
}
return {
candidates: [{ runId: 'run-c', stepRunId: 'step-c' }],
truncated: false,
};
},
async admit(runId, stepRunId) {
calls.push(`attempt:admit:${runId}:${stepRunId}`);
return {
status: stepRunId === 'step-b' ? 'existing' : 'created',
receipt: {},
};
},
};
const coordinator = new ClusterWorkflowSchedulerCoordinator(
scheduler,
frontier,
taskAttempts,
{
frontierPageSize: 2,
frontierMaxPages: 2,
taskAttemptPageSize: 2,
taskAttemptMaxPages: 2,
},
);
assert.deepEqual(await coordinator.scheduleOnce(), schedulerSummary());
assert.deepEqual(coordinator.latestWorkflowSummary(), {
frontierPages: 2,
frontierScanned: 3,
frontierAdvanced: 3,
frontierTruncated: false,
taskAttemptPages: 2,
taskAttemptsScanned: 3,
taskAttemptsCreated: 2,
taskAttemptsExisting: 1,
taskAttemptsTruncated: false,
});
assert.deepEqual(calls, [
'schedule',
'frontier:list:start',
'frontier:advance:run-a',
'frontier:advance:run-b',
`frontier:list:${DIGEST_A}`,
'frontier:advance:run-c',
'attempt:list:start',
'attempt:admit:run-a:step-a',
'attempt:admit:run-b:step-b',
'attempt:list:step-b',
'attempt:admit:run-c:step-c',
]);
});
test('coalesces overlapping cycles and fails closed on a stale continuation', async () => {
let release;
let schedulerCalls = 0;
const scheduled = new Promise((resolve) => {
release = resolve;
});
const coordinator = new ClusterWorkflowSchedulerCoordinator(
{
async scheduleOnce() {
schedulerCalls += 1;
await scheduled;
return schedulerSummary();
},
},
{
async listCandidates() {
return {
candidates: [{ runId: 'run-a' }],
truncated: true,
next: { admittedAtMs: 1, planDigest: DIGEST_B },
};
},
async advance() {
return { status: 'advanced' };
},
},
{
async listCandidates() {
return { candidates: [], truncated: false };
},
async admit() {
throw new Error('unexpected admission');
},
},
{
frontierPageSize: 1,
frontierMaxPages: 2,
taskAttemptPageSize: 1,
taskAttemptMaxPages: 1,
},
);
const first = coordinator.scheduleOnce();
const second = coordinator.scheduleOnce();
assert.equal(first, second);
release();
await assert.rejects(
first,
/frontier continuation did not advance/,
);
assert.equal(schedulerCalls, 1);
assert.equal(coordinator.latestWorkflowSummary(), undefined);
});
test('rejects invalid bounds before touching the production scheduler', () => {
assert.throws(
() =>
new ClusterWorkflowSchedulerCoordinator(
{ scheduleOnce() {} },
{ listCandidates() {}, advance() {} },
{ listCandidates() {}, admit() {} },
{
frontierPageSize: 65,
frontierMaxPages: 1,
taskAttemptPageSize: 1,
taskAttemptMaxPages: 1,
},
),
/frontier page size must be between 1 and 64/,
);
});