mirror of
https://github.com/whyour/qinglong.git
synced 2026-09-22 02:27:44 +08:00
feat(ql3): separate cluster secret transition authority
This commit is contained in:
@@ -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,
|
||||
});
|
||||
},
|
||||
});
|
||||
}
|
||||
Reference in New Issue
Block a user