mirror of
https://github.com/whyour/qinglong.git
synced 2026-09-20 16:07:11 +08:00
feat(ql3): separate cluster secret transition authority
This commit is contained in:
@@ -270,6 +270,21 @@
|
||||
"require": "./dist/plugin-package/secret-binding/pluginPackageSecretBindingApprovedAction.js",
|
||||
"default": "./dist/plugin-package/secret-binding/pluginPackageSecretBindingApprovedAction.js"
|
||||
},
|
||||
"./plugin-package-secret-binding-transition-management": {
|
||||
"types": "./dist/plugin-package/secret-binding/pluginPackageSecretBindingTransitionManagement.d.ts",
|
||||
"require": "./dist/plugin-package/secret-binding/pluginPackageSecretBindingTransitionManagement.js",
|
||||
"default": "./dist/plugin-package/secret-binding/pluginPackageSecretBindingTransitionManagement.js"
|
||||
},
|
||||
"./plugin-package-secret-binding-transition-approval-consumer": {
|
||||
"types": "./dist/plugin-package/secret-binding/pluginPackageSecretBindingTransitionApprovalConsumer.d.ts",
|
||||
"require": "./dist/plugin-package/secret-binding/pluginPackageSecretBindingTransitionApprovalConsumer.js",
|
||||
"default": "./dist/plugin-package/secret-binding/pluginPackageSecretBindingTransitionApprovalConsumer.js"
|
||||
},
|
||||
"./plugin-package-secret-binding-transition-approved-action": {
|
||||
"types": "./dist/plugin-package/secret-binding/pluginPackageSecretBindingTransitionApprovedAction.d.ts",
|
||||
"require": "./dist/plugin-package/secret-binding/pluginPackageSecretBindingTransitionApprovedAction.js",
|
||||
"default": "./dist/plugin-package/secret-binding/pluginPackageSecretBindingTransitionApprovedAction.js"
|
||||
},
|
||||
"./plugin-package-lifecycle-management": {
|
||||
"types": "./dist/plugin-package/lifecycle/pluginPackageLifecycleManagement.d.ts",
|
||||
"require": "./dist/plugin-package/lifecycle/pluginPackageLifecycleManagement.js",
|
||||
|
||||
+238
-1
@@ -306,6 +306,27 @@ const SECRET_BINDING_PLAN_KEYS = Object.freeze([
|
||||
'planDigest',
|
||||
'approvalPlanDigest',
|
||||
]);
|
||||
const SECRET_BINDING_TRANSITION_PLAN_KEYS = Object.freeze([
|
||||
'actionRef',
|
||||
'approvalPlanDigest',
|
||||
'plannedAtMs',
|
||||
'expiresAtMs',
|
||||
'kind',
|
||||
'transitionDigest',
|
||||
'projectId',
|
||||
'packageName',
|
||||
'previousInstallationId',
|
||||
'previousGeneration',
|
||||
'previousGenerationDigest',
|
||||
'previousActiveLockDigest',
|
||||
'previousAttemptGeneration',
|
||||
'nextInstallationId',
|
||||
'nextGeneration',
|
||||
'nextGenerationDigest',
|
||||
'nextLockDigest',
|
||||
'nextManifestDigest',
|
||||
'changes',
|
||||
]);
|
||||
|
||||
function validateScalarSummary(value: unknown, keys: readonly string[]): void {
|
||||
const record = exactResponseObject(value, keys);
|
||||
@@ -586,10 +607,224 @@ function validateSecretBindingPlanSummary(
|
||||
}
|
||||
}
|
||||
|
||||
function validateSecretBindingTransitionPlanSummary(
|
||||
value: unknown,
|
||||
command: Readonly<ClusterPluginPackageManagementCommand>,
|
||||
): void {
|
||||
const summary = exactResponseObject(
|
||||
value,
|
||||
SECRET_BINDING_TRANSITION_PLAN_KEYS,
|
||||
);
|
||||
const transitionRequest = command.request as { readonly actionRef: string };
|
||||
if (
|
||||
typeof summary.actionRef !== 'string' ||
|
||||
summary.actionRef !== transitionRequest.actionRef ||
|
||||
typeof summary.projectId !== 'string' ||
|
||||
typeof summary.packageName !== 'string' ||
|
||||
!PACKAGE_NAME_PATTERN.test(summary.packageName) ||
|
||||
typeof summary.previousInstallationId !== 'string' ||
|
||||
typeof summary.nextInstallationId !== 'string' ||
|
||||
!['carry-forward', 'rotate', 'rebind', 'revoke'].includes(
|
||||
String(summary.kind),
|
||||
) ||
|
||||
!Number.isSafeInteger(summary.plannedAtMs) ||
|
||||
!Number.isSafeInteger(summary.expiresAtMs) ||
|
||||
(summary.expiresAtMs as number) <= (summary.plannedAtMs as number) ||
|
||||
!Number.isSafeInteger(summary.previousGeneration) ||
|
||||
!Number.isSafeInteger(summary.previousAttemptGeneration) ||
|
||||
!Number.isSafeInteger(summary.nextGeneration) ||
|
||||
(summary.previousGeneration as number) < 1 ||
|
||||
(summary.previousAttemptGeneration as number) <
|
||||
(summary.previousGeneration as number) ||
|
||||
(summary.nextGeneration as number) !==
|
||||
(summary.previousAttemptGeneration as number) + 1 ||
|
||||
!Array.isArray(summary.changes) ||
|
||||
summary.changes.length < 1 ||
|
||||
summary.changes.length > 64
|
||||
) {
|
||||
throw new ClusterPluginPackageManagementClientRequestError();
|
||||
}
|
||||
for (const key of [
|
||||
'approvalPlanDigest',
|
||||
'transitionDigest',
|
||||
'previousGenerationDigest',
|
||||
'previousActiveLockDigest',
|
||||
'nextGenerationDigest',
|
||||
'nextLockDigest',
|
||||
'nextManifestDigest',
|
||||
]) {
|
||||
if (
|
||||
typeof summary[key] !== 'string' ||
|
||||
!DIGEST_PATTERN.test(summary[key] as string)
|
||||
) {
|
||||
throw new ClusterPluginPackageManagementClientRequestError();
|
||||
}
|
||||
}
|
||||
const nextEntries = new Map<string, string | null>();
|
||||
const changedNames = new Set<string>();
|
||||
for (const changeValue of summary.changes) {
|
||||
const change = exactResponseObject(changeValue, [
|
||||
'name',
|
||||
'requirement',
|
||||
'reference',
|
||||
'previous',
|
||||
'next',
|
||||
]);
|
||||
if (
|
||||
typeof change.name !== 'string' ||
|
||||
!/^[A-Z_][A-Z0-9_]{0,127}$/.test(change.name) ||
|
||||
changedNames.has(change.name) ||
|
||||
!['added', 'removed', 'tightened', 'relaxed', 'unchanged'].includes(
|
||||
String(change.requirement),
|
||||
) ||
|
||||
!['bound', 'revoked', 'rotated', 'rebound', 'unchanged'].includes(
|
||||
String(change.reference),
|
||||
)
|
||||
) {
|
||||
throw new ClusterPluginPackageManagementClientRequestError();
|
||||
}
|
||||
changedNames.add(change.name as string);
|
||||
for (const stateValue of [change.previous, change.next]) {
|
||||
if (stateValue === null) continue;
|
||||
const state = exactResponseObject(stateValue, ['required', 'secretRef']);
|
||||
if (
|
||||
typeof state.required !== 'boolean' ||
|
||||
(state.secretRef !== null && typeof state.secretRef !== 'string') ||
|
||||
(state.required && state.secretRef === null)
|
||||
) {
|
||||
throw new ClusterPluginPackageManagementClientRequestError();
|
||||
}
|
||||
if (state.secretRef !== null) {
|
||||
try {
|
||||
const reference = parseSecretRef(state.secretRef as string);
|
||||
if (reference.projectId !== summary.projectId) {
|
||||
throw new ClusterPluginPackageManagementClientRequestError();
|
||||
}
|
||||
} catch (error) {
|
||||
if (error instanceof ClusterPluginPackageManagementClientRequestError) {
|
||||
throw error;
|
||||
}
|
||||
throw new ClusterPluginPackageManagementClientRequestError();
|
||||
}
|
||||
}
|
||||
}
|
||||
if (change.next !== null) {
|
||||
nextEntries.set(
|
||||
change.name as string,
|
||||
(change.next as JsonObject).secretRef as string | null,
|
||||
);
|
||||
}
|
||||
}
|
||||
if (
|
||||
command.operation === 'plugin-package.secret-binding.transition.plan' &&
|
||||
(summary.projectId !== command.request.projectId ||
|
||||
summary.packageName !== command.request.packageName ||
|
||||
nextEntries.size !== command.request.assignments.length ||
|
||||
command.request.assignments.some(
|
||||
(assignment) =>
|
||||
nextEntries.get(assignment.name) !== assignment.secretRef,
|
||||
))
|
||||
) {
|
||||
throw new ClusterPluginPackageManagementClientRequestError();
|
||||
}
|
||||
}
|
||||
|
||||
function validateResult(
|
||||
value: unknown,
|
||||
command: Readonly<ClusterPluginPackageManagementCommand>,
|
||||
): Readonly<ClusterPluginPackageManagementTransportResult> {
|
||||
if (command.operation === 'plugin-package.secret-binding.transition.plan') {
|
||||
const result = exactResponseObject(value, [
|
||||
'schemaVersion',
|
||||
'operation',
|
||||
'status',
|
||||
'plan',
|
||||
]);
|
||||
if (
|
||||
result.schemaVersion !== 1 ||
|
||||
result.operation !== command.operation ||
|
||||
!['created', 'existing'].includes(String(result.status))
|
||||
) {
|
||||
throw new ClusterPluginPackageManagementClientRequestError();
|
||||
}
|
||||
validateSecretBindingTransitionPlanSummary(result.plan, command);
|
||||
return Object.freeze(
|
||||
result as unknown as ClusterPluginPackageManagementTransportResult,
|
||||
);
|
||||
}
|
||||
if (command.operation === 'plugin-package.secret-binding.transition.propose') {
|
||||
const result = exactResponseObject(value, [
|
||||
'schemaVersion',
|
||||
'operation',
|
||||
'approvalStatus',
|
||||
'plan',
|
||||
'approval',
|
||||
]);
|
||||
if (
|
||||
result.schemaVersion !== 1 ||
|
||||
result.operation !== command.operation ||
|
||||
!['created', 'existing'].includes(String(result.approvalStatus))
|
||||
) {
|
||||
throw new ClusterPluginPackageManagementClientRequestError();
|
||||
}
|
||||
validateSecretBindingTransitionPlanSummary(result.plan, command);
|
||||
validateScalarSummary(result.approval, APPROVAL_KEYS);
|
||||
const plan = result.plan as JsonObject;
|
||||
const approval = result.approval as JsonObject;
|
||||
if (
|
||||
approval.id !== command.request.approvalRequestId ||
|
||||
approval.projectId !== plan.projectId ||
|
||||
approval.actionDigest !== plan.approvalPlanDigest ||
|
||||
approval.previewDigest !== plan.transitionDigest
|
||||
) {
|
||||
throw new ClusterPluginPackageManagementClientRequestError();
|
||||
}
|
||||
return Object.freeze(
|
||||
result as unknown as ClusterPluginPackageManagementTransportResult,
|
||||
);
|
||||
}
|
||||
if (command.operation === 'plugin-package.secret-binding.transition.inspect') {
|
||||
const result = exactResponseObject(value, [
|
||||
'schemaVersion',
|
||||
'operation',
|
||||
'plan',
|
||||
'approval',
|
||||
'stale',
|
||||
]);
|
||||
if (
|
||||
result.schemaVersion !== 1 ||
|
||||
result.operation !== command.operation ||
|
||||
typeof result.stale !== 'boolean' ||
|
||||
(result.plan === null && result.approval === null)
|
||||
) {
|
||||
throw new ClusterPluginPackageManagementClientRequestError();
|
||||
}
|
||||
if (result.plan !== null) {
|
||||
validateSecretBindingTransitionPlanSummary(result.plan, command);
|
||||
}
|
||||
if (result.approval !== null) {
|
||||
validateScalarSummary(result.approval, APPROVAL_KEYS);
|
||||
if (
|
||||
(result.approval as JsonObject).id !== command.request.approvalRequestId
|
||||
) {
|
||||
throw new ClusterPluginPackageManagementClientRequestError();
|
||||
}
|
||||
}
|
||||
if (result.plan !== null && result.approval !== null) {
|
||||
const plan = result.plan as JsonObject;
|
||||
const approval = result.approval as JsonObject;
|
||||
if (
|
||||
approval.projectId !== plan.projectId ||
|
||||
approval.actionDigest !== plan.approvalPlanDigest ||
|
||||
approval.previewDigest !== plan.transitionDigest
|
||||
) {
|
||||
throw new ClusterPluginPackageManagementClientRequestError();
|
||||
}
|
||||
}
|
||||
return Object.freeze(
|
||||
result as unknown as ClusterPluginPackageManagementTransportResult,
|
||||
);
|
||||
}
|
||||
if (command.operation === 'plugin-package.secret-binding.plan') {
|
||||
const result = exactResponseObject(value, [
|
||||
'schemaVersion',
|
||||
@@ -835,7 +1070,9 @@ function validateResult(
|
||||
if (result.approval !== null) {
|
||||
validateScalarSummary(result.approval, APPROVAL_KEYS);
|
||||
if (
|
||||
command.operation === 'plugin-package.secret-binding.decide' &&
|
||||
(command.operation === 'plugin-package.secret-binding.decide' ||
|
||||
command.operation ===
|
||||
'plugin-package.secret-binding.transition.decide') &&
|
||||
(result.approval as JsonObject).id !== command.request.approvalRequestId
|
||||
) {
|
||||
throw new ClusterPluginPackageManagementClientRequestError();
|
||||
|
||||
@@ -10,6 +10,8 @@ import { PostgresPluginPackageInstallRepository } from '@qinglong/cluster-postgr
|
||||
import {
|
||||
PostgresPluginPackageSecretBindingApprovalPlanReader,
|
||||
PostgresPluginPackageSecretBindingRepository,
|
||||
PostgresPluginPackageSecretBindingTransitionApprovalPlanReader,
|
||||
PostgresPluginPackageSecretBindingTransitionRepository,
|
||||
} from '@qinglong/cluster-postgres/package-executor';
|
||||
import { PostgresPluginPackageInstallProposalRepository } from '@qinglong/cluster-postgres/plugin-package-proposal';
|
||||
import {
|
||||
@@ -27,6 +29,7 @@ import {
|
||||
type ClusterPluginPackagePublisherTrustTransitionExecutionPort,
|
||||
} from '../publisher/pluginPackagePublisherTrustTransitionApprovedAction';
|
||||
import { ClusterPluginPackageSecretBindingApprovedActionHandler } from '../secret-binding/pluginPackageSecretBindingApprovedAction';
|
||||
import { ClusterPluginPackageSecretBindingTransitionApprovedActionHandler } from '../secret-binding/pluginPackageSecretBindingTransitionApprovedAction';
|
||||
import type { PluginPackageSecretExistenceInspector } from '../secret-binding/projectedSecretExistenceInspector';
|
||||
|
||||
export const CLUSTER_PLUGIN_PACKAGE_DISPATCH_BATCH_LIMIT = 16;
|
||||
@@ -66,6 +69,11 @@ export function createClusterPluginPackageApprovedActionDispatcher(
|
||||
new PostgresPluginPackageSecretBindingRepository(pool),
|
||||
secretExistenceInspector,
|
||||
),
|
||||
new ClusterPluginPackageSecretBindingTransitionApprovedActionHandler(
|
||||
new PostgresPluginPackageSecretBindingTransitionApprovalPlanReader(pool),
|
||||
new PostgresPluginPackageSecretBindingTransitionRepository(pool),
|
||||
secretExistenceInspector,
|
||||
),
|
||||
...(['overlap_add', 'safe_retire'] as const).map(
|
||||
(mode) =>
|
||||
new ClusterPluginPackagePublisherTrustTransitionApprovedActionHandler(
|
||||
|
||||
+24
@@ -39,6 +39,11 @@ import {
|
||||
type ClusterPluginPackageSecretBindingApprovalSummary,
|
||||
type ConsumeClusterPluginPackageSecretBindingApprovalsOptions,
|
||||
} from '../secret-binding/pluginPackageSecretBindingApprovalConsumer';
|
||||
import {
|
||||
consumeClusterPluginPackageSecretBindingTransitionApprovals,
|
||||
type ClusterPluginPackageSecretBindingTransitionApprovalSummary,
|
||||
type ConsumeClusterPluginPackageSecretBindingTransitionApprovalsOptions,
|
||||
} from '../secret-binding/pluginPackageSecretBindingTransitionApprovalConsumer';
|
||||
import { ProjectedPluginPackageSecretExistenceInspector } from '../secret-binding/projectedSecretExistenceInspector';
|
||||
import {
|
||||
runClusterPluginPackagePublisherRevocation,
|
||||
@@ -70,6 +75,7 @@ export interface ClusterPluginPackageExecutorBatchResult {
|
||||
readonly approvals: Readonly<ClusterPluginPackagePublisherRevocationApprovalSummary>;
|
||||
readonly trustTransitionApprovals: Readonly<ClusterPluginPackagePublisherTrustTransitionApprovalSummary>;
|
||||
readonly secretBindingApprovals: Readonly<ClusterPluginPackageSecretBindingApprovalSummary>;
|
||||
readonly secretBindingTransitionApprovals: Readonly<ClusterPluginPackageSecretBindingTransitionApprovalSummary>;
|
||||
readonly dispatch: Readonly<ApprovedActionDispatchBatchSummary>;
|
||||
}
|
||||
|
||||
@@ -97,6 +103,11 @@ export interface RunClusterPluginPackageExecutorProcessOptions {
|
||||
readonly consumeSecretBindingApprovals?: (
|
||||
options: ConsumeClusterPluginPackageSecretBindingApprovalsOptions,
|
||||
) => Promise<Readonly<ClusterPluginPackageSecretBindingApprovalSummary>>;
|
||||
readonly consumeSecretBindingTransitionApprovals?: (
|
||||
options: ConsumeClusterPluginPackageSecretBindingTransitionApprovalsOptions,
|
||||
) => Promise<
|
||||
Readonly<ClusterPluginPackageSecretBindingTransitionApprovalSummary>
|
||||
>;
|
||||
readonly createDispatcher?: (
|
||||
options: ClusterPluginPackageApprovedActionDispatcherOptions,
|
||||
) => ApprovedActionDispatcher;
|
||||
@@ -375,6 +386,7 @@ function isIdleBatch(
|
||||
batch.approvals.scanned === 0 &&
|
||||
batch.trustTransitionApprovals.scanned === 0 &&
|
||||
batch.secretBindingApprovals.scanned === 0 &&
|
||||
batch.secretBindingTransitionApprovals.scanned === 0 &&
|
||||
batch.dispatch.scanned === 0
|
||||
);
|
||||
}
|
||||
@@ -395,6 +407,8 @@ export async function runClusterPluginPackageExecutorProcess(
|
||||
typeof options.consumeTrustTransitionApprovals !== 'function') ||
|
||||
(options.consumeSecretBindingApprovals !== undefined &&
|
||||
typeof options.consumeSecretBindingApprovals !== 'function') ||
|
||||
(options.consumeSecretBindingTransitionApprovals !== undefined &&
|
||||
typeof options.consumeSecretBindingTransitionApprovals !== 'function') ||
|
||||
(options.createDispatcher !== undefined &&
|
||||
typeof options.createDispatcher !== 'function') ||
|
||||
(options.now !== undefined && typeof options.now !== 'function')
|
||||
@@ -431,6 +445,9 @@ export async function runClusterPluginPackageExecutorProcess(
|
||||
const consumeSecretBindingApprovals =
|
||||
options.consumeSecretBindingApprovals ??
|
||||
consumeClusterPluginPackageSecretBindingApprovals;
|
||||
const consumeSecretBindingTransitionApprovals =
|
||||
options.consumeSecretBindingTransitionApprovals ??
|
||||
consumeClusterPluginPackageSecretBindingTransitionApprovals;
|
||||
const dispatcher = dispatcherFactory({
|
||||
pool: database.pool,
|
||||
owner: config.owner,
|
||||
@@ -487,6 +504,12 @@ export async function runClusterPluginPackageExecutorProcess(
|
||||
limit: config.approvalBatchSize,
|
||||
...(options.now ? { now: options.now } : {}),
|
||||
});
|
||||
const secretBindingTransitionApprovals =
|
||||
await consumeSecretBindingTransitionApprovals({
|
||||
pool: database.pool,
|
||||
limit: config.approvalBatchSize,
|
||||
...(options.now ? { now: options.now } : {}),
|
||||
});
|
||||
const dispatch = await dispatcher.dispatchBatch({
|
||||
limit: config.dispatchBatchSize,
|
||||
});
|
||||
@@ -494,6 +517,7 @@ export async function runClusterPluginPackageExecutorProcess(
|
||||
approvals,
|
||||
trustTransitionApprovals,
|
||||
secretBindingApprovals,
|
||||
secretBindingTransitionApprovals,
|
||||
dispatch,
|
||||
});
|
||||
batches.push(batch);
|
||||
|
||||
+9
@@ -29,6 +29,7 @@ import {
|
||||
import { createClusterPluginPackageManagementService } from './pluginPackageManagement';
|
||||
import { createClusterPluginPackageLifecycleManagementService } from '../lifecycle/pluginPackageLifecycleManagement';
|
||||
import { createClusterPluginPackageSecretBindingManagementService } from '../secret-binding/pluginPackageSecretBindingManagement';
|
||||
import { createClusterPluginPackageSecretBindingTransitionManagementService } from '../secret-binding/pluginPackageSecretBindingTransitionManagement';
|
||||
import {
|
||||
loadClusterPluginPackagePublisherTrustFileEvidence,
|
||||
type ClusterPluginPackagePublisherTrustFileEvidence,
|
||||
@@ -643,11 +644,19 @@ export async function startClusterPluginPackageManagementProcess(
|
||||
now,
|
||||
quota,
|
||||
});
|
||||
const secretBindingTransition =
|
||||
createClusterPluginPackageSecretBindingTransitionManagementService({
|
||||
pool: database.pool,
|
||||
approvalLifetimeMs: config.approvalLifetimeMs,
|
||||
now,
|
||||
quota,
|
||||
});
|
||||
const transport = createClusterPluginPackageManagementTransport({
|
||||
service,
|
||||
lifecycle,
|
||||
publisherTrust,
|
||||
secretBinding,
|
||||
secretBindingTransition,
|
||||
now,
|
||||
});
|
||||
const privateKey = readTlsFile(config.privateKeyFile, true);
|
||||
|
||||
+217
-1
@@ -16,6 +16,7 @@ import type { PluginPackageInstallProposal } from '@qinglong/runtime-core/plugin
|
||||
import type { PluginPackageLifecyclePlan } from '@qinglong/runtime-core/plugin-package-lifecycle-plan';
|
||||
import type { PluginPackageSecretBindingAssignment } from '@qinglong/runtime-core/plugin-package-secret-binding';
|
||||
import type { PluginPackageSecretBindingApprovalPlan } from '@qinglong/runtime-core/plugin-package-secret-binding-approval-plan';
|
||||
import type { PluginPackageSecretBindingTransitionApprovalPlan } from '@qinglong/runtime-core/plugin-package-secret-binding-transition-approval-plan';
|
||||
import {
|
||||
normalizeSecurityPrincipal,
|
||||
type SecurityPrincipal,
|
||||
@@ -28,6 +29,7 @@ import type {
|
||||
InspectClusterPluginPackagePublisherTrustTransitionResult,
|
||||
} from '../publisher/pluginPackagePublisherTrustManagement';
|
||||
import type { ClusterPluginPackageSecretBindingManagementService } from '../secret-binding/pluginPackageSecretBindingManagement';
|
||||
import type { ClusterPluginPackageSecretBindingTransitionManagementService } from '../secret-binding/pluginPackageSecretBindingTransitionManagement';
|
||||
|
||||
const STRONG_CLUSTER_ASSURANCES = new Set(['multi_factor', 'hardware']);
|
||||
|
||||
@@ -202,6 +204,30 @@ export interface InspectClusterPluginPackageSecretBindingCommand {
|
||||
readonly request: InspectClusterPluginPackageCommand['request'];
|
||||
}
|
||||
|
||||
export interface PlanClusterPluginPackageSecretBindingTransitionCommand {
|
||||
readonly schemaVersion: 1;
|
||||
readonly operation: 'plugin-package.secret-binding.transition.plan';
|
||||
readonly request: PlanClusterPluginPackageSecretBindingCommand['request'];
|
||||
}
|
||||
|
||||
export interface ProposeClusterPluginPackageSecretBindingTransitionCommand {
|
||||
readonly schemaVersion: 1;
|
||||
readonly operation: 'plugin-package.secret-binding.transition.propose';
|
||||
readonly request: ProposeClusterPluginPackageSecretBindingCommand['request'];
|
||||
}
|
||||
|
||||
export interface DecideClusterPluginPackageSecretBindingTransitionCommand {
|
||||
readonly schemaVersion: 1;
|
||||
readonly operation: 'plugin-package.secret-binding.transition.decide';
|
||||
readonly request: DecideClusterPluginPackageSecretBindingCommand['request'];
|
||||
}
|
||||
|
||||
export interface InspectClusterPluginPackageSecretBindingTransitionCommand {
|
||||
readonly schemaVersion: 1;
|
||||
readonly operation: 'plugin-package.secret-binding.transition.inspect';
|
||||
readonly request: InspectClusterPluginPackageSecretBindingCommand['request'];
|
||||
}
|
||||
|
||||
export type ClusterPluginPackageManagementCommand =
|
||||
| ProposeClusterPluginPackageCommand
|
||||
| DecideClusterPluginPackageCommand
|
||||
@@ -220,7 +246,11 @@ export type ClusterPluginPackageManagementCommand =
|
||||
| PlanClusterPluginPackageSecretBindingCommand
|
||||
| ProposeClusterPluginPackageSecretBindingCommand
|
||||
| DecideClusterPluginPackageSecretBindingCommand
|
||||
| InspectClusterPluginPackageSecretBindingCommand;
|
||||
| InspectClusterPluginPackageSecretBindingCommand
|
||||
| PlanClusterPluginPackageSecretBindingTransitionCommand
|
||||
| ProposeClusterPluginPackageSecretBindingTransitionCommand
|
||||
| DecideClusterPluginPackageSecretBindingTransitionCommand
|
||||
| InspectClusterPluginPackageSecretBindingTransitionCommand;
|
||||
|
||||
export type ClusterPluginPackageManagementTransportResult =
|
||||
| Readonly<{
|
||||
@@ -342,6 +372,32 @@ export type ClusterPluginPackageManagementTransportResult =
|
||||
plan: ReturnType<typeof secretBindingPlanSummary> | null;
|
||||
approval: ReturnType<typeof approvalSummary> | null;
|
||||
stale: boolean;
|
||||
}>
|
||||
| Readonly<{
|
||||
schemaVersion: 1;
|
||||
operation: 'plugin-package.secret-binding.transition.plan';
|
||||
status: 'created' | 'existing';
|
||||
plan: ReturnType<typeof secretBindingTransitionPlanSummary>;
|
||||
}>
|
||||
| Readonly<{
|
||||
schemaVersion: 1;
|
||||
operation: 'plugin-package.secret-binding.transition.propose';
|
||||
approvalStatus: 'created' | 'existing';
|
||||
plan: ReturnType<typeof secretBindingTransitionPlanSummary>;
|
||||
approval: ReturnType<typeof approvalSummary>;
|
||||
}>
|
||||
| Readonly<{
|
||||
schemaVersion: 1;
|
||||
operation: 'plugin-package.secret-binding.transition.decide';
|
||||
status: 'decided' | 'existing';
|
||||
approval: ReturnType<typeof approvalSummary>;
|
||||
}>
|
||||
| Readonly<{
|
||||
schemaVersion: 1;
|
||||
operation: 'plugin-package.secret-binding.transition.inspect';
|
||||
plan: ReturnType<typeof secretBindingTransitionPlanSummary> | null;
|
||||
approval: ReturnType<typeof approvalSummary> | null;
|
||||
stale: boolean;
|
||||
}>;
|
||||
|
||||
export interface ClusterPluginPackageManagementTransport {
|
||||
@@ -356,6 +412,7 @@ export interface ClusterPluginPackageManagementTransportOptions {
|
||||
readonly lifecycle?: ClusterPluginPackageLifecycleManagementService;
|
||||
readonly publisherTrust?: ClusterPluginPackagePublisherTrustManagementService;
|
||||
readonly secretBinding?: ClusterPluginPackageSecretBindingManagementService;
|
||||
readonly secretBindingTransition?: ClusterPluginPackageSecretBindingTransitionManagementService;
|
||||
readonly now?: () => number;
|
||||
}
|
||||
|
||||
@@ -639,6 +696,54 @@ export function normalizeClusterPluginPackageManagementCommand(
|
||||
'Secret binding inspection request',
|
||||
);
|
||||
break;
|
||||
case 'plugin-package.secret-binding.transition.plan':
|
||||
exactObject(
|
||||
value.request,
|
||||
['actionRef', 'assignments', 'packageName', 'projectId'],
|
||||
'Secret transition plan request',
|
||||
);
|
||||
if (!Array.isArray(value.request.assignments)) {
|
||||
throw new ClusterPluginPackageManagementTransportRequestError(
|
||||
'Secret transition assignments are invalid',
|
||||
);
|
||||
}
|
||||
for (const assignment of value.request.assignments) {
|
||||
exactObject(
|
||||
assignment,
|
||||
['name', 'secretRef'],
|
||||
'Secret transition assignment',
|
||||
);
|
||||
}
|
||||
break;
|
||||
case 'plugin-package.secret-binding.transition.propose':
|
||||
exactObject(
|
||||
value.request,
|
||||
['actionRef', 'approvalAuditEventId', 'approvalRequestId'],
|
||||
'Secret transition proposal request',
|
||||
);
|
||||
break;
|
||||
case 'plugin-package.secret-binding.transition.decide':
|
||||
exactObject(
|
||||
value.request,
|
||||
[
|
||||
'actionRef',
|
||||
'approvalRequestId',
|
||||
'expectedVersion',
|
||||
'decisionId',
|
||||
'auditEventId',
|
||||
'decision',
|
||||
'reasonCode',
|
||||
],
|
||||
'Secret transition decision request',
|
||||
);
|
||||
break;
|
||||
case 'plugin-package.secret-binding.transition.inspect':
|
||||
exactObject(
|
||||
value.request,
|
||||
['actionRef', 'approvalRequestId', 'inspectionId'],
|
||||
'Secret transition inspection request',
|
||||
);
|
||||
break;
|
||||
default:
|
||||
throw new ClusterPluginPackageManagementTransportRequestError(
|
||||
'operation is not publicly available',
|
||||
@@ -771,6 +876,33 @@ function secretBindingPlanSummary(
|
||||
});
|
||||
}
|
||||
|
||||
function secretBindingTransitionPlanSummary(
|
||||
plan: Readonly<PluginPackageSecretBindingTransitionApprovalPlan>,
|
||||
) {
|
||||
const transition = plan.transitionPlan;
|
||||
return Object.freeze({
|
||||
actionRef: plan.actionRef,
|
||||
approvalPlanDigest: plan.approvalPlanDigest,
|
||||
plannedAtMs: plan.plannedAtMs,
|
||||
expiresAtMs: plan.expiresAtMs,
|
||||
kind: transition.kind,
|
||||
transitionDigest: transition.transitionDigest,
|
||||
projectId: transition.nextTarget.projectId,
|
||||
packageName: transition.nextTarget.packageName,
|
||||
previousInstallationId: transition.previousTarget.installationId,
|
||||
previousGeneration: transition.previousTarget.generation,
|
||||
previousGenerationDigest: transition.previousTarget.generationDigest,
|
||||
previousActiveLockDigest: transition.previousActiveLockDigest,
|
||||
previousAttemptGeneration: transition.previousAttemptGeneration,
|
||||
nextInstallationId: transition.nextTarget.installationId,
|
||||
nextGeneration: transition.nextTarget.generation,
|
||||
nextGenerationDigest: transition.nextTarget.generationDigest,
|
||||
nextLockDigest: transition.nextTarget.lockDigest,
|
||||
nextManifestDigest: transition.nextTarget.manifestDigest,
|
||||
changes: transition.changes,
|
||||
});
|
||||
}
|
||||
|
||||
function publisherRevocationProposalSummary(
|
||||
proposal: NonNullable<
|
||||
InspectClusterPluginPackagePublisherRevocationResult['proposal']
|
||||
@@ -826,6 +958,7 @@ function exactDecisionReplay(
|
||||
| DecideClusterPluginPackagePublisherRevocationCommand
|
||||
| DecideClusterPluginPackagePublisherTrustTransitionCommand
|
||||
| DecideClusterPluginPackageSecretBindingCommand
|
||||
| DecideClusterPluginPackageSecretBindingTransitionCommand
|
||||
>,
|
||||
principal: Readonly<SecurityPrincipal>,
|
||||
): Readonly<DecideApprovalRequestResult> | null {
|
||||
@@ -859,6 +992,7 @@ export function createClusterPluginPackageManagementTransport(
|
||||
key !== 'lifecycle' &&
|
||||
key !== 'publisherTrust' &&
|
||||
key !== 'secretBinding' &&
|
||||
key !== 'secretBindingTransition' &&
|
||||
key !== 'now',
|
||||
) ||
|
||||
!options.service ||
|
||||
@@ -884,6 +1018,13 @@ export function createClusterPluginPackageManagementTransport(
|
||||
typeof options.secretBinding.propose !== 'function' ||
|
||||
typeof options.secretBinding.decide !== 'function' ||
|
||||
typeof options.secretBinding.inspectAuthorized !== 'function')) ||
|
||||
(options.secretBindingTransition !== undefined &&
|
||||
(!options.secretBindingTransition ||
|
||||
typeof options.secretBindingTransition.plan !== 'function' ||
|
||||
typeof options.secretBindingTransition.propose !== 'function' ||
|
||||
typeof options.secretBindingTransition.decide !== 'function' ||
|
||||
typeof options.secretBindingTransition.inspectAuthorized !==
|
||||
'function')) ||
|
||||
(options.now !== undefined && typeof options.now !== 'function')
|
||||
) {
|
||||
throw new ClusterPluginPackageManagementTransportConfigurationError(
|
||||
@@ -1152,6 +1293,81 @@ export function createClusterPluginPackageManagementTransport(
|
||||
stale: result.stale,
|
||||
});
|
||||
}
|
||||
case 'plugin-package.secret-binding.transition.plan': {
|
||||
if (!options.secretBindingTransition) {
|
||||
throw new ClusterPluginPackageManagementTransportConfigurationError(
|
||||
'Secret transition management is not configured',
|
||||
);
|
||||
}
|
||||
const result = await options.secretBindingTransition.plan({
|
||||
...command.request,
|
||||
principal,
|
||||
});
|
||||
return Object.freeze({
|
||||
schemaVersion: 1 as const,
|
||||
operation: command.operation,
|
||||
status: result.status,
|
||||
plan: secretBindingTransitionPlanSummary(result.plan),
|
||||
});
|
||||
}
|
||||
case 'plugin-package.secret-binding.transition.propose': {
|
||||
if (!options.secretBindingTransition) {
|
||||
throw new ClusterPluginPackageManagementTransportConfigurationError(
|
||||
'Secret transition management is not configured',
|
||||
);
|
||||
}
|
||||
const result = await options.secretBindingTransition.propose({
|
||||
...command.request,
|
||||
principal,
|
||||
});
|
||||
return Object.freeze({
|
||||
schemaVersion: 1 as const,
|
||||
operation: command.operation,
|
||||
approvalStatus: result.approvalStatus,
|
||||
plan: secretBindingTransitionPlanSummary(result.plan),
|
||||
approval: approvalSummary(result.approvalRequest),
|
||||
});
|
||||
}
|
||||
case 'plugin-package.secret-binding.transition.decide': {
|
||||
if (!options.secretBindingTransition) {
|
||||
throw new ClusterPluginPackageManagementTransportConfigurationError(
|
||||
'Secret transition management is not configured',
|
||||
);
|
||||
}
|
||||
const result = await options.secretBindingTransition.decide({
|
||||
...command.request,
|
||||
principal,
|
||||
});
|
||||
return Object.freeze({
|
||||
schemaVersion: 1 as const,
|
||||
operation: command.operation,
|
||||
status: result.status,
|
||||
approval: approvalSummary(result.request),
|
||||
});
|
||||
}
|
||||
case 'plugin-package.secret-binding.transition.inspect': {
|
||||
if (!options.secretBindingTransition) {
|
||||
throw new ClusterPluginPackageManagementTransportConfigurationError(
|
||||
'Secret transition management is not configured',
|
||||
);
|
||||
}
|
||||
const result =
|
||||
await options.secretBindingTransition.inspectAuthorized({
|
||||
...command.request,
|
||||
principal,
|
||||
});
|
||||
return Object.freeze({
|
||||
schemaVersion: 1 as const,
|
||||
operation: command.operation,
|
||||
plan: result.plan
|
||||
? secretBindingTransitionPlanSummary(result.plan)
|
||||
: null,
|
||||
approval: result.approvalRequest
|
||||
? approvalSummary(result.approvalRequest)
|
||||
: null,
|
||||
stale: result.stale,
|
||||
});
|
||||
}
|
||||
case 'plugin-package.publisher-revocation.propose': {
|
||||
if (!options.publisherTrust) {
|
||||
throw new ClusterPluginPackageManagementTransportConfigurationError(
|
||||
|
||||
+175
@@ -0,0 +1,175 @@
|
||||
import { createHash } from 'node:crypto';
|
||||
|
||||
import {
|
||||
PostgresApprovalRequestRepository,
|
||||
PostgresPluginPackageSecretBindingTransitionApprovalPlanReader,
|
||||
PostgresProjectPolicyRepository,
|
||||
} from '@qinglong/cluster-postgres/package-executor';
|
||||
import type { PostgresPool } from '@qinglong/runtime-core';
|
||||
import { pluginPackageSecretBindingTransitionApprovedAction } from '@qinglong/runtime-core/plugin-package-secret-binding-transition-approval-plan';
|
||||
import { ProjectPolicyEngine } from '@qinglong/runtime-core/project-policy';
|
||||
|
||||
export const CLUSTER_PLUGIN_PACKAGE_SECRET_BINDING_TRANSITION_APPROVAL_BATCH_LIMIT =
|
||||
16;
|
||||
|
||||
export interface ConsumeClusterPluginPackageSecretBindingTransitionApprovalsOptions {
|
||||
readonly pool: PostgresPool;
|
||||
readonly now?: () => number;
|
||||
readonly limit?: number;
|
||||
}
|
||||
|
||||
export interface ClusterPluginPackageSecretBindingTransitionApprovalSummary {
|
||||
readonly scanned: number;
|
||||
readonly consumed: number;
|
||||
readonly existing: number;
|
||||
readonly expired: number;
|
||||
readonly blocked: number;
|
||||
}
|
||||
|
||||
const CONSUMER = Object.freeze({
|
||||
type: 'system' as const,
|
||||
id: 'cluster_package_executor',
|
||||
});
|
||||
|
||||
function stableDigest(domain: string, value: string): string {
|
||||
return createHash('sha256')
|
||||
.update(domain)
|
||||
.update('\0')
|
||||
.update(value)
|
||||
.digest('hex');
|
||||
}
|
||||
|
||||
function stableId(prefix: string, domain: string, value: string): string {
|
||||
return `${prefix}-${stableDigest(domain, value)}`;
|
||||
}
|
||||
|
||||
function stableAuditEventId(requestId: string): string {
|
||||
const bytes = Buffer.from(
|
||||
stableDigest(
|
||||
'qinglong/plugin-package-secret-binding-transition-consume-audit@v1',
|
||||
requestId,
|
||||
),
|
||||
'hex',
|
||||
);
|
||||
bytes[6] = (bytes[6]! & 0x0f) | 0x40;
|
||||
bytes[8] = (bytes[8]! & 0x3f) | 0x80;
|
||||
const hex = bytes.toString('hex');
|
||||
return `${hex.slice(0, 8)}-${hex.slice(8, 12)}-${hex.slice(
|
||||
12,
|
||||
16,
|
||||
)}-${hex.slice(16, 20)}-${hex.slice(20, 32)}`;
|
||||
}
|
||||
|
||||
export async function consumeClusterPluginPackageSecretBindingTransitionApprovals(
|
||||
options: ConsumeClusterPluginPackageSecretBindingTransitionApprovalsOptions,
|
||||
): Promise<
|
||||
Readonly<ClusterPluginPackageSecretBindingTransitionApprovalSummary>
|
||||
> {
|
||||
if (
|
||||
!options ||
|
||||
typeof options !== 'object' ||
|
||||
Array.isArray(options) ||
|
||||
Object.keys(options).some((key) => !['pool', 'now', 'limit'].includes(key)) ||
|
||||
!options.pool ||
|
||||
typeof options.pool.query !== 'function' ||
|
||||
typeof options.pool.connect !== 'function'
|
||||
) {
|
||||
throw new TypeError('Secret transition approval consumer options are invalid');
|
||||
}
|
||||
const limit =
|
||||
options.limit ??
|
||||
CLUSTER_PLUGIN_PACKAGE_SECRET_BINDING_TRANSITION_APPROVAL_BATCH_LIMIT;
|
||||
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 64) {
|
||||
throw new TypeError('Secret transition approval consumer limit is invalid');
|
||||
}
|
||||
const observedAtMs = (options.now ?? Date.now)();
|
||||
if (!Number.isSafeInteger(observedAtMs) || observedAtMs < 0) {
|
||||
throw new TypeError('Secret transition approval consumer clock is invalid');
|
||||
}
|
||||
const plans =
|
||||
new PostgresPluginPackageSecretBindingTransitionApprovalPlanReader(
|
||||
options.pool,
|
||||
);
|
||||
const approvals = new PostgresApprovalRequestRepository(options.pool);
|
||||
const policy = new ProjectPolicyEngine(
|
||||
new PostgresProjectPolicyRepository(options.pool),
|
||||
);
|
||||
const requests = await plans.listApprovedRequests(limit);
|
||||
let consumed = 0;
|
||||
let existing = 0;
|
||||
let expired = 0;
|
||||
let blocked = 0;
|
||||
for (const request of requests) {
|
||||
const plan = await plans.findByActionRef(request.action.actionRef);
|
||||
if (
|
||||
!plan ||
|
||||
request.projectId !== plan.transitionPlan.nextTarget.projectId ||
|
||||
request.decisionMode !== 'separation_of_duty' ||
|
||||
JSON.stringify(request.action) !==
|
||||
JSON.stringify(
|
||||
pluginPackageSecretBindingTransitionApprovedAction(plan),
|
||||
) ||
|
||||
request.requestedBy.type !== plan.requestedBy.type ||
|
||||
request.requestedBy.id !== plan.requestedBy.id
|
||||
) {
|
||||
blocked += 1;
|
||||
continue;
|
||||
}
|
||||
if (observedAtMs >= request.expiresAtMs || observedAtMs > plan.expiresAtMs) {
|
||||
expired += 1;
|
||||
continue;
|
||||
}
|
||||
const decision = await policy.decide({
|
||||
subject: request.requestedBy,
|
||||
projectId: request.projectId,
|
||||
permission: 'secret.manage',
|
||||
});
|
||||
if (
|
||||
decision.fence === null ||
|
||||
(decision.effect !== 'allow' && decision.effect !== 'require_approval')
|
||||
) {
|
||||
blocked += 1;
|
||||
continue;
|
||||
}
|
||||
const result = await approvals.consume({
|
||||
requestId: request.id,
|
||||
expectedVersion: request.version,
|
||||
consumptionId: stableId(
|
||||
'psbtc',
|
||||
'qinglong/plugin-package-secret-binding-transition-consumption@v1',
|
||||
request.id,
|
||||
),
|
||||
dispatchId: stableId(
|
||||
'psbtd',
|
||||
'qinglong/plugin-package-secret-binding-transition-dispatch@v1',
|
||||
request.id,
|
||||
),
|
||||
action: request.action,
|
||||
requestedBy: request.requestedBy,
|
||||
consumedBy: CONSUMER,
|
||||
consumedAtMs: observedAtMs,
|
||||
authorizationFence: decision.fence,
|
||||
audit: {
|
||||
eventId: stableAuditEventId(request.id),
|
||||
requestId: request.id,
|
||||
operationId: 'approval.consume',
|
||||
projectId: request.projectId,
|
||||
subject: CONSUMER,
|
||||
authenticationId: 'cluster-package-executor',
|
||||
outcome: 'allowed',
|
||||
reasons: ['package_secret_binding_transition_execution'],
|
||||
fence: decision.fence,
|
||||
occurredAtMs: observedAtMs,
|
||||
},
|
||||
});
|
||||
if (result.status === 'consumed') consumed += 1;
|
||||
else existing += 1;
|
||||
}
|
||||
return Object.freeze({
|
||||
scanned: requests.length,
|
||||
consumed,
|
||||
existing,
|
||||
expired,
|
||||
blocked,
|
||||
});
|
||||
}
|
||||
+170
@@ -0,0 +1,170 @@
|
||||
import type {
|
||||
ApprovedActionHandler,
|
||||
ApprovedActionHandlerExecutionContext,
|
||||
ApprovedActionHandlerInspection,
|
||||
ApprovedActionHandlerResult,
|
||||
} from '@qinglong/runtime-core/approved-action-dispatcher';
|
||||
import {
|
||||
InvalidPluginPackageSecretBindingTransitionApprovalPlanError,
|
||||
PLUGIN_PACKAGE_SECRET_BINDING_TRANSITION_ACTION_TYPE,
|
||||
normalizePluginPackageSecretBindingTransitionApprovalPlan,
|
||||
pluginPackageSecretBindingTransitionApprovedAction,
|
||||
type PluginPackageSecretBindingTransitionApprovalPlanRepository,
|
||||
} from '@qinglong/runtime-core/plugin-package-secret-binding-transition-approval-plan';
|
||||
import {
|
||||
PluginPackageSecretBindingConflictError,
|
||||
} from '@qinglong/runtime-core/plugin-package-secret-binding';
|
||||
import type {
|
||||
ApplyPostgresPluginPackageSecretBindingTransitionInput,
|
||||
ApplyPostgresPluginPackageSecretBindingTransitionResult,
|
||||
} from '@qinglong/cluster-postgres/package-executor';
|
||||
|
||||
import type { PluginPackageSecretExistenceInspector } from './projectedSecretExistenceInspector';
|
||||
|
||||
export interface ClusterPluginPackageSecretBindingTransitionExecutionPort {
|
||||
apply(
|
||||
input: Readonly<ApplyPostgresPluginPackageSecretBindingTransitionInput>,
|
||||
): Promise<Readonly<ApplyPostgresPluginPackageSecretBindingTransitionResult>>;
|
||||
}
|
||||
|
||||
export class ClusterPluginPackageSecretBindingTransitionApprovedActionHandler
|
||||
implements ApprovedActionHandler
|
||||
{
|
||||
readonly actionType = PLUGIN_PACKAGE_SECRET_BINDING_TRANSITION_ACTION_TYPE;
|
||||
|
||||
constructor(
|
||||
readonly plans: Pick<
|
||||
PluginPackageSecretBindingTransitionApprovalPlanRepository,
|
||||
'findByActionRef'
|
||||
>,
|
||||
readonly transitions: ClusterPluginPackageSecretBindingTransitionExecutionPort,
|
||||
readonly secrets: PluginPackageSecretExistenceInspector,
|
||||
) {
|
||||
if (
|
||||
!plans ||
|
||||
typeof plans.findByActionRef !== 'function' ||
|
||||
!transitions ||
|
||||
typeof transitions.apply !== 'function' ||
|
||||
!secrets ||
|
||||
typeof secrets.assertExists !== 'function'
|
||||
) {
|
||||
throw new TypeError('Secret transition Approved Action authority is invalid');
|
||||
}
|
||||
}
|
||||
|
||||
async inspect(
|
||||
dispatch: ApprovedActionHandlerExecutionContext['dispatch'],
|
||||
): Promise<ApprovedActionHandlerInspection> {
|
||||
let plan;
|
||||
try {
|
||||
plan = await this.plans.findByActionRef(dispatch.action.actionRef);
|
||||
} catch {
|
||||
return Object.freeze({
|
||||
status: 'retry',
|
||||
resultCode: 'package_secret_transition_plan_unavailable',
|
||||
});
|
||||
}
|
||||
if (!plan) {
|
||||
return Object.freeze({
|
||||
status: 'blocked',
|
||||
resultCode: 'package_secret_transition_plan_missing',
|
||||
});
|
||||
}
|
||||
try {
|
||||
const normalized =
|
||||
normalizePluginPackageSecretBindingTransitionApprovalPlan(plan);
|
||||
if (
|
||||
JSON.stringify(dispatch.action) !==
|
||||
JSON.stringify(
|
||||
pluginPackageSecretBindingTransitionApprovedAction(normalized),
|
||||
) ||
|
||||
dispatch.projectId !== normalized.transitionPlan.nextTarget.projectId ||
|
||||
dispatch.requestedBy.type !== normalized.requestedBy.type ||
|
||||
dispatch.requestedBy.id !== normalized.requestedBy.id ||
|
||||
dispatch.createdAtMs > normalized.expiresAtMs
|
||||
) {
|
||||
throw new Error('dispatch does not match transition plan');
|
||||
}
|
||||
const secretRefs =
|
||||
normalized.transitionPlan.nextBindingPlan?.entries.flatMap((entry) =>
|
||||
entry.secretRef === null ? [] : [entry.secretRef],
|
||||
) ?? [];
|
||||
if (secretRefs.length > 0) await this.secrets.assertExists(secretRefs);
|
||||
return Object.freeze({
|
||||
status: 'ready',
|
||||
actionDigest: normalized.approvalPlanDigest,
|
||||
});
|
||||
} catch {
|
||||
return Object.freeze({
|
||||
status: 'blocked',
|
||||
resultCode: 'package_secret_transition_plan_rejected',
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
async execute(
|
||||
context: Readonly<ApprovedActionHandlerExecutionContext>,
|
||||
): Promise<Readonly<ApprovedActionHandlerResult>> {
|
||||
const startedAtMs = context.execution.startedAtMs;
|
||||
if (
|
||||
context.execution.status !== 'executing' ||
|
||||
startedAtMs === null ||
|
||||
context.execution.leaseOwner !== context.fence.owner ||
|
||||
context.execution.leaseToken !== context.fence.leaseToken ||
|
||||
context.execution.version !== context.fence.version
|
||||
) {
|
||||
return Object.freeze({
|
||||
outcome: 'failed',
|
||||
resultCode: 'package_secret_transition_execution_rejected',
|
||||
});
|
||||
}
|
||||
const plan = await this.plans.findByActionRef(
|
||||
context.dispatch.action.actionRef,
|
||||
);
|
||||
if (!plan) {
|
||||
return Object.freeze({
|
||||
outcome: 'failed',
|
||||
resultCode: 'package_secret_transition_plan_missing',
|
||||
});
|
||||
}
|
||||
const inspection = await this.inspect(context.dispatch);
|
||||
if (inspection.status !== 'ready' || startedAtMs > plan.expiresAtMs) {
|
||||
return Object.freeze({
|
||||
outcome: 'failed',
|
||||
resultCode: 'package_secret_transition_plan_rejected',
|
||||
});
|
||||
}
|
||||
try {
|
||||
const result = await this.transitions.apply({
|
||||
transitionPlan: plan.transitionPlan,
|
||||
evidenceDigest: plan.approvalPlanDigest,
|
||||
committedAtMs: startedAtMs,
|
||||
});
|
||||
return Object.freeze({
|
||||
outcome: 'succeeded',
|
||||
resultCode:
|
||||
result.status === 'created'
|
||||
? 'package_secret_transition_committed'
|
||||
: 'package_secret_transition_existing',
|
||||
resultDigest: result.receipt.receiptDigest,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof PluginPackageSecretBindingConflictError) {
|
||||
return Object.freeze({
|
||||
outcome: 'failed',
|
||||
resultCode: 'package_secret_transition_conflict',
|
||||
});
|
||||
}
|
||||
if (
|
||||
error instanceof
|
||||
InvalidPluginPackageSecretBindingTransitionApprovalPlanError
|
||||
) {
|
||||
return Object.freeze({
|
||||
outcome: 'failed',
|
||||
resultCode: 'package_secret_transition_plan_rejected',
|
||||
});
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
}
|
||||
+739
@@ -0,0 +1,739 @@
|
||||
import {
|
||||
PostgresApprovalRequestRepository,
|
||||
PostgresPluginPackageSecretBindingTransitionApprovalPlanRepository,
|
||||
PostgresProjectPolicyRepository,
|
||||
} from '@qinglong/cluster-postgres/package-manager';
|
||||
import type { PostgresPool } from '@qinglong/runtime-core';
|
||||
import {
|
||||
createApprovalRequest,
|
||||
normalizeApprovalRequestRecord,
|
||||
type ApprovalRequestRecord,
|
||||
type CreateApprovalRequestResult,
|
||||
type DecideApprovalRequestResult,
|
||||
} from '@qinglong/runtime-core/approved-action';
|
||||
import {
|
||||
PluginPackageManagementAuthorizationError,
|
||||
PluginPackageManagementConflictError,
|
||||
PluginPackageManagementQuotaExceededError,
|
||||
PluginPackageManagementRequestError,
|
||||
PluginPackageManagementUnavailableError,
|
||||
type PluginPackageManagementQuotaOperation,
|
||||
type PluginPackageManagementQuotaPort,
|
||||
} from '@qinglong/runtime-core/plugin-package-management';
|
||||
import { createPluginPackageResourceGenerationFromReferences } from '@qinglong/runtime-core/plugin-package-resource-generation';
|
||||
import {
|
||||
createPluginPackageSecretBindingTarget,
|
||||
type PluginPackageSecretBindingAssignment,
|
||||
} from '@qinglong/runtime-core/plugin-package-secret-binding';
|
||||
import { createPluginPackageSecretBindingTransitionPlan } from '@qinglong/runtime-core/plugin-package-secret-binding-transition-plan';
|
||||
import {
|
||||
MAX_PLUGIN_PACKAGE_SECRET_BINDING_TRANSITION_APPROVAL_PLAN_LIFETIME_MS,
|
||||
PluginPackageSecretBindingTransitionApprovalPlanConflictError,
|
||||
PluginPackageSecretBindingTransitionApprovalPlanUnavailableError,
|
||||
createPluginPackageSecretBindingTransitionApprovalPlan,
|
||||
normalizePluginPackageSecretBindingTransitionApprovalPlan,
|
||||
pluginPackageSecretBindingTransitionApprovedAction,
|
||||
type CreatePluginPackageSecretBindingTransitionApprovalPlanResult,
|
||||
type PluginPackageSecretBindingTransitionApprovalPlan,
|
||||
} from '@qinglong/runtime-core/plugin-package-secret-binding-transition-approval-plan';
|
||||
import { ProjectPolicyEngine } from '@qinglong/runtime-core/project-policy';
|
||||
import {
|
||||
normalizeSecurityPrincipal,
|
||||
type SecurityPolicyFence,
|
||||
type SecurityPrincipal,
|
||||
type SecuritySubject,
|
||||
} from '@qinglong/runtime-core/security';
|
||||
import type { SecurityAuditRecord } from '@qinglong/runtime-core/security-audit';
|
||||
|
||||
const DEFAULT_APPROVAL_LIFETIME_MS = 15 * 60 * 1000;
|
||||
const ACTION_REF_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,254}$/;
|
||||
const IDENTIFIER_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
|
||||
const PACKAGE_NAME_PATTERN = /^[a-z0-9](?:[a-z0-9-]{0,61}[a-z0-9])?$/;
|
||||
const REASON_PATTERN = /^[a-z][a-z0-9_]{0,63}$/;
|
||||
|
||||
export interface PlanClusterPluginPackageSecretBindingTransitionRequest {
|
||||
readonly actionRef: string;
|
||||
readonly projectId: string;
|
||||
readonly packageName: string;
|
||||
readonly assignments: readonly Readonly<PluginPackageSecretBindingAssignment>[];
|
||||
readonly principal: SecurityPrincipal;
|
||||
}
|
||||
|
||||
export interface ProposeClusterPluginPackageSecretBindingTransitionRequest {
|
||||
readonly actionRef: string;
|
||||
readonly approvalRequestId: string;
|
||||
readonly approvalAuditEventId: string;
|
||||
readonly principal: SecurityPrincipal;
|
||||
}
|
||||
|
||||
export interface DecideClusterPluginPackageSecretBindingTransitionRequest {
|
||||
readonly actionRef: string;
|
||||
readonly approvalRequestId: string;
|
||||
readonly expectedVersion: number;
|
||||
readonly decisionId: string;
|
||||
readonly auditEventId: string;
|
||||
readonly decision: 'approved' | 'rejected';
|
||||
readonly reasonCode: string;
|
||||
readonly principal: SecurityPrincipal;
|
||||
}
|
||||
|
||||
export interface InspectClusterPluginPackageSecretBindingTransitionRequest {
|
||||
readonly actionRef: string;
|
||||
readonly approvalRequestId: string;
|
||||
readonly inspectionId: string;
|
||||
readonly principal: SecurityPrincipal;
|
||||
}
|
||||
|
||||
export interface ClusterPluginPackageSecretBindingTransitionManagementService {
|
||||
plan(
|
||||
request: PlanClusterPluginPackageSecretBindingTransitionRequest,
|
||||
): Promise<
|
||||
Readonly<CreatePluginPackageSecretBindingTransitionApprovalPlanResult>
|
||||
>;
|
||||
propose(
|
||||
request: ProposeClusterPluginPackageSecretBindingTransitionRequest,
|
||||
): Promise<
|
||||
Readonly<{
|
||||
plan: Readonly<PluginPackageSecretBindingTransitionApprovalPlan>;
|
||||
approvalStatus: CreateApprovalRequestResult['status'];
|
||||
approvalRequest: Readonly<ApprovalRequestRecord>;
|
||||
}>
|
||||
>;
|
||||
decide(
|
||||
request: DecideClusterPluginPackageSecretBindingTransitionRequest,
|
||||
): Promise<Readonly<DecideApprovalRequestResult>>;
|
||||
inspectAuthorized(
|
||||
request: InspectClusterPluginPackageSecretBindingTransitionRequest,
|
||||
): Promise<
|
||||
Readonly<{
|
||||
plan: Readonly<PluginPackageSecretBindingTransitionApprovalPlan> | null;
|
||||
approvalRequest: Readonly<ApprovalRequestRecord> | null;
|
||||
stale: boolean;
|
||||
}>
|
||||
>;
|
||||
}
|
||||
|
||||
export interface ClusterPluginPackageSecretBindingTransitionManagementOptions {
|
||||
readonly pool: PostgresPool;
|
||||
readonly now?: () => number;
|
||||
readonly planLifetimeMs?: number;
|
||||
readonly approvalLifetimeMs?: number;
|
||||
readonly quota?: PluginPackageManagementQuotaPort;
|
||||
}
|
||||
|
||||
function exact(value: unknown, keys: readonly string[], label: string): void {
|
||||
if (!value || typeof value !== 'object' || Array.isArray(value)) {
|
||||
throw new PluginPackageManagementRequestError(`${label} is invalid`);
|
||||
}
|
||||
const actual = Object.keys(value).sort();
|
||||
const expected = [...keys].sort();
|
||||
if (
|
||||
actual.length !== expected.length ||
|
||||
actual.some((key, index) => key !== expected[index])
|
||||
) {
|
||||
throw new PluginPackageManagementRequestError(`${label} shape is invalid`);
|
||||
}
|
||||
}
|
||||
|
||||
function identifier(value: unknown, label: string): string {
|
||||
if (typeof value !== 'string' || !IDENTIFIER_PATTERN.test(value)) {
|
||||
throw new PluginPackageManagementRequestError(`${label} is invalid`);
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function actionRef(value: unknown): string {
|
||||
if (typeof value !== 'string' || !ACTION_REF_PATTERN.test(value)) {
|
||||
throw new PluginPackageManagementRequestError('actionRef is invalid');
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function currentTime(now: () => number): number {
|
||||
const value = now();
|
||||
if (!Number.isSafeInteger(value) || value < 0) {
|
||||
throw new PluginPackageManagementUnavailableError();
|
||||
}
|
||||
return value;
|
||||
}
|
||||
|
||||
function same(left: unknown, right: unknown): boolean {
|
||||
return JSON.stringify(left) === JSON.stringify(right);
|
||||
}
|
||||
|
||||
function sameSubject(
|
||||
left: Readonly<SecuritySubject>,
|
||||
right: Readonly<SecuritySubject>,
|
||||
): boolean {
|
||||
return left.type === right.type && left.id === right.id;
|
||||
}
|
||||
|
||||
function assignmentsMatch(
|
||||
assignments: readonly Readonly<PluginPackageSecretBindingAssignment>[],
|
||||
plan: Readonly<PluginPackageSecretBindingTransitionApprovalPlan>,
|
||||
): boolean {
|
||||
const expected = plan.transitionPlan.nextBindingPlan?.entries ?? [];
|
||||
if (!Array.isArray(assignments) || assignments.length !== expected.length) {
|
||||
return false;
|
||||
}
|
||||
const mapped = new Map<string, string | null>();
|
||||
for (const value of assignments) {
|
||||
if (
|
||||
!value ||
|
||||
typeof value !== 'object' ||
|
||||
Array.isArray(value) ||
|
||||
Object.keys(value).sort().join('\0') !== 'name\0secretRef' ||
|
||||
typeof value.name !== 'string' ||
|
||||
(value.secretRef !== null && typeof value.secretRef !== 'string') ||
|
||||
mapped.has(value.name)
|
||||
) {
|
||||
return false;
|
||||
}
|
||||
mapped.set(value.name, value.secretRef);
|
||||
}
|
||||
return expected.every(
|
||||
(entry) => mapped.get(entry.name) === entry.secretRef,
|
||||
);
|
||||
}
|
||||
|
||||
function audit(
|
||||
eventId: string,
|
||||
requestId: string,
|
||||
operationId: 'approval.request' | 'approval.decide',
|
||||
projectId: string,
|
||||
principal: Readonly<SecurityPrincipal>,
|
||||
outcome: 'allowed' | 'approval_required',
|
||||
fence: Readonly<SecurityPolicyFence>,
|
||||
occurredAtMs: number,
|
||||
): Readonly<SecurityAuditRecord> {
|
||||
return Object.freeze({
|
||||
eventId,
|
||||
requestId,
|
||||
operationId,
|
||||
projectId,
|
||||
subject: principal.subject,
|
||||
authenticationId: principal.authenticationId,
|
||||
outcome,
|
||||
reasons: Object.freeze(['package_secret_binding_transition_review']),
|
||||
fence,
|
||||
occurredAtMs,
|
||||
});
|
||||
}
|
||||
|
||||
export function createClusterPluginPackageSecretBindingTransitionManagementService(
|
||||
options: ClusterPluginPackageSecretBindingTransitionManagementOptions,
|
||||
): Readonly<ClusterPluginPackageSecretBindingTransitionManagementService> {
|
||||
if (
|
||||
!options ||
|
||||
typeof options !== 'object' ||
|
||||
Array.isArray(options) ||
|
||||
Object.keys(options).some(
|
||||
(key) =>
|
||||
!['pool', 'now', 'planLifetimeMs', 'approvalLifetimeMs', 'quota'].includes(
|
||||
key,
|
||||
),
|
||||
) ||
|
||||
!options.pool ||
|
||||
typeof options.pool.query !== 'function' ||
|
||||
typeof options.pool.connect !== 'function'
|
||||
) {
|
||||
throw new TypeError('Secret binding transition management options are invalid');
|
||||
}
|
||||
const planLifetimeMs =
|
||||
options.planLifetimeMs ??
|
||||
MAX_PLUGIN_PACKAGE_SECRET_BINDING_TRANSITION_APPROVAL_PLAN_LIFETIME_MS;
|
||||
const approvalLifetimeMs =
|
||||
options.approvalLifetimeMs ?? DEFAULT_APPROVAL_LIFETIME_MS;
|
||||
for (const value of [planLifetimeMs, approvalLifetimeMs]) {
|
||||
if (
|
||||
!Number.isSafeInteger(value) ||
|
||||
value < 1_000 ||
|
||||
value >
|
||||
MAX_PLUGIN_PACKAGE_SECRET_BINDING_TRANSITION_APPROVAL_PLAN_LIFETIME_MS
|
||||
) {
|
||||
throw new TypeError('Secret binding transition lifetime is invalid');
|
||||
}
|
||||
}
|
||||
const now = options.now ?? Date.now;
|
||||
const plans =
|
||||
new PostgresPluginPackageSecretBindingTransitionApprovalPlanRepository(
|
||||
options.pool,
|
||||
);
|
||||
const approvals = new PostgresApprovalRequestRepository(options.pool);
|
||||
const policy = new ProjectPolicyEngine(
|
||||
new PostgresProjectPolicyRepository(options.pool),
|
||||
);
|
||||
|
||||
const consumeQuota = async (
|
||||
projectId: string,
|
||||
principal: Readonly<SecurityPrincipal>,
|
||||
operation: PluginPackageManagementQuotaOperation,
|
||||
idempotencyKey: string,
|
||||
): Promise<void> => {
|
||||
if (!options.quota) return;
|
||||
try {
|
||||
await options.quota.consume({
|
||||
projectId,
|
||||
subject: principal.subject,
|
||||
operation,
|
||||
idempotencyKey,
|
||||
});
|
||||
} catch (error) {
|
||||
if (error instanceof PluginPackageManagementQuotaExceededError) throw error;
|
||||
throw new PluginPackageManagementUnavailableError({
|
||||
cause: error instanceof Error ? error : undefined,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
const authorize = async (
|
||||
principalValue: SecurityPrincipal,
|
||||
projectId: string,
|
||||
permission: 'secret.manage' | 'approval.decide',
|
||||
observedAtMs: number,
|
||||
): Promise<
|
||||
Readonly<{
|
||||
principal: Readonly<SecurityPrincipal>;
|
||||
fence: Readonly<SecurityPolicyFence>;
|
||||
}>
|
||||
> => {
|
||||
let principal;
|
||||
try {
|
||||
principal = normalizeSecurityPrincipal(principalValue, observedAtMs);
|
||||
} catch {
|
||||
throw new PluginPackageManagementAuthorizationError();
|
||||
}
|
||||
if (
|
||||
principal.subject.type !== 'user' ||
|
||||
(principal.assurance !== 'multi_factor' &&
|
||||
principal.assurance !== 'hardware')
|
||||
) {
|
||||
throw new PluginPackageManagementAuthorizationError();
|
||||
}
|
||||
let decision;
|
||||
try {
|
||||
decision = await policy.authorize(principal, projectId, permission);
|
||||
} catch (error) {
|
||||
throw new PluginPackageManagementUnavailableError({
|
||||
cause: error instanceof Error ? error : undefined,
|
||||
});
|
||||
}
|
||||
if (decision.effect !== 'allow' || decision.fence === null) {
|
||||
throw new PluginPackageManagementAuthorizationError();
|
||||
}
|
||||
return Object.freeze({ principal, fence: decision.fence });
|
||||
};
|
||||
|
||||
const loadPlan = async (requestedActionRef: string) => {
|
||||
try {
|
||||
const value = await plans.findByActionRef(actionRef(requestedActionRef));
|
||||
if (!value) {
|
||||
throw new PluginPackageManagementConflictError(
|
||||
'Secret binding transition plan does not exist',
|
||||
);
|
||||
}
|
||||
return normalizePluginPackageSecretBindingTransitionApprovalPlan(value);
|
||||
} catch (error) {
|
||||
if (error instanceof PluginPackageManagementConflictError) throw error;
|
||||
throw new PluginPackageManagementUnavailableError({
|
||||
cause: error instanceof Error ? error : undefined,
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
return Object.freeze({
|
||||
async plan(
|
||||
request: PlanClusterPluginPackageSecretBindingTransitionRequest,
|
||||
) {
|
||||
exact(
|
||||
request,
|
||||
['actionRef', 'assignments', 'packageName', 'principal', 'projectId'],
|
||||
'Secret transition plan request',
|
||||
);
|
||||
const projectId = identifier(request.projectId, 'projectId');
|
||||
if (
|
||||
typeof request.packageName !== 'string' ||
|
||||
!PACKAGE_NAME_PATTERN.test(request.packageName) ||
|
||||
!Array.isArray(request.assignments)
|
||||
) {
|
||||
throw new PluginPackageManagementRequestError(
|
||||
'Secret transition target is invalid',
|
||||
);
|
||||
}
|
||||
const authorization = await authorize(
|
||||
request.principal,
|
||||
projectId,
|
||||
'secret.manage',
|
||||
currentTime(now),
|
||||
);
|
||||
const requestedActionRef = actionRef(request.actionRef);
|
||||
await consumeQuota(
|
||||
projectId,
|
||||
authorization.principal,
|
||||
'plugin-package.propose',
|
||||
requestedActionRef,
|
||||
);
|
||||
let existing;
|
||||
try {
|
||||
existing = await plans.findByActionRef(requestedActionRef);
|
||||
} catch (error) {
|
||||
throw new PluginPackageManagementUnavailableError({
|
||||
cause: error instanceof Error ? error : undefined,
|
||||
});
|
||||
}
|
||||
if (existing) {
|
||||
const normalized =
|
||||
normalizePluginPackageSecretBindingTransitionApprovalPlan(existing);
|
||||
if (
|
||||
normalized.transitionPlan.nextTarget.projectId !== projectId ||
|
||||
normalized.transitionPlan.nextTarget.packageName !==
|
||||
request.packageName ||
|
||||
!sameSubject(normalized.requestedBy, authorization.principal.subject) ||
|
||||
normalized.expiresAtMs - normalized.plannedAtMs !== planLifetimeMs ||
|
||||
!assignmentsMatch(request.assignments, normalized)
|
||||
) {
|
||||
throw new PluginPackageManagementConflictError(
|
||||
'Secret transition actionRef is bound to another request',
|
||||
);
|
||||
}
|
||||
return Object.freeze({ status: 'existing' as const, plan: normalized });
|
||||
}
|
||||
let snapshot;
|
||||
try {
|
||||
snapshot = await plans.loadPlanningSnapshot(
|
||||
projectId,
|
||||
request.packageName,
|
||||
);
|
||||
} catch (error) {
|
||||
throw new PluginPackageManagementUnavailableError({
|
||||
cause: error instanceof Error ? error : undefined,
|
||||
});
|
||||
}
|
||||
if (!snapshot) {
|
||||
throw new PluginPackageManagementConflictError(
|
||||
'reviewed staged Package transition does not exist',
|
||||
);
|
||||
}
|
||||
const generation = (value: typeof snapshot.next) =>
|
||||
createPluginPackageResourceGenerationFromReferences({
|
||||
installationId: value.record.installationId,
|
||||
projectId: value.record.projectId,
|
||||
packageName: value.record.packageName,
|
||||
lockDigest: value.record.lockDigest,
|
||||
generation: value.record.targetGeneration,
|
||||
previousActiveLockDigest: value.record.previousActiveLockDigest,
|
||||
contentDigest: value.lock.source.contentDigest,
|
||||
resources: value.lock.resources,
|
||||
});
|
||||
try {
|
||||
const previousTarget = createPluginPackageSecretBindingTarget(
|
||||
generation(snapshot.previous),
|
||||
snapshot.previous.proposal.actionInput.manifest,
|
||||
);
|
||||
const transitionPlan = createPluginPackageSecretBindingTransitionPlan({
|
||||
previousTarget,
|
||||
previousBinding: snapshot.previous.binding,
|
||||
previousAttemptGeneration: snapshot.previousAttemptGeneration,
|
||||
nextGeneration: generation(snapshot.next),
|
||||
nextManifest: snapshot.next.proposal.actionInput.manifest,
|
||||
assignments: request.assignments,
|
||||
plannedAtMs: snapshot.observedAtMs,
|
||||
});
|
||||
return await plans.create(
|
||||
createPluginPackageSecretBindingTransitionApprovalPlan({
|
||||
actionRef: requestedActionRef,
|
||||
transitionPlan,
|
||||
requestedBy: authorization.principal.subject,
|
||||
plannedAtMs: snapshot.observedAtMs,
|
||||
expiresAtMs: snapshot.observedAtMs + planLifetimeMs,
|
||||
}),
|
||||
);
|
||||
} catch (error) {
|
||||
if (
|
||||
error instanceof
|
||||
PluginPackageSecretBindingTransitionApprovalPlanConflictError
|
||||
) {
|
||||
throw new PluginPackageManagementConflictError(
|
||||
'Secret transition actionRef or generation is already bound',
|
||||
);
|
||||
}
|
||||
if (
|
||||
error instanceof
|
||||
PluginPackageSecretBindingTransitionApprovalPlanUnavailableError
|
||||
) {
|
||||
throw new PluginPackageManagementUnavailableError({ cause: error });
|
||||
}
|
||||
if (error instanceof TypeError) {
|
||||
throw new PluginPackageManagementRequestError(
|
||||
'Secret transition assignments are invalid',
|
||||
);
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
},
|
||||
|
||||
async propose(
|
||||
request: ProposeClusterPluginPackageSecretBindingTransitionRequest,
|
||||
) {
|
||||
exact(
|
||||
request,
|
||||
['actionRef', 'approvalAuditEventId', 'approvalRequestId', 'principal'],
|
||||
'Secret transition proposal request',
|
||||
);
|
||||
const approvalRequestId = identifier(
|
||||
request.approvalRequestId,
|
||||
'approvalRequestId',
|
||||
);
|
||||
const approvalAuditEventId = identifier(
|
||||
request.approvalAuditEventId,
|
||||
'approvalAuditEventId',
|
||||
);
|
||||
const plan = await loadPlan(request.actionRef);
|
||||
const observedAtMs = currentTime(now);
|
||||
if (observedAtMs > plan.expiresAtMs) {
|
||||
throw new PluginPackageManagementConflictError(
|
||||
'Secret transition plan expired',
|
||||
);
|
||||
}
|
||||
const authorization = await authorize(
|
||||
request.principal,
|
||||
plan.transitionPlan.nextTarget.projectId,
|
||||
'secret.manage',
|
||||
observedAtMs,
|
||||
);
|
||||
await consumeQuota(
|
||||
plan.transitionPlan.nextTarget.projectId,
|
||||
authorization.principal,
|
||||
'plugin-package.propose',
|
||||
approvalRequestId,
|
||||
);
|
||||
if (!sameSubject(plan.requestedBy, authorization.principal.subject)) {
|
||||
throw new PluginPackageManagementAuthorizationError();
|
||||
}
|
||||
const binding = pluginPackageSecretBindingTransitionApprovedAction(plan);
|
||||
const existing = await approvals.findById(approvalRequestId);
|
||||
if (existing) {
|
||||
const normalized = normalizeApprovalRequestRecord(existing);
|
||||
if (
|
||||
normalized.projectId !== plan.transitionPlan.nextTarget.projectId ||
|
||||
normalized.decisionMode !== 'separation_of_duty' ||
|
||||
!sameSubject(normalized.requestedBy, plan.requestedBy) ||
|
||||
!same(normalized.action, binding)
|
||||
) {
|
||||
throw new PluginPackageManagementConflictError(
|
||||
'Approval request is bound to another Secret transition',
|
||||
);
|
||||
}
|
||||
return Object.freeze({
|
||||
plan,
|
||||
approvalStatus: 'existing' as const,
|
||||
approvalRequest: normalized,
|
||||
});
|
||||
}
|
||||
const expiresAtMs = Math.min(
|
||||
observedAtMs + approvalLifetimeMs,
|
||||
plan.expiresAtMs,
|
||||
);
|
||||
if (expiresAtMs <= observedAtMs) {
|
||||
throw new PluginPackageManagementConflictError(
|
||||
'Secret transition plan has no approval lifetime',
|
||||
);
|
||||
}
|
||||
const result = await approvals.create({
|
||||
request: createApprovalRequest({
|
||||
id: approvalRequestId,
|
||||
projectId: plan.transitionPlan.nextTarget.projectId,
|
||||
action: binding,
|
||||
risk: 'high',
|
||||
decisionMode: 'separation_of_duty',
|
||||
requestedBy: authorization.principal.subject,
|
||||
requestedAtMs: observedAtMs,
|
||||
expiresAtMs,
|
||||
requestFence: authorization.fence,
|
||||
}),
|
||||
audit: audit(
|
||||
approvalAuditEventId,
|
||||
approvalRequestId,
|
||||
'approval.request',
|
||||
plan.transitionPlan.nextTarget.projectId,
|
||||
authorization.principal,
|
||||
'approval_required',
|
||||
authorization.fence,
|
||||
observedAtMs,
|
||||
),
|
||||
});
|
||||
return Object.freeze({
|
||||
plan,
|
||||
approvalStatus: result.status,
|
||||
approvalRequest: result.request,
|
||||
});
|
||||
},
|
||||
|
||||
async decide(
|
||||
request: DecideClusterPluginPackageSecretBindingTransitionRequest,
|
||||
) {
|
||||
exact(
|
||||
request,
|
||||
[
|
||||
'actionRef',
|
||||
'approvalRequestId',
|
||||
'auditEventId',
|
||||
'decision',
|
||||
'decisionId',
|
||||
'expectedVersion',
|
||||
'principal',
|
||||
'reasonCode',
|
||||
],
|
||||
'Secret transition decision request',
|
||||
);
|
||||
if (
|
||||
(request.decision !== 'approved' && request.decision !== 'rejected') ||
|
||||
typeof request.reasonCode !== 'string' ||
|
||||
!REASON_PATTERN.test(request.reasonCode) ||
|
||||
!Number.isSafeInteger(request.expectedVersion) ||
|
||||
request.expectedVersion < 1
|
||||
) {
|
||||
throw new PluginPackageManagementRequestError(
|
||||
'Secret transition decision tuple is invalid',
|
||||
);
|
||||
}
|
||||
const plan = await loadPlan(request.actionRef);
|
||||
const approvalRequestId = identifier(
|
||||
request.approvalRequestId,
|
||||
'approvalRequestId',
|
||||
);
|
||||
const decisionId = identifier(request.decisionId, 'decisionId');
|
||||
const auditEventId = identifier(request.auditEventId, 'auditEventId');
|
||||
const current = await approvals.findById(approvalRequestId);
|
||||
if (!current) {
|
||||
throw new PluginPackageManagementConflictError(
|
||||
'Approval request does not exist',
|
||||
);
|
||||
}
|
||||
const approval = normalizeApprovalRequestRecord(current);
|
||||
if (
|
||||
!same(
|
||||
approval.action,
|
||||
pluginPackageSecretBindingTransitionApprovedAction(plan),
|
||||
)
|
||||
) {
|
||||
throw new PluginPackageManagementConflictError(
|
||||
'Approval request does not match Secret transition plan',
|
||||
);
|
||||
}
|
||||
const observedAtMs = currentTime(now);
|
||||
const authorization = await authorize(
|
||||
request.principal,
|
||||
approval.projectId,
|
||||
'approval.decide',
|
||||
observedAtMs,
|
||||
);
|
||||
await consumeQuota(
|
||||
approval.projectId,
|
||||
authorization.principal,
|
||||
'plugin-package.decide',
|
||||
decisionId,
|
||||
);
|
||||
if (
|
||||
approval.decisionId === decisionId &&
|
||||
approval.decision === request.decision &&
|
||||
approval.decisionReasonCode === request.reasonCode &&
|
||||
approval.decidedBy &&
|
||||
sameSubject(approval.decidedBy, authorization.principal.subject)
|
||||
) {
|
||||
return Object.freeze({ status: 'existing' as const, request: approval });
|
||||
}
|
||||
return approvals.decide({
|
||||
requestId: approvalRequestId,
|
||||
expectedVersion: request.expectedVersion,
|
||||
decisionId,
|
||||
decision: request.decision,
|
||||
reasonCode: request.reasonCode,
|
||||
principal: authorization.principal,
|
||||
decidedAtMs: observedAtMs,
|
||||
authorizationFence: authorization.fence,
|
||||
audit: audit(
|
||||
auditEventId,
|
||||
approvalRequestId,
|
||||
'approval.decide',
|
||||
approval.projectId,
|
||||
authorization.principal,
|
||||
'allowed',
|
||||
authorization.fence,
|
||||
observedAtMs,
|
||||
),
|
||||
});
|
||||
},
|
||||
|
||||
async inspectAuthorized(
|
||||
request: InspectClusterPluginPackageSecretBindingTransitionRequest,
|
||||
) {
|
||||
exact(
|
||||
request,
|
||||
['actionRef', 'approvalRequestId', 'inspectionId', 'principal'],
|
||||
'Secret transition inspection request',
|
||||
);
|
||||
const requestedActionRef = actionRef(request.actionRef);
|
||||
const approvalRequestId = identifier(
|
||||
request.approvalRequestId,
|
||||
'approvalRequestId',
|
||||
);
|
||||
const [planValue, approvalValue] = await Promise.all([
|
||||
plans.findByActionRef(requestedActionRef),
|
||||
approvals.findById(approvalRequestId),
|
||||
]);
|
||||
if (!planValue && !approvalValue) {
|
||||
throw new PluginPackageManagementConflictError(
|
||||
'Secret transition review state does not exist',
|
||||
);
|
||||
}
|
||||
const plan = planValue
|
||||
? normalizePluginPackageSecretBindingTransitionApprovalPlan(planValue)
|
||||
: null;
|
||||
const approval = approvalValue
|
||||
? normalizeApprovalRequestRecord(approvalValue)
|
||||
: null;
|
||||
const projectId =
|
||||
plan?.transitionPlan.nextTarget.projectId ?? approval?.projectId;
|
||||
if (!projectId) throw new PluginPackageManagementUnavailableError();
|
||||
const observedAtMs = currentTime(now);
|
||||
let authorization;
|
||||
try {
|
||||
authorization = await authorize(
|
||||
request.principal,
|
||||
projectId,
|
||||
'secret.manage',
|
||||
observedAtMs,
|
||||
);
|
||||
} catch (error) {
|
||||
if (!(error instanceof PluginPackageManagementAuthorizationError)) {
|
||||
throw error;
|
||||
}
|
||||
authorization = await authorize(
|
||||
request.principal,
|
||||
projectId,
|
||||
'approval.decide',
|
||||
observedAtMs,
|
||||
);
|
||||
}
|
||||
await consumeQuota(
|
||||
projectId,
|
||||
authorization.principal,
|
||||
'plugin-package.inspect',
|
||||
identifier(request.inspectionId, 'inspectionId'),
|
||||
);
|
||||
return Object.freeze({
|
||||
plan,
|
||||
approvalRequest: approval,
|
||||
stale:
|
||||
plan === null ||
|
||||
approval === null ||
|
||||
!same(
|
||||
approval.action,
|
||||
pluginPackageSecretBindingTransitionApprovedAction(plan),
|
||||
) ||
|
||||
observedAtMs > plan.expiresAtMs,
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
@@ -186,6 +186,8 @@ function database(serverVersionNum = '160014') {
|
||||
'plugin_package_workflow_task_attempt_snapshot',
|
||||
'register_plugin_package_automation_disposition_event',
|
||||
'create_plugin_package_secret_binding_approval_plan',
|
||||
'create_plugin_package_secret_transition_plan',
|
||||
'plugin_package_secret_binding_transition_snapshot',
|
||||
].includes(functionName),
|
||||
isOwner: false,
|
||||
})),
|
||||
|
||||
@@ -240,6 +240,47 @@ function commands() {
|
||||
inspectionId: 'inspection-secret-binding-1',
|
||||
},
|
||||
},
|
||||
{
|
||||
schemaVersion: 1,
|
||||
operation: 'plugin-package.secret-binding.transition.plan',
|
||||
request: {
|
||||
actionRef: 'secret-transition:cluster-monitor:2',
|
||||
projectId: 'project-1',
|
||||
packageName: 'cluster-monitor',
|
||||
assignments: [{
|
||||
name: 'TOKEN',
|
||||
secretRef:
|
||||
'qlsecret:v1:eyJwcm9qZWN0SWQiOiJwcm9qZWN0LTEiLCJuYW1lIjoicnVudGltZS10b2tlbiIsInZlcnNpb24iOjJ9',
|
||||
}],
|
||||
},
|
||||
},
|
||||
{
|
||||
schemaVersion: 1,
|
||||
operation: 'plugin-package.secret-binding.transition.propose',
|
||||
request: {
|
||||
actionRef: 'secret-transition:cluster-monitor:2',
|
||||
approvalRequestId: 'approval-secret-transition-1',
|
||||
approvalAuditEventId: 'audit-secret-transition-approval-1',
|
||||
},
|
||||
},
|
||||
{
|
||||
schemaVersion: 1,
|
||||
operation: 'plugin-package.secret-binding.transition.decide',
|
||||
request: {
|
||||
...decision,
|
||||
actionRef: 'secret-transition:cluster-monitor:2',
|
||||
approvalRequestId: 'approval-secret-transition-1',
|
||||
},
|
||||
},
|
||||
{
|
||||
schemaVersion: 1,
|
||||
operation: 'plugin-package.secret-binding.transition.inspect',
|
||||
request: {
|
||||
actionRef: 'secret-transition:cluster-monitor:2',
|
||||
approvalRequestId: 'approval-secret-transition-1',
|
||||
inspectionId: 'inspection-secret-transition-1',
|
||||
},
|
||||
},
|
||||
];
|
||||
}
|
||||
|
||||
@@ -391,6 +432,42 @@ function secretBindingPlanSummary() {
|
||||
};
|
||||
}
|
||||
|
||||
function secretBindingTransitionPlanSummary() {
|
||||
const secretRef =
|
||||
'qlsecret:v1:eyJwcm9qZWN0SWQiOiJwcm9qZWN0LTEiLCJuYW1lIjoicnVudGltZS10b2tlbiIsInZlcnNpb24iOjJ9';
|
||||
return {
|
||||
actionRef: 'secret-transition:cluster-monitor:2',
|
||||
approvalPlanDigest: '1'.repeat(64),
|
||||
plannedAtMs: 1_000,
|
||||
expiresAtMs: 10_000,
|
||||
kind: 'rotate',
|
||||
transitionDigest: '2'.repeat(64),
|
||||
projectId: 'project-1',
|
||||
packageName: 'cluster-monitor',
|
||||
previousInstallationId: 'install-cluster-monitor-1',
|
||||
previousGeneration: 1,
|
||||
previousGenerationDigest: '3'.repeat(64),
|
||||
previousActiveLockDigest: '4'.repeat(64),
|
||||
previousAttemptGeneration: 1,
|
||||
nextInstallationId: 'install-cluster-monitor-2',
|
||||
nextGeneration: 2,
|
||||
nextGenerationDigest: '5'.repeat(64),
|
||||
nextLockDigest: '6'.repeat(64),
|
||||
nextManifestDigest: '7'.repeat(64),
|
||||
changes: [{
|
||||
name: 'TOKEN',
|
||||
requirement: 'unchanged',
|
||||
reference: 'rotated',
|
||||
previous: {
|
||||
required: true,
|
||||
secretRef:
|
||||
'qlsecret:v1:eyJwcm9qZWN0SWQiOiJwcm9qZWN0LTEiLCJuYW1lIjoicnVudGltZS10b2tlbiIsInZlcnNpb24iOjF9',
|
||||
},
|
||||
next: { required: true, secretRef },
|
||||
}],
|
||||
};
|
||||
}
|
||||
|
||||
function successfulResult(operation) {
|
||||
const secretApproval = {
|
||||
...approvalSummary(),
|
||||
@@ -398,6 +475,47 @@ function successfulResult(operation) {
|
||||
actionDigest: 'd'.repeat(64),
|
||||
previewDigest: 'c'.repeat(64),
|
||||
};
|
||||
const transitionApproval = {
|
||||
...approvalSummary(),
|
||||
id: 'approval-secret-transition-1',
|
||||
projectId: 'project-1',
|
||||
actionDigest: '1'.repeat(64),
|
||||
previewDigest: '2'.repeat(64),
|
||||
};
|
||||
if (operation === 'plugin-package.secret-binding.transition.plan') {
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
operation,
|
||||
status: 'created',
|
||||
plan: secretBindingTransitionPlanSummary(),
|
||||
};
|
||||
}
|
||||
if (operation === 'plugin-package.secret-binding.transition.propose') {
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
operation,
|
||||
approvalStatus: 'created',
|
||||
plan: secretBindingTransitionPlanSummary(),
|
||||
approval: transitionApproval,
|
||||
};
|
||||
}
|
||||
if (operation === 'plugin-package.secret-binding.transition.inspect') {
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
operation,
|
||||
plan: secretBindingTransitionPlanSummary(),
|
||||
approval: transitionApproval,
|
||||
stale: false,
|
||||
};
|
||||
}
|
||||
if (operation === 'plugin-package.secret-binding.transition.decide') {
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
operation,
|
||||
status: 'decided',
|
||||
approval: transitionApproval,
|
||||
};
|
||||
}
|
||||
if (operation === 'plugin-package.secret-binding.plan') {
|
||||
return {
|
||||
schemaVersion: 1,
|
||||
@@ -743,7 +861,7 @@ test('readiness probe rejects unreviewed status and bounded response drift', asy
|
||||
}
|
||||
});
|
||||
|
||||
test('permits and validates exactly the eighteen public management operations', async () => {
|
||||
test('permits and validates exactly the twenty-two public management operations', async () => {
|
||||
const received = [];
|
||||
const fixture = await startServer((request, response) => {
|
||||
const chunks = [];
|
||||
@@ -788,7 +906,7 @@ test('permits and validates exactly the eighteen public management operations',
|
||||
return true;
|
||||
},
|
||||
);
|
||||
assert.equal(received.length, 18);
|
||||
assert.equal(received.length, 22);
|
||||
} finally {
|
||||
await fixture.close();
|
||||
rmSync(files.directory, { recursive: true, force: true });
|
||||
|
||||
@@ -410,6 +410,116 @@ function fakeSecretBinding() {
|
||||
};
|
||||
}
|
||||
|
||||
function secretBindingTransitionPlan() {
|
||||
const previousSecretRef =
|
||||
'qlsecret:v1:eyJwcm9qZWN0SWQiOiJkZWZhdWx0IiwibmFtZSI6InJ1bnRpbWUtdG9rZW4iLCJ2ZXJzaW9uIjoxfQ';
|
||||
const nextSecretRef =
|
||||
'qlsecret:v1:eyJwcm9qZWN0SWQiOiJkZWZhdWx0IiwibmFtZSI6InJ1bnRpbWUtdG9rZW4iLCJ2ZXJzaW9uIjoyfQ';
|
||||
return {
|
||||
schema:
|
||||
'qinglong/plugin-package-secret-binding-transition-approval-plan@v1',
|
||||
actionRef: 'secret-transition:cluster-monitor:2',
|
||||
approvalPlanDigest: 'a'.repeat(64),
|
||||
requestedBy: { type: 'user', id: 'cluster-reviewer' },
|
||||
plannedAtMs: NOW - 10,
|
||||
expiresAtMs: NOW + 10_000,
|
||||
transitionPlan: {
|
||||
schema: 'qinglong/plugin-package-secret-binding-transition-plan@v1',
|
||||
kind: 'rotate',
|
||||
previousTarget: {
|
||||
installationId: 'cluster-monitor-installation-v1',
|
||||
projectId: 'default',
|
||||
packageName: 'cluster-monitor',
|
||||
lockDigest: '1'.repeat(64),
|
||||
generation: 1,
|
||||
generationDigest: '2'.repeat(64),
|
||||
manifestDigest: '3'.repeat(64),
|
||||
},
|
||||
previousBinding: null,
|
||||
previousActiveLockDigest: '1'.repeat(64),
|
||||
previousAttemptGeneration: 1,
|
||||
nextTarget: {
|
||||
installationId: 'cluster-monitor-installation-v2',
|
||||
projectId: 'default',
|
||||
packageName: 'cluster-monitor',
|
||||
lockDigest: '4'.repeat(64),
|
||||
generation: 2,
|
||||
generationDigest: '5'.repeat(64),
|
||||
manifestDigest: '6'.repeat(64),
|
||||
},
|
||||
nextBindingPlan: null,
|
||||
changes: [{
|
||||
name: 'TOKEN',
|
||||
requirement: 'unchanged',
|
||||
reference: 'rotated',
|
||||
previous: { required: true, secretRef: previousSecretRef },
|
||||
next: { required: true, secretRef: nextSecretRef },
|
||||
}],
|
||||
transitionDigest: 'b'.repeat(64),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function fakeSecretBindingTransition() {
|
||||
const calls = { plan: [], propose: [], decide: [], inspectAuthorized: [] };
|
||||
return {
|
||||
calls,
|
||||
service: {
|
||||
async plan(request) {
|
||||
calls.plan.push(request);
|
||||
return { status: 'created', plan: secretBindingTransitionPlan() };
|
||||
},
|
||||
async propose(request) {
|
||||
calls.propose.push(request);
|
||||
return {
|
||||
plan: secretBindingTransitionPlan(),
|
||||
approvalStatus: 'created',
|
||||
approvalRequest: approval({
|
||||
id: request.approvalRequestId,
|
||||
projectId: 'default',
|
||||
action: {
|
||||
permission: 'secret.manage',
|
||||
actionType: 'plugin_package.secret_binding.transition',
|
||||
actionRef: request.actionRef,
|
||||
actionDigest: 'a'.repeat(64),
|
||||
previewDigest: 'b'.repeat(64),
|
||||
},
|
||||
requestedBy: request.principal.subject,
|
||||
}),
|
||||
};
|
||||
},
|
||||
async decide(request) {
|
||||
calls.decide.push(request);
|
||||
return {
|
||||
status: 'decided',
|
||||
request: approval({
|
||||
id: request.approvalRequestId,
|
||||
projectId: 'default',
|
||||
version: 2,
|
||||
state: request.decision,
|
||||
decisionId: request.decisionId,
|
||||
decision: request.decision,
|
||||
decisionReasonCode: request.reasonCode,
|
||||
decidedBy: request.principal.subject,
|
||||
decisionAuthenticationId: request.principal.authenticationId,
|
||||
decisionAssurance: request.principal.assurance,
|
||||
decidedAtMs: NOW,
|
||||
decisionFence: { projectVersion: 1, bindingVersion: 1 },
|
||||
}),
|
||||
};
|
||||
},
|
||||
async inspectAuthorized(request) {
|
||||
calls.inspectAuthorized.push(request);
|
||||
return {
|
||||
plan: secretBindingTransitionPlan(),
|
||||
approvalRequest: null,
|
||||
stale: false,
|
||||
};
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function lifecyclePlan() {
|
||||
return {
|
||||
schema: 'qinglong/plugin-package-lifecycle-plan@v1',
|
||||
@@ -982,6 +1092,78 @@ test('routes content-free Secret binding review without executor authority', asy
|
||||
assert.deepEqual(management.calls.dispatch, []);
|
||||
});
|
||||
|
||||
test('routes content-free Secret transition review without executor authority', async () => {
|
||||
const management = fakeService();
|
||||
const transition = fakeSecretBindingTransition();
|
||||
const transport = createClusterPluginPackageManagementTransport({
|
||||
service: management.service,
|
||||
secretBindingTransition: transition.service,
|
||||
now: () => NOW,
|
||||
});
|
||||
const plan = secretBindingTransitionPlan();
|
||||
const assignments = plan.transitionPlan.changes
|
||||
.filter(({ next }) => next !== null)
|
||||
.map(({ name, next }) => ({ name, secretRef: next.secretRef }));
|
||||
const planned = await transport.execute({
|
||||
schemaVersion: 1,
|
||||
operation: 'plugin-package.secret-binding.transition.plan',
|
||||
request: {
|
||||
actionRef: plan.actionRef,
|
||||
projectId: 'default',
|
||||
packageName: 'cluster-monitor',
|
||||
assignments,
|
||||
},
|
||||
}, authentication().authority);
|
||||
assert.equal(planned.status, 'created');
|
||||
assert.equal(planned.plan.kind, 'rotate');
|
||||
assert.equal(planned.plan.previousGeneration, 1);
|
||||
assert.equal(planned.plan.nextGeneration, 2);
|
||||
assert.equal(Object.hasOwn(planned.plan, 'previousBinding'), false);
|
||||
|
||||
const proposed = await transport.execute({
|
||||
schemaVersion: 1,
|
||||
operation: 'plugin-package.secret-binding.transition.propose',
|
||||
request: {
|
||||
actionRef: plan.actionRef,
|
||||
approvalRequestId: 'approval-secret-transition-1',
|
||||
approvalAuditEventId: 'audit-secret-transition-approval-1',
|
||||
},
|
||||
}, authentication().authority);
|
||||
assert.equal(proposed.approvalStatus, 'created');
|
||||
|
||||
const decided = await transport.execute({
|
||||
schemaVersion: 1,
|
||||
operation: 'plugin-package.secret-binding.transition.decide',
|
||||
request: {
|
||||
actionRef: plan.actionRef,
|
||||
approvalRequestId: 'approval-secret-transition-1',
|
||||
expectedVersion: 1,
|
||||
decisionId: 'decision-secret-transition-1',
|
||||
auditEventId: 'audit-secret-transition-decision-1',
|
||||
decision: 'approved',
|
||||
reasonCode: 'reviewed',
|
||||
},
|
||||
}, authentication().authority);
|
||||
assert.equal(decided.status, 'decided');
|
||||
|
||||
const inspected = await transport.execute({
|
||||
schemaVersion: 1,
|
||||
operation: 'plugin-package.secret-binding.transition.inspect',
|
||||
request: {
|
||||
actionRef: plan.actionRef,
|
||||
approvalRequestId: 'approval-secret-transition-1',
|
||||
inspectionId: 'inspection-secret-transition-1',
|
||||
},
|
||||
}, authentication().authority);
|
||||
assert.equal(inspected.stale, false);
|
||||
assert.equal(transition.calls.plan.length, 1);
|
||||
assert.equal(transition.calls.propose.length, 1);
|
||||
assert.equal(transition.calls.decide.length, 1);
|
||||
assert.equal(transition.calls.inspectAuthorized.length, 1);
|
||||
assert.deepEqual(management.calls.consume, []);
|
||||
assert.deepEqual(management.calls.dispatch, []);
|
||||
});
|
||||
|
||||
test('routes publisher revocation proposal with derived-only low-sensitive output', async () => {
|
||||
const management = fakeService();
|
||||
const publisherTrust = fakePublisherTrust();
|
||||
|
||||
@@ -54,6 +54,7 @@ function executorPrivileges() {
|
||||
'approval_requests',
|
||||
'plugin_package_install_proposals',
|
||||
'plugin_package_secret_binding_approval_plans',
|
||||
'plugin_package_secret_binding_transition_approval_plans',
|
||||
'plugin_package_task_ownerships',
|
||||
'plugin_package_task_reconciliations',
|
||||
'plugin_package_task_reconciliation_items',
|
||||
@@ -217,6 +218,8 @@ function database(serverVersionNum = '160014') {
|
||||
'register_plugin_package_automation_disposition_event',
|
||||
'create_plugin_package_secret_binding_approval_plan',
|
||||
'plugin_package_secret_binding_planning_snapshot',
|
||||
'create_plugin_package_secret_transition_plan',
|
||||
'plugin_package_secret_binding_transition_snapshot',
|
||||
].includes(functionName),
|
||||
isOwner: false,
|
||||
})),
|
||||
|
||||
+285
@@ -11,6 +11,7 @@ const {
|
||||
createPostgresDatabaseOpener,
|
||||
PostgresPluginPackageSecretBindingApprovalPlanReader,
|
||||
PostgresPluginPackageSecretBindingRepository,
|
||||
PostgresPluginPackageSecretBindingTransitionApprovalPlanReader,
|
||||
} = require('@qinglong/cluster-postgres/package-executor');
|
||||
const {
|
||||
PostgresApprovedActionExecutionRepository,
|
||||
@@ -62,6 +63,12 @@ const {
|
||||
const {
|
||||
ClusterPluginPackageSecretBindingApprovedActionHandler,
|
||||
} = require('@qinglong/cluster-admin/plugin-package-secret-binding-approved-action');
|
||||
const {
|
||||
createClusterPluginPackageSecretBindingTransitionManagementService,
|
||||
} = require('@qinglong/cluster-admin/plugin-package-secret-binding-transition-management');
|
||||
const {
|
||||
consumeClusterPluginPackageSecretBindingTransitionApprovals,
|
||||
} = require('@qinglong/cluster-admin/plugin-package-secret-binding-transition-approval-consumer');
|
||||
|
||||
const MIGRATION_URL =
|
||||
process.env.QL3_TEST_POSTGRES_MIGRATION_URL ??
|
||||
@@ -525,6 +532,284 @@ if (!MIGRATION_URL || !MANAGER_URL || !EXECUTOR_URL) {
|
||||
assert.deepEqual(binding.entries, plannedPublic.plan.entries);
|
||||
assert.doesNotMatch(JSON.stringify(binding), /secret-value/);
|
||||
assert.equal((await secretDispatcher.dispatchBatch({ limit: 4 })).scanned, 0);
|
||||
|
||||
const manifestV2 = Object.freeze({
|
||||
...manifest,
|
||||
metadata: Object.freeze({ ...manifest.metadata, version: '2.0.0' }),
|
||||
});
|
||||
const actionInputV2 = Object.freeze({
|
||||
lockId: `lock-v2-${suffix}`,
|
||||
projectId,
|
||||
manifest: manifestV2,
|
||||
previousManifest: manifest,
|
||||
plan: planPluginPackageInstall(manifestV2, environment, manifest),
|
||||
environment,
|
||||
source: {
|
||||
kind: 'offline',
|
||||
locator: `offline:sha256:${'e'.repeat(64)}`,
|
||||
artifactDigest: 'e'.repeat(64),
|
||||
artifactBytes: 2048,
|
||||
contentDigest: 'f'.repeat(64),
|
||||
},
|
||||
architecture: 'arm64',
|
||||
deploymentProfile: 'cluster-control',
|
||||
targetGeneration: 2,
|
||||
previousLockDigest: lock.lockDigest,
|
||||
});
|
||||
const upgradeApprovalId = `upgrade-approval-${suffix}`;
|
||||
now += 10;
|
||||
const upgradeProposed = await installManagement.propose({
|
||||
actionRef: `install:${packageName}:v2`,
|
||||
approvalRequestId: upgradeApprovalId,
|
||||
proposalAuditEventId: randomUUID(),
|
||||
approvalAuditEventId: randomUUID(),
|
||||
requestedAtMs: now,
|
||||
actionInput: actionInputV2,
|
||||
principal: principal(requesterSubject, `upgrade-owner-${suffix}`, now),
|
||||
});
|
||||
now += 10;
|
||||
const upgradeDecision = await installManagement.decide({
|
||||
approvalRequestId: upgradeApprovalId,
|
||||
expectedVersion: upgradeProposed.approvalRequest.version,
|
||||
decisionId: `upgrade-decision-${suffix}`,
|
||||
auditEventId: randomUUID(),
|
||||
decision: 'approved',
|
||||
reasonCode: 'reviewed',
|
||||
decidedAtMs: now,
|
||||
principal: principal(reviewerSubject, `upgrade-reviewer-${suffix}`, now),
|
||||
});
|
||||
now += 10;
|
||||
const upgradeConsumed = await new PostgresApprovalRequestRepository(
|
||||
executor.pool,
|
||||
).consume({
|
||||
requestId: upgradeApprovalId,
|
||||
expectedVersion: upgradeDecision.request.version,
|
||||
consumptionId: `upgrade-consume-${suffix}`,
|
||||
dispatchId: `upgrade-dispatch-${suffix}`,
|
||||
action: upgradeDecision.request.action,
|
||||
requestedBy: requesterSubject,
|
||||
consumedBy: { type: 'system', id: 'cluster_package_executor' },
|
||||
consumedAtMs: now,
|
||||
authorizationFence: fence,
|
||||
audit: audit(
|
||||
randomUUID(),
|
||||
upgradeApprovalId,
|
||||
'approval.consume',
|
||||
projectId,
|
||||
{ type: 'system', id: 'cluster_package_executor' },
|
||||
now,
|
||||
fence,
|
||||
),
|
||||
});
|
||||
assert.equal(upgradeConsumed.status, 'consumed');
|
||||
id = 0;
|
||||
now += 10;
|
||||
const upgradeDispatch =
|
||||
await createClusterPluginPackageApprovedActionDispatcher({
|
||||
pool: executor.pool,
|
||||
owner: `upgrade-executor-${suffix}`,
|
||||
clock: () => now,
|
||||
createId: () => `upgrade-executor-id-${suffix}-${++id}`,
|
||||
secretExistenceInspector: inspector,
|
||||
}).dispatchBatch({ limit: 4 });
|
||||
assert.equal(upgradeDispatch.succeeded, 1);
|
||||
const queuedV2 = await installs.find(projectId, packageName);
|
||||
assert.ok(queuedV2);
|
||||
assert.equal(queuedV2.targetGeneration, 2);
|
||||
const lockV2 = await installs.findLock(queuedV2.lockDigest);
|
||||
assert.ok(lockV2);
|
||||
now += 10;
|
||||
const stagedV2 = transitionPluginPackageInstall(lockV2, queuedV2, {
|
||||
type: 'stage_completed',
|
||||
mutationId: `stage-v2-${suffix}`,
|
||||
occurredAtMs: now,
|
||||
stageRef: `stage:${lockV2.lockDigest}`,
|
||||
artifactDigest: lockV2.source.artifactDigest,
|
||||
manifestDigest: lockV2.manifestDigest,
|
||||
contentDigest: lockV2.source.contentDigest,
|
||||
evidenceDigest: '8'.repeat(64),
|
||||
});
|
||||
const provenanceV2 = createPluginPackagePublisherProvenance({
|
||||
projectId,
|
||||
packageName,
|
||||
installationId: queuedV2.installationId,
|
||||
lockDigest: lockV2.lockDigest,
|
||||
artifactDigest: stagedV2.stageReceipt.artifactDigest,
|
||||
manifestDigest: stagedV2.stageReceipt.manifestDigest,
|
||||
contentDigest: stagedV2.stageReceipt.contentDigest,
|
||||
stageEvidenceDigest: stagedV2.stageReceipt.evidenceDigest,
|
||||
signature: {
|
||||
publisher: 'integration.qinglong.dev',
|
||||
keyId: 'integration-key-1',
|
||||
signatureDigest: '9'.repeat(64),
|
||||
keyNotBeforeMs: now - 1,
|
||||
keyNotAfterMs: now + 60_000,
|
||||
verifiedAtMs: now,
|
||||
},
|
||||
});
|
||||
await executor.pool.query(
|
||||
`INSERT INTO "ql3"."plugin_package_publisher_provenance" (
|
||||
installation_id, project_id, package_name, lock_digest,
|
||||
artifact_digest, manifest_digest, content_digest,
|
||||
stage_evidence_digest, publisher, key_id, signature_digest,
|
||||
key_not_before_ms, key_not_after_ms, verified_at_ms,
|
||||
provenance_digest, provenance_json
|
||||
) VALUES (
|
||||
$1, $2, $3, $4, $5, $6, $7, $8, $9, $10, $11,
|
||||
$12, $13, $14, $15, $16::jsonb
|
||||
)`,
|
||||
[
|
||||
provenanceV2.installationId,
|
||||
provenanceV2.projectId,
|
||||
provenanceV2.packageName,
|
||||
provenanceV2.lockDigest,
|
||||
provenanceV2.artifactDigest,
|
||||
provenanceV2.manifestDigest,
|
||||
provenanceV2.contentDigest,
|
||||
provenanceV2.stageEvidenceDigest,
|
||||
provenanceV2.publisher,
|
||||
provenanceV2.keyId,
|
||||
provenanceV2.signatureDigest,
|
||||
provenanceV2.keyNotBeforeMs,
|
||||
provenanceV2.keyNotAfterMs,
|
||||
provenanceV2.verifiedAtMs,
|
||||
provenanceV2.provenanceDigest,
|
||||
JSON.stringify(provenanceV2),
|
||||
],
|
||||
);
|
||||
await installs.commit(pluginPackageInstallCommit(queuedV2, stagedV2));
|
||||
|
||||
const secretRefV2 = createSecretRef({
|
||||
projectId,
|
||||
name: 'runtime-token',
|
||||
version: 2,
|
||||
});
|
||||
writeFileSync(
|
||||
join(projectionRoot, secretProjectionFileName(secretRefV2)),
|
||||
'',
|
||||
{ mode: 0o440 },
|
||||
);
|
||||
const transitionActionRef = `secret-transition:${packageName}:v2`;
|
||||
const transitionApprovalId = `secret-transition-approval-${suffix}`;
|
||||
const transitionManagement =
|
||||
createClusterPluginPackageSecretBindingTransitionManagementService({
|
||||
pool: manager.pool,
|
||||
now: () => now,
|
||||
planLifetimeMs: 60_000,
|
||||
approvalLifetimeMs: 60_000,
|
||||
});
|
||||
const transitionTransport = createClusterPluginPackageManagementTransport({
|
||||
service: installManagement,
|
||||
secretBindingTransition: transitionManagement,
|
||||
now: () => now,
|
||||
});
|
||||
const transitionPlan = await transitionTransport.execute({
|
||||
schemaVersion: 1,
|
||||
operation: 'plugin-package.secret-binding.transition.plan',
|
||||
request: {
|
||||
actionRef: transitionActionRef,
|
||||
projectId,
|
||||
packageName,
|
||||
assignments: [{ name: 'TOKEN', secretRef: secretRefV2 }],
|
||||
},
|
||||
}, requesterAuthentication);
|
||||
assert.equal(transitionPlan.status, 'created');
|
||||
assert.equal(transitionPlan.plan.kind, 'rotate');
|
||||
assert.equal(transitionPlan.plan.previousGeneration, 1);
|
||||
assert.equal(transitionPlan.plan.nextGeneration, 2);
|
||||
assert.equal(
|
||||
transitionPlan.plan.previousActiveLockDigest,
|
||||
lock.lockDigest,
|
||||
);
|
||||
now = Math.max(now, transitionPlan.plan.plannedAtMs) + 10;
|
||||
const transitionProposed = await transitionTransport.execute({
|
||||
schemaVersion: 1,
|
||||
operation: 'plugin-package.secret-binding.transition.propose',
|
||||
request: {
|
||||
actionRef: transitionActionRef,
|
||||
approvalRequestId: transitionApprovalId,
|
||||
approvalAuditEventId: randomUUID(),
|
||||
},
|
||||
}, requesterAuthentication);
|
||||
now += 10;
|
||||
const transitionDecision = await transitionTransport.execute({
|
||||
schemaVersion: 1,
|
||||
operation: 'plugin-package.secret-binding.transition.decide',
|
||||
request: {
|
||||
actionRef: transitionActionRef,
|
||||
approvalRequestId: transitionApprovalId,
|
||||
expectedVersion: transitionProposed.approval.version,
|
||||
decisionId: `secret-transition-decision-${suffix}`,
|
||||
auditEventId: randomUUID(),
|
||||
decision: 'approved',
|
||||
reasonCode: 'reviewed',
|
||||
},
|
||||
}, {
|
||||
async authenticate() {
|
||||
return principal(
|
||||
reviewerSubject,
|
||||
`secret-transition-reviewer-${suffix}`,
|
||||
now,
|
||||
);
|
||||
},
|
||||
});
|
||||
assert.equal(transitionDecision.status, 'decided');
|
||||
now += 10;
|
||||
assert.deepEqual(
|
||||
await consumeClusterPluginPackageSecretBindingTransitionApprovals({
|
||||
pool: executor.pool,
|
||||
now: () => now,
|
||||
limit: 4,
|
||||
}),
|
||||
{ scanned: 1, consumed: 1, existing: 0, expired: 0, blocked: 0 },
|
||||
);
|
||||
const transitionApproval =
|
||||
await new PostgresApprovalRequestRepository(executor.pool).findById(
|
||||
transitionApprovalId,
|
||||
);
|
||||
assert.ok(transitionApproval?.dispatchId);
|
||||
const transitionExecution =
|
||||
await new PostgresApprovedActionExecutionRepository(
|
||||
executor.pool,
|
||||
).findExecutionByDispatchId(transitionApproval.dispatchId);
|
||||
assert.ok(transitionExecution);
|
||||
const storedTransitionPlan =
|
||||
await new PostgresPluginPackageSecretBindingTransitionApprovalPlanReader(
|
||||
executor.pool,
|
||||
).findByActionRef(transitionActionRef);
|
||||
assert.equal(
|
||||
storedTransitionPlan?.approvalPlanDigest,
|
||||
transitionPlan.plan.approvalPlanDigest,
|
||||
);
|
||||
id = 0;
|
||||
now += 10;
|
||||
const transitionDispatch =
|
||||
await createClusterPluginPackageApprovedActionDispatcher({
|
||||
pool: executor.pool,
|
||||
owner: `transition-executor-${suffix}`,
|
||||
clock: () => now,
|
||||
createId: () => `transition-executor-id-${suffix}-${++id}`,
|
||||
secretExistenceInspector: inspector,
|
||||
}).dispatchBatch({ limit: 4 });
|
||||
assert.equal(transitionDispatch.succeeded, 1);
|
||||
const transitionReceipt = await executor.pool.query(
|
||||
`SELECT receipt_json AS "receiptJson"
|
||||
FROM "ql3"."plugin_package_secret_binding_transition_receipts"
|
||||
WHERE generation_digest = $1`,
|
||||
[transitionPlan.plan.nextGenerationDigest],
|
||||
);
|
||||
assert.equal(transitionReceipt.rows.length, 1);
|
||||
assert.equal(
|
||||
transitionReceipt.rows[0].receiptJson.authority.evidenceDigest,
|
||||
transitionPlan.plan.approvalPlanDigest,
|
||||
);
|
||||
const bindingV2 = await bindings.find(
|
||||
transitionPlan.plan.nextGenerationDigest,
|
||||
);
|
||||
assert.ok(bindingV2);
|
||||
assert.deepEqual(bindingV2.entries, [
|
||||
{ name: 'TOKEN', required: false, secretRef: secretRefV2 },
|
||||
]);
|
||||
await assert.rejects(
|
||||
manager.pool.query(
|
||||
`SELECT * FROM "ql3"."plugin_package_secret_bindings" WHERE generation_digest = $1`,
|
||||
|
||||
+273
@@ -0,0 +1,273 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const { test } = require('node:test');
|
||||
|
||||
const {
|
||||
approvalRequestDigest,
|
||||
createApprovalRequest,
|
||||
decideApprovalRequest,
|
||||
} = require('@qinglong/runtime-core/approved-action');
|
||||
const {
|
||||
createPluginPackageResourceGeneration,
|
||||
} = require('@qinglong/runtime-core/plugin-package-resource-generation');
|
||||
const {
|
||||
createPluginPackageSecretBinding,
|
||||
} = require('@qinglong/runtime-core/plugin-package-secret-binding');
|
||||
const {
|
||||
createPluginPackageSecretBindingTransitionApprovalPlan,
|
||||
pluginPackageSecretBindingTransitionApprovedAction,
|
||||
} = require('@qinglong/runtime-core/plugin-package-secret-binding-transition-approval-plan');
|
||||
const {
|
||||
createPluginPackageSecretBindingTransitionPlan,
|
||||
} = require('@qinglong/runtime-core/plugin-package-secret-binding-transition-plan');
|
||||
const { createSecretRef } = require('@qinglong/runtime-core/secret-reference');
|
||||
const {
|
||||
consumeClusterPluginPackageSecretBindingTransitionApprovals,
|
||||
} = require('@qinglong/cluster-admin/plugin-package-secret-binding-transition-approval-consumer');
|
||||
|
||||
const REQUESTER = Object.freeze({ type: 'user', id: 'cluster-owner' });
|
||||
const REVIEWER = Object.freeze({ type: 'user', id: 'security-reviewer' });
|
||||
const FENCE = Object.freeze({ projectVersion: 3, bindingVersion: 4 });
|
||||
|
||||
function manifest(version) {
|
||||
return {
|
||||
apiVersion: 'qinglong.io/v1alpha1',
|
||||
kind: 'Package',
|
||||
metadata: {
|
||||
name: 'example-monitor',
|
||||
displayName: 'Example Monitor',
|
||||
version,
|
||||
description: 'Secret transition consumer fixture',
|
||||
license: 'Apache-2.0',
|
||||
},
|
||||
spec: {
|
||||
compatibility: {
|
||||
qinglong: '>=3.0.0-0 <4.0.0',
|
||||
architectures: ['arm64'],
|
||||
deploymentProfiles: ['cluster-control'],
|
||||
},
|
||||
runtimes: [],
|
||||
resources: {
|
||||
memory: { recommended: '32Mi' },
|
||||
disk: { install: '4Mi', working: '8Mi' },
|
||||
},
|
||||
permissions: {
|
||||
network: { allowedHosts: [] },
|
||||
secrets: [{ name: 'TOKEN', required: true }],
|
||||
tools: ['secret.use'],
|
||||
},
|
||||
contents: { tasks: [], workflows: [], prompts: [], tools: [] },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function plan() {
|
||||
const previousManifest = manifest('1.0.0');
|
||||
const previousGeneration = createPluginPackageResourceGeneration({
|
||||
installationId: 'install-secret-transition-v1',
|
||||
projectId: 'project-1',
|
||||
packageName: 'example-monitor',
|
||||
lockDigest: 'a'.repeat(64),
|
||||
generation: 1,
|
||||
previousActiveLockDigest: null,
|
||||
contentDigest: 'b'.repeat(64),
|
||||
contents: previousManifest.spec.contents,
|
||||
});
|
||||
const previousBinding = createPluginPackageSecretBinding({
|
||||
generation: previousGeneration,
|
||||
manifest: previousManifest,
|
||||
assignments: [{
|
||||
name: 'TOKEN',
|
||||
secretRef: createSecretRef({
|
||||
projectId: 'project-1',
|
||||
name: 'runtime-token',
|
||||
version: 1,
|
||||
}),
|
||||
}],
|
||||
authority: {
|
||||
kind: 'approved-action-execution',
|
||||
evidenceDigest: 'c'.repeat(64),
|
||||
},
|
||||
boundAtMs: 80,
|
||||
});
|
||||
const nextManifest = manifest('2.0.0');
|
||||
const transitionPlan = createPluginPackageSecretBindingTransitionPlan({
|
||||
previousTarget: previousBinding.target,
|
||||
previousBinding,
|
||||
previousAttemptGeneration: 1,
|
||||
nextGeneration: createPluginPackageResourceGeneration({
|
||||
installationId: 'install-secret-transition-v2',
|
||||
projectId: 'project-1',
|
||||
packageName: 'example-monitor',
|
||||
lockDigest: 'd'.repeat(64),
|
||||
generation: 2,
|
||||
previousActiveLockDigest: 'a'.repeat(64),
|
||||
contentDigest: 'e'.repeat(64),
|
||||
contents: nextManifest.spec.contents,
|
||||
}),
|
||||
nextManifest,
|
||||
assignments: [{
|
||||
name: 'TOKEN',
|
||||
secretRef: createSecretRef({
|
||||
projectId: 'project-1',
|
||||
name: 'runtime-token',
|
||||
version: 2,
|
||||
}),
|
||||
}],
|
||||
plannedAtMs: 100,
|
||||
});
|
||||
return createPluginPackageSecretBindingTransitionApprovalPlan({
|
||||
actionRef: 'secret-transition:example-monitor-v2',
|
||||
transitionPlan,
|
||||
requestedBy: REQUESTER,
|
||||
plannedAtMs: 100,
|
||||
expiresAtMs: 1_000,
|
||||
});
|
||||
}
|
||||
|
||||
function approvedRequest(candidate) {
|
||||
return decideApprovalRequest(
|
||||
createApprovalRequest({
|
||||
id: 'approval-secret-transition-1',
|
||||
projectId: 'project-1',
|
||||
action: pluginPackageSecretBindingTransitionApprovedAction(candidate),
|
||||
risk: 'high',
|
||||
decisionMode: 'separation_of_duty',
|
||||
requestedBy: REQUESTER,
|
||||
requestedAtMs: 110,
|
||||
expiresAtMs: 900,
|
||||
requestFence: FENCE,
|
||||
}),
|
||||
{
|
||||
expectedVersion: 1,
|
||||
decisionId: 'decision-secret-transition-1',
|
||||
decision: 'approved',
|
||||
reasonCode: 'reviewed',
|
||||
principal: {
|
||||
subject: REVIEWER,
|
||||
authenticationId: 'auth-reviewer',
|
||||
authenticatedAtMs: 100,
|
||||
expiresAtMs: 800,
|
||||
assurance: 'multi_factor',
|
||||
},
|
||||
decidedAtMs: 120,
|
||||
authorizationFence: FENCE,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
function pool(candidate, request, policyEffect = 'allow') {
|
||||
const dispatches = new Map();
|
||||
return {
|
||||
dispatches,
|
||||
async query(text, values) {
|
||||
if (text.includes('JOIN "ql3"."plugin_package_secret_binding_transition_approval_plans"')) {
|
||||
return {
|
||||
rows: [{
|
||||
requestJson: request,
|
||||
requestDigest: approvalRequestDigest(request),
|
||||
}],
|
||||
};
|
||||
}
|
||||
if (text.includes('FROM "ql3"."plugin_package_secret_binding_transition_approval_plans"')) {
|
||||
return { rows: [{ planJson: candidate }] };
|
||||
}
|
||||
if (text.includes('FROM "ql3"."projects" AS project')) {
|
||||
return policyEffect === 'deny'
|
||||
? { rows: [] }
|
||||
: {
|
||||
rows: [{
|
||||
projectId: 'project-1',
|
||||
projectName: 'Project 1',
|
||||
projectSlug: 'project-1',
|
||||
projectStatus: 'active',
|
||||
projectVersion: 3,
|
||||
projectCreatedAtMs: 1,
|
||||
projectUpdatedAtMs: 2,
|
||||
bindingProjectId: 'project-1',
|
||||
bindingSubjectType: 'user',
|
||||
bindingSubjectId: 'cluster-owner',
|
||||
bindingVersion: 4,
|
||||
bindingState: 'active',
|
||||
bindingRole: 'admin',
|
||||
bindingMutationId: 'binding-owner-v4',
|
||||
bindingChangedByType: 'user',
|
||||
bindingChangedById: 'root-owner',
|
||||
bindingCreatedAtMs: 2,
|
||||
}],
|
||||
};
|
||||
}
|
||||
if (
|
||||
text === 'BEGIN ISOLATION LEVEL SERIALIZABLE' ||
|
||||
text === 'COMMIT' ||
|
||||
text === 'ROLLBACK'
|
||||
) return { rows: [] };
|
||||
if (text.includes('SELECT set_config(')) return { rows: [{}] };
|
||||
if (text.includes('lock_approval_policy_fence')) {
|
||||
return { rows: [{ matches: true }] };
|
||||
}
|
||||
if (text.includes('FROM "ql3"."approval_requests"')) {
|
||||
return {
|
||||
rows: [{
|
||||
requestJson: request,
|
||||
requestDigest: approvalRequestDigest(request),
|
||||
}],
|
||||
};
|
||||
}
|
||||
if (text.includes('INSERT INTO "ql3"."approved_action_dispatches"')) {
|
||||
dispatches.set(values[0], values);
|
||||
return { rows: [], rowCount: 1 };
|
||||
}
|
||||
if (text.includes('INSERT INTO "ql3"."approved_action_executions"')) {
|
||||
return { rows: [], rowCount: 1 };
|
||||
}
|
||||
if (text.includes('UPDATE "ql3"."approval_requests"')) {
|
||||
return { rows: [], rowCount: 1 };
|
||||
}
|
||||
if (text.includes('INSERT INTO "ql3"."security_audit_events"')) {
|
||||
return { rows: [], rowCount: 1 };
|
||||
}
|
||||
throw new Error(`unexpected query: ${text}`);
|
||||
},
|
||||
async connect() {
|
||||
return { query: this.query.bind(this), release() {} };
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
test('consumes one exact approved Secret transition under a current requester fence', async () => {
|
||||
const candidate = plan();
|
||||
const request = approvedRequest(candidate);
|
||||
const database = pool(candidate, request);
|
||||
assert.deepEqual(
|
||||
await consumeClusterPluginPackageSecretBindingTransitionApprovals({
|
||||
pool: database,
|
||||
now: () => 130,
|
||||
limit: 4,
|
||||
}),
|
||||
{ scanned: 1, consumed: 1, existing: 0, expired: 0, blocked: 0 },
|
||||
);
|
||||
assert.equal(database.dispatches.size, 1);
|
||||
});
|
||||
|
||||
test('does not consume expired or no-longer-authorized Secret transitions', async () => {
|
||||
const candidate = plan();
|
||||
const request = approvedRequest(candidate);
|
||||
assert.deepEqual(
|
||||
await consumeClusterPluginPackageSecretBindingTransitionApprovals({
|
||||
pool: pool(candidate, request),
|
||||
now: () => 901,
|
||||
limit: 4,
|
||||
}),
|
||||
{ scanned: 1, consumed: 0, existing: 0, expired: 1, blocked: 0 },
|
||||
);
|
||||
assert.deepEqual(
|
||||
await consumeClusterPluginPackageSecretBindingTransitionApprovals({
|
||||
pool: pool(candidate, request, 'deny'),
|
||||
now: () => 130,
|
||||
limit: 4,
|
||||
}),
|
||||
{ scanned: 1, consumed: 0, existing: 0, expired: 0, blocked: 1 },
|
||||
);
|
||||
});
|
||||
+289
@@ -0,0 +1,289 @@
|
||||
'use strict';
|
||||
|
||||
const assert = require('node:assert/strict');
|
||||
const { test } = require('node:test');
|
||||
|
||||
const {
|
||||
consumeApprovalRequest,
|
||||
createApprovalRequest,
|
||||
decideApprovalRequest,
|
||||
} = require('@qinglong/runtime-core/approved-action');
|
||||
const {
|
||||
claimApprovedActionExecution,
|
||||
createApprovedActionExecution,
|
||||
startApprovedActionExecution,
|
||||
} = require('@qinglong/runtime-core/approved-action-execution');
|
||||
const {
|
||||
createPluginPackageResourceGeneration,
|
||||
} = require('@qinglong/runtime-core/plugin-package-resource-generation');
|
||||
const {
|
||||
createPluginPackageSecretBinding,
|
||||
} = require('@qinglong/runtime-core/plugin-package-secret-binding');
|
||||
const {
|
||||
createPluginPackageSecretBindingTransitionApprovalPlan,
|
||||
pluginPackageSecretBindingTransitionApprovedAction,
|
||||
} = require('@qinglong/runtime-core/plugin-package-secret-binding-transition-approval-plan');
|
||||
const {
|
||||
createPluginPackageSecretBindingTransitionPlan,
|
||||
} = require('@qinglong/runtime-core/plugin-package-secret-binding-transition-plan');
|
||||
const { createSecretRef } = require('@qinglong/runtime-core/secret-reference');
|
||||
const {
|
||||
ClusterPluginPackageSecretBindingTransitionApprovedActionHandler,
|
||||
} = require('@qinglong/cluster-admin/plugin-package-secret-binding-transition-approved-action');
|
||||
|
||||
const REQUESTER = Object.freeze({ type: 'user', id: 'cluster-owner' });
|
||||
const REVIEWER = Object.freeze({ type: 'user', id: 'security-reviewer' });
|
||||
const CONSUMER = Object.freeze({
|
||||
type: 'system',
|
||||
id: 'cluster_package_executor',
|
||||
});
|
||||
const FENCE = Object.freeze({ projectVersion: 3, bindingVersion: 4 });
|
||||
|
||||
function manifest(version) {
|
||||
return {
|
||||
apiVersion: 'qinglong.io/v1alpha1',
|
||||
kind: 'Package',
|
||||
metadata: {
|
||||
name: 'example-monitor',
|
||||
displayName: 'Example Monitor',
|
||||
version,
|
||||
description: 'Secret transition handler fixture',
|
||||
license: 'Apache-2.0',
|
||||
},
|
||||
spec: {
|
||||
compatibility: {
|
||||
qinglong: '>=3.0.0-0 <4.0.0',
|
||||
architectures: ['arm64'],
|
||||
deploymentProfiles: ['cluster-control'],
|
||||
},
|
||||
runtimes: [],
|
||||
resources: {
|
||||
memory: { recommended: '32Mi' },
|
||||
disk: { install: '4Mi', working: '8Mi' },
|
||||
},
|
||||
permissions: {
|
||||
network: { allowedHosts: [] },
|
||||
secrets: [{ name: 'TOKEN', required: true }],
|
||||
tools: ['secret.use'],
|
||||
},
|
||||
contents: { tasks: [], workflows: [], prompts: [], tools: [] },
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function approvalPlan() {
|
||||
const previousManifest = manifest('1.0.0');
|
||||
const previousGeneration = createPluginPackageResourceGeneration({
|
||||
installationId: 'install-secret-transition-v1',
|
||||
projectId: 'project-1',
|
||||
packageName: 'example-monitor',
|
||||
lockDigest: 'a'.repeat(64),
|
||||
generation: 1,
|
||||
previousActiveLockDigest: null,
|
||||
contentDigest: 'b'.repeat(64),
|
||||
contents: previousManifest.spec.contents,
|
||||
});
|
||||
const previousBinding = createPluginPackageSecretBinding({
|
||||
generation: previousGeneration,
|
||||
manifest: previousManifest,
|
||||
assignments: [{
|
||||
name: 'TOKEN',
|
||||
secretRef: createSecretRef({
|
||||
projectId: 'project-1',
|
||||
name: 'runtime-token',
|
||||
version: 1,
|
||||
}),
|
||||
}],
|
||||
authority: {
|
||||
kind: 'approved-action-execution',
|
||||
evidenceDigest: 'c'.repeat(64),
|
||||
},
|
||||
boundAtMs: 80,
|
||||
});
|
||||
const nextManifest = manifest('2.0.0');
|
||||
const transitionPlan = createPluginPackageSecretBindingTransitionPlan({
|
||||
previousTarget: previousBinding.target,
|
||||
previousBinding,
|
||||
previousAttemptGeneration: 1,
|
||||
nextGeneration: createPluginPackageResourceGeneration({
|
||||
installationId: 'install-secret-transition-v2',
|
||||
projectId: 'project-1',
|
||||
packageName: 'example-monitor',
|
||||
lockDigest: 'd'.repeat(64),
|
||||
generation: 2,
|
||||
previousActiveLockDigest: 'a'.repeat(64),
|
||||
contentDigest: 'e'.repeat(64),
|
||||
contents: nextManifest.spec.contents,
|
||||
}),
|
||||
nextManifest,
|
||||
assignments: [{
|
||||
name: 'TOKEN',
|
||||
secretRef: createSecretRef({
|
||||
projectId: 'project-1',
|
||||
name: 'runtime-token',
|
||||
version: 2,
|
||||
}),
|
||||
}],
|
||||
plannedAtMs: 100,
|
||||
});
|
||||
return createPluginPackageSecretBindingTransitionApprovalPlan({
|
||||
actionRef: 'secret-transition:example-monitor-v2',
|
||||
transitionPlan,
|
||||
requestedBy: REQUESTER,
|
||||
plannedAtMs: 100,
|
||||
expiresAtMs: 1_000,
|
||||
});
|
||||
}
|
||||
|
||||
function dispatch(plan) {
|
||||
const action = pluginPackageSecretBindingTransitionApprovedAction(plan);
|
||||
const pending = createApprovalRequest({
|
||||
id: 'approval-secret-transition-1',
|
||||
projectId: 'project-1',
|
||||
action,
|
||||
risk: 'high',
|
||||
decisionMode: 'separation_of_duty',
|
||||
requestedBy: REQUESTER,
|
||||
requestedAtMs: 110,
|
||||
expiresAtMs: 900,
|
||||
requestFence: FENCE,
|
||||
});
|
||||
const approved = decideApprovalRequest(pending, {
|
||||
expectedVersion: 1,
|
||||
decisionId: 'decision-secret-transition-1',
|
||||
decision: 'approved',
|
||||
reasonCode: 'reviewed',
|
||||
principal: {
|
||||
subject: REVIEWER,
|
||||
authenticationId: 'auth-reviewer',
|
||||
authenticatedAtMs: 100,
|
||||
expiresAtMs: 800,
|
||||
assurance: 'multi_factor',
|
||||
},
|
||||
decidedAtMs: 120,
|
||||
authorizationFence: FENCE,
|
||||
});
|
||||
return consumeApprovalRequest(approved, {
|
||||
expectedVersion: 2,
|
||||
consumptionId: 'consume-secret-transition-1',
|
||||
dispatchId: 'dispatch-secret-transition-1',
|
||||
action,
|
||||
requestedBy: REQUESTER,
|
||||
consumedBy: CONSUMER,
|
||||
consumedAtMs: 130,
|
||||
authorizationFence: FENCE,
|
||||
}).dispatch;
|
||||
}
|
||||
|
||||
function execution(approvedDispatch, startedAtMs = 140) {
|
||||
const claimed = claimApprovedActionExecution(
|
||||
createApprovedActionExecution(approvedDispatch, 5),
|
||||
{
|
||||
owner: 'secret-transition-executor',
|
||||
leaseToken: 'lease-secret-transition-1',
|
||||
nowMs: 131,
|
||||
leaseDurationMs: 2_000,
|
||||
},
|
||||
);
|
||||
return startApprovedActionExecution(
|
||||
{ dispatch: approvedDispatch, execution: claimed },
|
||||
{
|
||||
dispatchId: approvedDispatch.id,
|
||||
approvalRequestId: approvedDispatch.approvalRequestId,
|
||||
actionDigest: approvedDispatch.action.actionDigest,
|
||||
owner: claimed.leaseOwner,
|
||||
leaseToken: claimed.leaseToken,
|
||||
expectedVersion: claimed.version,
|
||||
startedAtMs,
|
||||
},
|
||||
);
|
||||
}
|
||||
|
||||
test('commits exactly one approved transition and verifies projected references', async () => {
|
||||
const plan = approvalPlan();
|
||||
const approvedDispatch = dispatch(plan);
|
||||
const started = execution(approvedDispatch);
|
||||
const applied = [];
|
||||
const inspected = [];
|
||||
const subject = new ClusterPluginPackageSecretBindingTransitionApprovedActionHandler(
|
||||
{ async findByActionRef() { return plan; } },
|
||||
{
|
||||
async apply(input) {
|
||||
applied.push(input);
|
||||
return {
|
||||
status: 'created',
|
||||
receipt: { receiptDigest: 'f'.repeat(64) },
|
||||
};
|
||||
},
|
||||
},
|
||||
{ async assertExists(refs) { inspected.push(...refs); } },
|
||||
);
|
||||
assert.deepEqual(await subject.inspect(approvedDispatch), {
|
||||
status: 'ready',
|
||||
actionDigest: plan.approvalPlanDigest,
|
||||
});
|
||||
const result = await subject.execute({
|
||||
dispatch: approvedDispatch,
|
||||
execution: started,
|
||||
idempotencyKey: approvedDispatch.id,
|
||||
fence: {
|
||||
owner: started.leaseOwner,
|
||||
leaseToken: started.leaseToken,
|
||||
version: started.version,
|
||||
},
|
||||
});
|
||||
assert.deepEqual(result, {
|
||||
outcome: 'succeeded',
|
||||
resultCode: 'package_secret_transition_committed',
|
||||
resultDigest: 'f'.repeat(64),
|
||||
});
|
||||
assert.equal(applied.length, 1);
|
||||
assert.deepEqual(applied[0], {
|
||||
transitionPlan: plan.transitionPlan,
|
||||
evidenceDigest: plan.approvalPlanDigest,
|
||||
committedAtMs: 140,
|
||||
});
|
||||
assert.deepEqual(inspected, [
|
||||
plan.transitionPlan.nextBindingPlan.entries[0].secretRef,
|
||||
plan.transitionPlan.nextBindingPlan.entries[0].secretRef,
|
||||
]);
|
||||
});
|
||||
|
||||
test('blocks plan drift and execution that starts after plan expiry', async () => {
|
||||
const plan = approvalPlan();
|
||||
const approvedDispatch = dispatch(plan);
|
||||
const applied = [];
|
||||
const subject = new ClusterPluginPackageSecretBindingTransitionApprovedActionHandler(
|
||||
{ async findByActionRef() { return plan; } },
|
||||
{ async apply(input) { applied.push(input); throw new Error('must not apply'); } },
|
||||
{ async assertExists() {} },
|
||||
);
|
||||
const late = execution(approvedDispatch, 1_001);
|
||||
assert.deepEqual(
|
||||
await subject.execute({
|
||||
dispatch: approvedDispatch,
|
||||
execution: late,
|
||||
idempotencyKey: approvedDispatch.id,
|
||||
fence: {
|
||||
owner: late.leaseOwner,
|
||||
leaseToken: late.leaseToken,
|
||||
version: late.version,
|
||||
},
|
||||
}),
|
||||
{
|
||||
outcome: 'failed',
|
||||
resultCode: 'package_secret_transition_plan_rejected',
|
||||
},
|
||||
);
|
||||
assert.equal(applied.length, 0);
|
||||
const drifted = { ...plan, approvalPlanDigest: '9'.repeat(64) };
|
||||
const driftedSubject = new ClusterPluginPackageSecretBindingTransitionApprovedActionHandler(
|
||||
{ async findByActionRef() { return drifted; } },
|
||||
{ async apply() { throw new Error('must not apply'); } },
|
||||
{ async assertExists() {} },
|
||||
);
|
||||
assert.deepEqual(await driftedSubject.inspect(approvedDispatch), {
|
||||
status: 'blocked',
|
||||
resultCode: 'package_secret_transition_plan_rejected',
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user