feat(ql3): establish 3.0 incubation baseline

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

No files matched your search

@@ -0,0 +1,234 @@
// Cluster Plugin Package publisher boundary; keep provenance recovery authority explicit.
import {
assertPluginPackageInstallMatchesLock,
type PluginPackageInstallCommit,
type PluginPackageInstallCreate,
type PluginPackageInstallRecord,
type PluginPackageInstallRecoveryCursor,
type PluginPackageInstallRecoveryPage,
type PluginPackageInstallRepository,
type PluginPackageLock,
} from '@qinglong/runtime-core/plugin-package-install';
import {
normalizePluginPackageStageEvidence,
type PluginPackageStageEvidence,
} from '@qinglong/runtime-core/plugin-package-installation';
import {
createPluginPackagePublisherProvenance,
type PluginPackagePublisherProvenance,
} from '@qinglong/runtime-core/plugin-package-publisher-provenance';
import {
PostgresPluginPackageInstallRepository,
} from '@qinglong/cluster-postgres/plugin-package-install';
import {
POSTGRES_PLUGIN_PACKAGE_PROVENANCE_RECOVERY_PAGE_LIMIT,
PostgresPluginPackagePublisherProvenanceRepository,
type PluginPackagePublisherProvenanceRecoveryCursor,
} from '@qinglong/cluster-postgres/package-executor';
import type { ClusterPluginPackageStageAuthority } from '../recovery/pluginPackageOciStage';
export const MAX_CLUSTER_PLUGIN_PACKAGE_PROVENANCE_RECOVERY_PAGES = 64;
export interface ClusterPluginPackagePublisherProvenanceRecoveryResult {
readonly pages: number;
readonly scanned: number;
readonly created: number;
readonly existing: number;
readonly remaining: boolean;
readonly safeToAdmit: boolean;
}
function stageEvidence(
record: Readonly<PluginPackageInstallRecord>,
): Readonly<PluginPackageStageEvidence> {
if (record.stageReceipt === null) {
throw new TypeError(
'Plugin Package install lacks durable stage evidence for provenance',
);
}
return normalizePluginPackageStageEvidence({
stageRef: record.stageReceipt.stageRef,
artifactDigest: record.stageReceipt.artifactDigest,
manifestDigest: record.stageReceipt.manifestDigest,
contentDigest: record.stageReceipt.contentDigest,
evidenceDigest: record.stageReceipt.evidenceDigest,
});
}
async function provenanceFor(
authority: ClusterPluginPackageStageAuthority,
lock: Readonly<PluginPackageLock>,
record: Readonly<PluginPackageInstallRecord>,
): Promise<Readonly<PluginPackagePublisherProvenance>> {
assertPluginPackageInstallMatchesLock(lock, record);
const stage = stageEvidence(record);
const signature = await authority.publisherEvidence(lock, stage);
return createPluginPackagePublisherProvenance({
projectId: record.projectId,
packageName: record.packageName,
installationId: record.installationId,
lockDigest: record.lockDigest,
artifactDigest: stage.artifactDigest,
manifestDigest: stage.manifestDigest,
contentDigest: stage.contentDigest,
stageEvidenceDigest: stage.evidenceDigest,
signature,
});
}
export class ClusterPluginPackageProvenanceInstallRepository
implements PluginPackageInstallRepository
{
constructor(
private readonly installs: PostgresPluginPackageInstallRepository,
private readonly provenance: PostgresPluginPackagePublisherProvenanceRepository,
private readonly authority: ClusterPluginPackageStageAuthority,
private readonly trustAuthorityId: string,
) {
if (
!(installs instanceof PostgresPluginPackageInstallRepository) ||
!(provenance instanceof
PostgresPluginPackagePublisherProvenanceRepository) ||
!authority ||
typeof authority.publisherEvidence !== 'function' ||
typeof trustAuthorityId !== 'string' ||
!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(trustAuthorityId)
) {
throw new TypeError(
'Cluster Plugin Package provenance install repository is invalid',
);
}
}
find(
projectId: string,
packageName: string,
): Promise<Readonly<PluginPackageInstallRecord> | null> {
return this.installs.find(projectId, packageName);
}
findLock(
lockDigest: string,
): Promise<Readonly<PluginPackageLock> | null> {
return this.installs.findLock(lockDigest);
}
create(command: Readonly<PluginPackageInstallCreate>): Promise<
Readonly<{
status: 'created' | 'existing';
record: Readonly<PluginPackageInstallRecord>;
}>
> {
return this.installs.create(command);
}
async commit(command: Readonly<PluginPackageInstallCommit>): Promise<
Readonly<{
status: 'committed' | 'existing';
record: Readonly<PluginPackageInstallRecord>;
}>
> {
if (command.record.state !== 'staged') {
return this.installs.commit(command);
}
const lock = await this.installs.findLock(command.record.lockDigest);
if (!lock) {
throw new TypeError('Plugin Package stage lock is unavailable');
}
return this.provenance.commitStage(
command,
await provenanceFor(this.authority, lock, command.record),
this.trustAuthorityId,
);
}
listRecoveryPage(options: {
readonly limit: number;
readonly after?: Readonly<PluginPackageInstallRecoveryCursor>;
}): Promise<Readonly<PluginPackageInstallRecoveryPage>> {
return this.installs.listRecoveryPage(options);
}
}
export async function recoverClusterPluginPackagePublisherProvenance(
installs: PostgresPluginPackageInstallRepository,
repository: PostgresPluginPackagePublisherProvenanceRepository,
authority: ClusterPluginPackageStageAuthority,
options: Readonly<{
trustAuthorityId: string;
pageSize?: number;
maxPages?: number;
}>,
): Promise<Readonly<ClusterPluginPackagePublisherProvenanceRecoveryResult>> {
const pageSize = options.pageSize ?? 16;
const maxPages = options.maxPages ?? 16;
if (
!(installs instanceof PostgresPluginPackageInstallRepository) ||
!(repository instanceof
PostgresPluginPackagePublisherProvenanceRepository) ||
!authority ||
typeof authority.verify !== 'function' ||
typeof authority.publisherEvidence !== 'function' ||
typeof options.trustAuthorityId !== 'string' ||
!/^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/.test(
options.trustAuthorityId,
) ||
!Number.isSafeInteger(pageSize) ||
pageSize < 1 ||
pageSize > POSTGRES_PLUGIN_PACKAGE_PROVENANCE_RECOVERY_PAGE_LIMIT ||
!Number.isSafeInteger(maxPages) ||
maxPages < 1 ||
maxPages > MAX_CLUSTER_PLUGIN_PACKAGE_PROVENANCE_RECOVERY_PAGES
) {
throw new TypeError(
'Cluster Plugin Package provenance recovery configuration is invalid',
);
}
let after:
| Readonly<PluginPackagePublisherProvenanceRecoveryCursor>
| undefined;
const counts = {
pages: 0,
scanned: 0,
created: 0,
existing: 0,
};
let exhausted = false;
while (counts.pages < maxPages) {
const page = await repository.listMissingPage({
limit: pageSize,
...(after ? { after } : {}),
});
counts.pages += 1;
for (const record of page.records) {
const lock = await installs.findLock(record.lockDigest);
if (!lock || record.stageReceipt === null) {
throw new TypeError(
'Cluster Plugin Package provenance recovery source is incomplete',
);
}
assertPluginPackageInstallMatchesLock(lock, record);
await authority.verify(lock, record.stageReceipt);
const result = await repository.recordExisting(
record,
await provenanceFor(authority, lock, record),
options.trustAuthorityId,
);
counts.scanned += 1;
counts[result.status] += 1;
}
if (!page.truncated) {
exhausted = true;
break;
}
after = page.next;
}
const probe = await repository.listMissingPage({ limit: 1 });
const remaining = !exhausted || probe.records.length > 0;
return Object.freeze({
...counts,
remaining,
safeToAdmit: !remaining,
});
}
@@ -0,0 +1,203 @@
// Cluster Plugin Package publisher boundary; keep revocation authority explicit.
import type {
OpenPostgresDatabase,
PostgresDatabaseResource,
} from '@qinglong/runtime-core';
import {
normalizePluginPackagePublisherRevocationReceipt,
type PluginPackagePublisherRevocationReceipt,
} from '@qinglong/runtime-core/plugin-package-publisher-provenance';
import {
createPluginPackageQuarantineEvent,
pluginPackageQuarantineMutationId,
} from '@qinglong/runtime-core/plugin-package-quarantine';
import {
PostgresPluginPackagePublisherProvenanceRepository,
PostgresPluginPackageQuarantineRepository,
assertPostgresPackageExecutorSchemaReady,
type PostgresSchemaReadinessReport,
} from '@qinglong/cluster-postgres/package-executor';
import {
CLUSTER_PLUGIN_PACKAGE_QUARANTINE_BATCH_LIMIT,
createClusterPluginPackageQuarantineService,
} from '../lifecycle/pluginPackageQuarantine';
export const MAX_CLUSTER_PLUGIN_PACKAGE_REVOCATION_PAGES = 64;
export interface RunClusterPluginPackagePublisherRevocationOptions {
readonly openDatabase: OpenPostgresDatabase;
readonly receipt: Readonly<PluginPackagePublisherRevocationReceipt>;
readonly confirmAuthorization: (
receipt: Readonly<PluginPackagePublisherRevocationReceipt>,
) => void | Promise<void>;
readonly pageSize?: number;
readonly maxPages?: number;
}
export interface ClusterPluginPackagePublisherRevocationRun {
readonly database: PostgresSchemaReadinessReport;
readonly receiptStatus: 'created' | 'existing';
readonly receiptDigest: string;
readonly impactDigest: string;
readonly impacted: number;
readonly pages: number;
readonly quarantined: number;
readonly existing: number;
readonly remaining: boolean;
readonly safeToAdmit: boolean;
}
function normalizedOptions(
options: RunClusterPluginPackagePublisherRevocationOptions,
): Readonly<{
receipt: Readonly<PluginPackagePublisherRevocationReceipt>;
pageSize: number;
maxPages: number;
}> {
if (
!options ||
typeof options !== 'object' ||
Array.isArray(options) ||
Object.keys(options).some(
(key) =>
![
'openDatabase',
'receipt',
'confirmAuthorization',
'pageSize',
'maxPages',
].includes(key),
) ||
typeof options.openDatabase !== 'function' ||
typeof options.confirmAuthorization !== 'function'
) {
throw new TypeError(
'Cluster Plugin Package publisher revocation options are invalid',
);
}
const pageSize = options.pageSize ?? 64;
const maxPages = options.maxPages ?? 32;
if (
!Number.isSafeInteger(pageSize) ||
pageSize < 1 ||
pageSize > CLUSTER_PLUGIN_PACKAGE_QUARANTINE_BATCH_LIMIT ||
!Number.isSafeInteger(maxPages) ||
maxPages < 1 ||
maxPages > MAX_CLUSTER_PLUGIN_PACKAGE_REVOCATION_PAGES
) {
throw new TypeError(
'Cluster Plugin Package publisher revocation bounds are invalid',
);
}
return Object.freeze({
receipt: normalizePluginPackagePublisherRevocationReceipt(options.receipt),
pageSize,
maxPages,
});
}
/**
* Short-lived administration composition. The immutable revocation receipt
* and its bounded impact are committed before quarantine materialization.
* Re-running the same receipt converges on the same facts and skips targets
* already quarantined or superseded by a newer installation head.
*/
export async function runClusterPluginPackagePublisherRevocation(
options: RunClusterPluginPackagePublisherRevocationOptions,
): Promise<Readonly<ClusterPluginPackagePublisherRevocationRun>> {
const normalized = normalizedOptions(options);
let database: PostgresDatabaseResource | undefined;
let result: Readonly<ClusterPluginPackagePublisherRevocationRun> | undefined;
let failure: unknown;
try {
database = await options.openDatabase();
const evidence = await assertPostgresPackageExecutorSchemaReady(
database.pool,
);
const provenance =
new PostgresPluginPackagePublisherProvenanceRepository(database.pool);
const quarantine = createClusterPluginPackageQuarantineService(
new PostgresPluginPackageQuarantineRepository(database.pool),
);
const impactResult = await provenance.recordRevocationImpact(
normalized.receipt,
() => options.confirmAuthorization(normalized.receipt),
);
let pages = 0;
let quarantined = 0;
let existing = 0;
while (pages < normalized.maxPages) {
const page = await provenance.listPendingQuarantineTargets(
impactResult.impact.impactDigest,
normalized.pageSize,
);
if (page.targets.length === 0) break;
const events = page.targets.map((target) =>
createPluginPackageQuarantineEvent({
mutationId: pluginPackageQuarantineMutationId(
normalized.receipt.receiptDigest,
target,
),
revocationReceiptDigest: normalized.receipt.receiptDigest,
impactDigest: impactResult.impact.impactDigest,
target,
proposer: normalized.receipt.proposer,
confirmer: normalized.receipt.confirmer,
authorizationMode: normalized.receipt.authorizationMode,
reasonCode: normalized.receipt.reasonCode,
occurredAtMs: normalized.receipt.revokedAtMs,
}),
);
const quarantineResults = await quarantine.quarantine(
events,
() => options.confirmAuthorization(normalized.receipt),
);
pages += 1;
for (const item of quarantineResults) {
if (item.status === 'created') quarantined += 1;
else existing += 1;
}
}
const probe = await provenance.listPendingQuarantineTargets(
impactResult.impact.impactDigest,
1,
);
const remaining = probe.targets.length > 0;
result = Object.freeze({
database: evidence,
receiptStatus: impactResult.status,
receiptDigest: normalized.receipt.receiptDigest,
impactDigest: impactResult.impact.impactDigest,
impacted: impactResult.impact.items.length,
pages,
quarantined,
existing,
remaining,
safeToAdmit: !remaining,
});
} catch (error) {
failure = error;
}
if (database) {
try {
await database.close();
} catch (closeError) {
if (failure !== undefined) {
throw new AggregateError(
[failure, closeError],
'Cluster Plugin Package publisher revocation failed and PostgreSQL did not close',
);
}
throw closeError;
}
}
if (failure !== undefined) throw failure;
if (!result) {
throw new Error(
'Cluster Plugin Package publisher revocation produced no result',
);
}
return result;
}
@@ -0,0 +1,172 @@
// Cluster Plugin Package publisher boundary; keep approval consumption authority explicit.
import { createHash } from 'node:crypto';
import { PostgresApprovalRequestRepository } from '@qinglong/cluster-postgres/approved-action';
import {
PostgresPluginPackagePublisherRevocationProposalRepository,
} from '@qinglong/cluster-postgres/package-executor';
import { PostgresProjectPolicyRepository } from '@qinglong/cluster-postgres/project-policy';
import type { PostgresPool } from '@qinglong/runtime-core';
import { ProjectPolicyEngine } from '@qinglong/runtime-core/project-policy';
export const CLUSTER_PLUGIN_PACKAGE_PUBLISHER_APPROVAL_BATCH_LIMIT = 16;
export interface ConsumeClusterPluginPackagePublisherRevocationApprovalsOptions {
readonly pool: PostgresPool;
readonly now?: () => number;
readonly limit?: number;
}
export interface ClusterPluginPackagePublisherRevocationApprovalSummary {
readonly scanned: number;
readonly consumed: number;
readonly existing: number;
readonly expired: number;
readonly blocked: number;
}
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-publisher-revocation-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 consumeClusterPluginPackagePublisherRevocationApprovals(
options: ConsumeClusterPluginPackagePublisherRevocationApprovalsOptions,
): Promise<
Readonly<ClusterPluginPackagePublisherRevocationApprovalSummary>
> {
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' ||
(options.now !== undefined && typeof options.now !== 'function')
) {
throw new TypeError(
'publisher revocation approval consumer options are invalid',
);
}
const limit =
options.limit ?? CLUSTER_PLUGIN_PACKAGE_PUBLISHER_APPROVAL_BATCH_LIMIT;
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 64) {
throw new TypeError(
'publisher revocation approval consumer limit is invalid',
);
}
const now = options.now ?? Date.now;
const observedAtMs = now();
if (!Number.isSafeInteger(observedAtMs) || observedAtMs < 0) {
throw new TypeError(
'publisher revocation approval consumer clock is invalid',
);
}
const proposals =
new PostgresPluginPackagePublisherRevocationProposalRepository(
options.pool,
);
const approvals = new PostgresApprovalRequestRepository(options.pool);
const policy = new ProjectPolicyEngine(
new PostgresProjectPolicyRepository(options.pool),
);
const requests = await proposals.listApprovedRequests(limit);
let consumed = 0;
let existing = 0;
let expired = 0;
let blocked = 0;
for (const request of requests) {
if (observedAtMs >= request.expiresAtMs) {
expired += 1;
continue;
}
const decision = await policy.decide({
subject: request.requestedBy,
projectId: request.projectId,
permission: 'package.manage',
});
if (
decision.fence === null ||
(decision.effect !== 'allow' &&
decision.effect !== 'require_approval')
) {
blocked += 1;
continue;
}
const consumptionId = stableId(
'pprc',
'qinglong/plugin-package-publisher-revocation-consumption@v1',
request.id,
);
const dispatchId = stableId(
'pprd',
'qinglong/plugin-package-publisher-revocation-dispatch@v1',
request.id,
);
const result = await approvals.consume({
requestId: request.id,
expectedVersion: request.version,
consumptionId,
dispatchId,
action: request.action,
requestedBy: request.requestedBy,
consumedBy: {
type: 'system',
id: 'cluster_package_executor',
},
consumedAtMs: observedAtMs,
authorizationFence: decision.fence,
audit: {
eventId: stableAuditEventId(request.id),
requestId: request.id,
operationId: 'approval.consume',
projectId: request.projectId,
subject: {
type: 'system',
id: 'cluster_package_executor',
},
authenticationId: 'cluster-package-executor',
outcome: 'allowed',
reasons: ['publisher_revocation_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,
});
}
@@ -0,0 +1,160 @@
// Cluster Plugin Package publisher boundary; keep Approved Action authority explicit.
import {
type ApprovedActionHandler,
type ApprovedActionHandlerExecutionContext,
type ApprovedActionHandlerInspection,
type ApprovedActionHandlerResult,
} from '@qinglong/runtime-core/approved-action-dispatcher';
import {
PLUGIN_PACKAGE_PUBLISHER_REVOCATION_ACTION_TYPE,
PluginPackagePublisherRevocationProposalBindingConflictError,
normalizePluginPackagePublisherRevocationProposal,
resolvePluginPackagePublisherRevocationProposal,
type PluginPackagePublisherRevocationProposalRepository,
} from '@qinglong/runtime-core/plugin-package-publisher-revocation-proposal';
import type {
PluginPackagePublisherRevocationReceipt,
} from '@qinglong/runtime-core/plugin-package-publisher-provenance';
export interface ClusterPluginPackagePublisherRevocationExecutionResult {
readonly safeToAdmit: boolean;
readonly receiptDigest: string;
readonly impactDigest: string;
}
export interface ClusterPluginPackagePublisherRevocationExecutionPort {
run(
receipt: Readonly<PluginPackagePublisherRevocationReceipt>,
): Promise<
Readonly<ClusterPluginPackagePublisherRevocationExecutionResult>
>;
}
export class ClusterPluginPackagePublisherRevocationApprovedActionHandler
implements ApprovedActionHandler
{
readonly actionType = PLUGIN_PACKAGE_PUBLISHER_REVOCATION_ACTION_TYPE;
constructor(
readonly proposals: PluginPackagePublisherRevocationProposalRepository,
readonly revocations: ClusterPluginPackagePublisherRevocationExecutionPort,
) {
if (
!proposals ||
typeof proposals.findProposalByActionRef !== 'function' ||
!revocations ||
typeof revocations.run !== 'function'
) {
throw new TypeError(
'publisher revocation Approved Action authority is invalid',
);
}
}
async inspect(
dispatch: ApprovedActionHandlerExecutionContext['dispatch'],
): Promise<ApprovedActionHandlerInspection> {
let proposal;
try {
proposal = await this.proposals.findProposalByActionRef(
dispatch.action.actionRef,
);
} catch {
return Object.freeze({
status: 'retry',
resultCode: 'publisher_revocation_proposal_unavailable',
});
}
if (!proposal) {
return Object.freeze({
status: 'blocked',
resultCode: 'publisher_revocation_proposal_missing',
});
}
try {
const normalized =
normalizePluginPackagePublisherRevocationProposal(proposal);
resolvePluginPackagePublisherRevocationProposal(
normalized,
dispatch,
dispatch.createdAtMs,
);
return Object.freeze({
status: 'ready',
actionDigest: normalized.actionDigest,
});
} catch {
return Object.freeze({
status: 'blocked',
resultCode: 'publisher_revocation_proposal_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: 'publisher_revocation_execution_rejected',
});
}
const proposal = await this.proposals.findProposalByActionRef(
context.dispatch.action.actionRef,
);
if (!proposal) {
return Object.freeze({
outcome: 'failed',
resultCode: 'publisher_revocation_proposal_missing',
});
}
let receipt;
try {
receipt = resolvePluginPackagePublisherRevocationProposal(
proposal,
context.dispatch,
startedAtMs,
);
} catch (error) {
if (
error instanceof
PluginPackagePublisherRevocationProposalBindingConflictError
) {
return Object.freeze({
outcome: 'failed',
resultCode: 'publisher_revocation_proposal_rejected',
});
}
throw error;
}
const result = await this.revocations.run(receipt);
if (!result.safeToAdmit) {
return Object.freeze({
outcome: 'indeterminate',
resultCode: 'publisher_revocation_convergence_incomplete',
});
}
if (
result.receiptDigest !== receipt.receiptDigest ||
!/^[0-9a-f]{64}$/.test(result.impactDigest)
) {
return Object.freeze({
outcome: 'failed',
resultCode: 'publisher_revocation_result_rejected',
});
}
return Object.freeze({
outcome: 'succeeded',
resultCode: 'publisher_revocation_converged',
resultDigest: result.impactDigest,
});
}
}
@@ -0,0 +1,178 @@
// Cluster Plugin Package publisher boundary; keep transition approval authority explicit.
import { createHash } from 'node:crypto';
import { PostgresApprovalRequestRepository } from '@qinglong/cluster-postgres/approved-action';
import {
PostgresPluginPackagePublisherTrustTransitionProposalRepository,
} from '@qinglong/cluster-postgres/package-executor';
import { PostgresProjectPolicyRepository } from '@qinglong/cluster-postgres/project-policy';
import type { PostgresPool } from '@qinglong/runtime-core';
import { ProjectPolicyEngine } from '@qinglong/runtime-core/project-policy';
export const CLUSTER_PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_APPROVAL_BATCH_LIMIT =
16;
export interface ConsumeClusterPluginPackagePublisherTrustTransitionApprovalsOptions {
readonly pool: PostgresPool;
readonly now?: () => number;
readonly limit?: number;
}
export interface ClusterPluginPackagePublisherTrustTransitionApprovalSummary {
readonly scanned: number;
readonly consumed: number;
readonly existing: number;
readonly expired: number;
readonly blocked: number;
}
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-publisher-trust-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 consumeClusterPluginPackagePublisherTrustTransitionApprovals(
options: ConsumeClusterPluginPackagePublisherTrustTransitionApprovalsOptions,
): Promise<
Readonly<ClusterPluginPackagePublisherTrustTransitionApprovalSummary>
> {
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' ||
(options.now !== undefined && typeof options.now !== 'function')
) {
throw new TypeError(
'publisher trust transition approval consumer options are invalid',
);
}
const limit =
options.limit ??
CLUSTER_PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_APPROVAL_BATCH_LIMIT;
if (!Number.isSafeInteger(limit) || limit < 1 || limit > 64) {
throw new TypeError(
'publisher trust transition approval consumer limit is invalid',
);
}
const now = options.now ?? Date.now;
const observedAtMs = now();
if (!Number.isSafeInteger(observedAtMs) || observedAtMs < 0) {
throw new TypeError(
'publisher trust transition approval consumer clock is invalid',
);
}
const proposals =
new PostgresPluginPackagePublisherTrustTransitionProposalRepository(
options.pool,
);
const approvals = new PostgresApprovalRequestRepository(options.pool);
const policy = new ProjectPolicyEngine(
new PostgresProjectPolicyRepository(options.pool),
);
const requests = await proposals.listApprovedRequests(limit);
let consumed = 0;
let existing = 0;
let expired = 0;
let blocked = 0;
for (const request of requests) {
if (observedAtMs >= request.expiresAtMs) {
expired += 1;
continue;
}
if (request.decisionMode !== 'separation_of_duty') {
blocked += 1;
continue;
}
const decision = await policy.decide({
subject: request.requestedBy,
projectId: request.projectId,
permission: 'package.manage',
});
if (
decision.fence === null ||
(decision.effect !== 'allow' &&
decision.effect !== 'require_approval')
) {
blocked += 1;
continue;
}
const consumptionId = stableId(
'ppttc',
'qinglong/plugin-package-publisher-trust-transition-consumption@v1',
request.id,
);
const dispatchId = stableId(
'ppttd',
'qinglong/plugin-package-publisher-trust-transition-dispatch@v1',
request.id,
);
const result = await approvals.consume({
requestId: request.id,
expectedVersion: request.version,
consumptionId,
dispatchId,
action: request.action,
requestedBy: request.requestedBy,
consumedBy: {
type: 'system',
id: 'cluster_package_executor',
},
consumedAtMs: observedAtMs,
authorizationFence: decision.fence,
audit: {
eventId: stableAuditEventId(request.id),
requestId: request.id,
operationId: 'approval.consume',
projectId: request.projectId,
subject: {
type: 'system',
id: 'cluster_package_executor',
},
authenticationId: 'cluster-package-executor',
outcome: 'allowed',
reasons: ['publisher_trust_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,
});
}
@@ -0,0 +1,167 @@
// Cluster Plugin Package publisher boundary; keep transition execution authority explicit.
import {
type ApprovedActionHandler,
type ApprovedActionHandlerExecutionContext,
type ApprovedActionHandlerInspection,
type ApprovedActionHandlerResult,
} from '@qinglong/runtime-core/approved-action-dispatcher';
import {
PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_ACTION_TYPES,
PluginPackagePublisherTrustTransitionBindingConflictError,
PluginPackagePublisherTrustTransitionConflictError,
normalizePluginPackagePublisherTrustTransitionProposal,
resolvePluginPackagePublisherTrustTransitionProposal,
type PluginPackagePublisherTrustTransitionMode,
type PluginPackagePublisherTrustTransitionProposalRepository,
type PluginPackagePublisherTrustTransitionReceipt,
} from '@qinglong/runtime-core/plugin-package-publisher-trust-transition-proposal';
export interface ClusterPluginPackagePublisherTrustTransitionExecutionResult {
readonly status: 'created' | 'existing';
readonly receipt: Readonly<PluginPackagePublisherTrustTransitionReceipt>;
readonly head: Readonly<{
generation: number;
effectiveTrustDigest: string;
}>;
}
export interface ClusterPluginPackagePublisherTrustTransitionExecutionPort {
applyApprovedTransition(
input: Readonly<{
dispatch: ApprovedActionHandlerExecutionContext['dispatch'];
executedAtMs: number;
}>,
): Promise<
Readonly<ClusterPluginPackagePublisherTrustTransitionExecutionResult>
>;
}
export class ClusterPluginPackagePublisherTrustTransitionApprovedActionHandler
implements ApprovedActionHandler
{
readonly actionType:
(typeof PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_ACTION_TYPES)[PluginPackagePublisherTrustTransitionMode];
constructor(
readonly mode: PluginPackagePublisherTrustTransitionMode,
readonly proposals: PluginPackagePublisherTrustTransitionProposalRepository,
readonly transitions: ClusterPluginPackagePublisherTrustTransitionExecutionPort,
) {
this.actionType =
PLUGIN_PACKAGE_PUBLISHER_TRUST_TRANSITION_ACTION_TYPES[mode];
if (
(mode !== 'overlap_add' && mode !== 'safe_retire') ||
!proposals ||
typeof proposals.findProposalByActionRef !== 'function' ||
!transitions ||
typeof transitions.applyApprovedTransition !== 'function'
) {
throw new TypeError(
'publisher trust transition Approved Action authority is invalid',
);
}
}
async inspect(
dispatch: ApprovedActionHandlerExecutionContext['dispatch'],
): Promise<ApprovedActionHandlerInspection> {
let proposal;
try {
proposal = await this.proposals.findProposalByActionRef(
dispatch.action.actionRef,
);
} catch {
return Object.freeze({
status: 'retry',
resultCode: 'publisher_trust_transition_proposal_unavailable',
});
}
if (!proposal) {
return Object.freeze({
status: 'blocked',
resultCode: 'publisher_trust_transition_proposal_missing',
});
}
try {
const normalized =
normalizePluginPackagePublisherTrustTransitionProposal(proposal);
if (
normalized.actionInput.mode !== this.mode ||
normalized.actionType !== this.actionType
) {
throw new PluginPackagePublisherTrustTransitionBindingConflictError();
}
resolvePluginPackagePublisherTrustTransitionProposal(
normalized,
dispatch,
dispatch.createdAtMs,
this.mode === 'safe_retire' ? 0 : null,
);
return Object.freeze({
status: 'ready',
actionDigest: normalized.actionDigest,
});
} catch {
return Object.freeze({
status: 'blocked',
resultCode: 'publisher_trust_transition_proposal_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: 'publisher_trust_transition_execution_rejected',
});
}
try {
const result = await this.transitions.applyApprovedTransition({
dispatch: context.dispatch,
executedAtMs: startedAtMs,
});
if (
result.receipt.mode !== this.mode ||
result.receipt.mutationId !== context.dispatch.id ||
result.head.generation !== result.receipt.currentGeneration ||
result.head.effectiveTrustDigest !==
result.receipt.currentTrustDigest
) {
return Object.freeze({
outcome: 'failed',
resultCode: 'publisher_trust_transition_result_rejected',
});
}
return Object.freeze({
outcome: 'succeeded',
resultCode:
this.mode === 'overlap_add'
? 'publisher_trust_overlap_added'
: 'publisher_trust_key_retired',
resultDigest: result.receipt.receiptDigest,
});
} catch (error) {
if (
error instanceof
PluginPackagePublisherTrustTransitionBindingConflictError ||
error instanceof PluginPackagePublisherTrustTransitionConflictError
) {
return Object.freeze({
outcome: 'failed',
resultCode: 'publisher_trust_transition_conflict',
});
}
throw error;
}
}
}