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,608 @@
/** Model-provider credential management application service boundary. */
import {
InvalidModelProviderCredentialAdministrationMutationError,
ModelProviderCredentialAdministrationAuthorizationFenceConflictError,
ModelProviderCredentialAdministrationMutationConflictError,
modelProviderCredentialAdministrationOperationId,
type ModelProviderCredentialAdministrationRepository,
} from '@qinglong/ai/model-provider-credential-administration';
import {
MODEL_PROVIDER_CREDENTIAL_TRANSITION_COMMAND_SCHEMA,
InvalidModelProviderCredentialTransitionError,
ModelProviderCredentialCatalogUnavailableError,
ModelProviderCredentialTransitionConflictError,
createModelProviderCredentialTransitionCommand,
type CommitModelProviderCredentialTransitionResult,
} from '@qinglong/ai/model-provider-credential-catalog';
import { MODEL_PROVIDER_CREDENTIAL_BINDING_SCHEMA } from '@qinglong/ai/provider-credential';
import {
MAX_MODEL_PROVIDER_CREDENTIAL_TEST_PLAN_LIFETIME_MS,
InvalidModelProviderCredentialTestConnectionError,
createModelProviderCredentialTestPlan,
normalizeModelProviderCredentialTestAllowlist,
resolveModelProviderCredentialTestEndpoint,
type ModelProviderCredentialTestAllowlist,
} from '@qinglong/ai/model-provider-credential-test-connection';
import {
InvalidModelProviderCredentialManagementAuditQueryError,
MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_AUDIT_QUERY_OPERATION_ID,
ModelProviderCredentialManagementAuditAuthorizationFenceConflictError,
ModelProviderCredentialManagementAuditConflictError,
ModelProviderCredentialManagementAuditUnavailableError,
normalizeModelProviderCredentialManagementAuditQuery,
type ModelProviderCredentialManagementAuditCursor,
type ModelProviderCredentialManagementAuditPage,
type ModelProviderCredentialManagementAuditQueryRepository,
} from '@qinglong/ai/postgres-model-provider-credential-management-audit-query';
import {
MODEL_PROVIDER_CREDENTIAL_TEST_PLAN_OPERATION_ID,
ModelProviderCredentialTestPlanAuthorizationFenceConflictError,
ModelProviderCredentialTestPlanConflictError,
ModelProviderCredentialTestPlanQuotaExceededError,
ModelProviderCredentialTestPlanUnavailableError,
type CreateModelProviderCredentialTestPlanResult,
type ModelProviderCredentialTestPlanRepository,
} from '@qinglong/ai/postgres-model-provider-credential-test-connection';
import type { ProjectPermission } from '@qinglong/runtime-core/project-policy';
import {
normalizeSecurityPrincipal,
type SecurityPolicyDecision,
type SecurityPrincipal,
} from '@qinglong/runtime-core/security';
const REQUEST_ID_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,127}$/;
const IDENTITY_PATTERN = /^[A-Za-z0-9][A-Za-z0-9._:/-]{0,127}$/;
const UUID_PATTERN =
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
const STRONG_USER_ASSURANCES = new Set(['multi_factor', 'hardware']);
const MAX_PRINCIPAL_AGE_MS = 5 * 60 * 1_000;
interface BaseMutationRequest {
readonly requestId: string;
readonly mutationId: string;
readonly projectId: string;
readonly provider: string;
readonly expectedGeneration: number;
readonly principal: SecurityPrincipal;
}
export interface BindModelProviderCredentialRequest
extends BaseMutationRequest {
readonly revision: string;
readonly secretRef: string;
}
export interface RevokeModelProviderCredentialRequest
extends BaseMutationRequest {}
export interface ListModelProviderCredentialManagementAuditRequest {
readonly requestId: string;
readonly queryId: string;
readonly projectId: string;
readonly limit: number;
readonly before?: ModelProviderCredentialManagementAuditCursor;
readonly principal: SecurityPrincipal;
}
export interface PlanModelProviderCredentialTestRequest {
readonly requestId: string;
readonly testId: string;
readonly projectId: string;
readonly provider: string;
readonly principal: SecurityPrincipal;
}
export interface ClusterModelProviderCredentialManagementPolicy {
authorize(
principal: Readonly<SecurityPrincipal>,
projectId: string,
permission: ProjectPermission,
): Promise<Readonly<SecurityPolicyDecision>>;
}
export interface ClusterModelProviderCredentialManagementService {
bind(
request: Readonly<BindModelProviderCredentialRequest>,
): Promise<Readonly<CommitModelProviderCredentialTransitionResult>>;
revoke(
request: Readonly<RevokeModelProviderCredentialRequest>,
): Promise<Readonly<CommitModelProviderCredentialTransitionResult>>;
listAudit(
request: Readonly<ListModelProviderCredentialManagementAuditRequest>,
): Promise<Readonly<ModelProviderCredentialManagementAuditPage>>;
planTestConnection(
request: Readonly<PlanModelProviderCredentialTestRequest>,
): Promise<Readonly<CreateModelProviderCredentialTestPlanResult>>;
}
export interface ClusterModelProviderCredentialManagementOptions {
readonly policy: ClusterModelProviderCredentialManagementPolicy;
readonly credentials: ModelProviderCredentialAdministrationRepository;
readonly audit: ModelProviderCredentialManagementAuditQueryRepository;
readonly testPlans: ModelProviderCredentialTestPlanRepository;
readonly testAllowlist: ModelProviderCredentialTestAllowlist;
readonly testPlanLifetimeMs?: number;
readonly now?: () => number;
}
export class ClusterModelProviderCredentialManagementRequestError extends TypeError {
readonly code =
'CLUSTER_MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_REQUEST_INVALID';
constructor() {
super('Cluster model provider credential management request is invalid');
this.name = 'ClusterModelProviderCredentialManagementRequestError';
}
}
export class ClusterModelProviderCredentialManagementAuthenticationError extends Error {
readonly code =
'CLUSTER_MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_AUTHENTICATION_REQUIRED';
constructor() {
super(
'Cluster model provider credential management requires a recent strong User',
);
this.name = 'ClusterModelProviderCredentialManagementAuthenticationError';
}
}
export class ClusterModelProviderCredentialManagementAuthorizationError extends Error {
readonly code = 'CLUSTER_MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_FORBIDDEN';
constructor() {
super('Cluster model provider credential management is forbidden');
this.name = 'ClusterModelProviderCredentialManagementAuthorizationError';
}
}
export class ClusterModelProviderCredentialManagementConflictError extends Error {
readonly code = 'CLUSTER_MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_CONFLICT';
constructor() {
super(
'Cluster model provider credential management conflicts with durable state',
);
this.name = 'ClusterModelProviderCredentialManagementConflictError';
}
}
export class ClusterModelProviderCredentialManagementUnavailableError extends Error {
readonly code = 'CLUSTER_MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_UNAVAILABLE';
constructor() {
super('Cluster model provider credential management is unavailable');
this.name = 'ClusterModelProviderCredentialManagementUnavailableError';
}
}
export class ClusterModelProviderCredentialManagementQuotaExceededError extends Error {
readonly code = 'CLUSTER_MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_QUOTA_EXCEEDED';
constructor(readonly retryAfterMs: number) {
super('Cluster model provider credential management quota is exceeded');
this.name = 'ClusterModelProviderCredentialManagementQuotaExceededError';
}
}
function exactKeys(value: object, expected: readonly string[]): boolean {
const actual = Object.keys(value).sort();
const canonical = [...expected].sort();
return (
actual.length === canonical.length &&
actual.every((key, index) => key === canonical[index])
);
}
function normalizeBaseRequest(
value: BaseMutationRequest,
expectedKeys: readonly string[],
): Readonly<BaseMutationRequest> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, expectedKeys) ||
typeof value.requestId !== 'string' ||
!REQUEST_ID_PATTERN.test(value.requestId) ||
typeof value.mutationId !== 'string' ||
!UUID_PATTERN.test(value.mutationId) ||
typeof value.projectId !== 'string' ||
!IDENTITY_PATTERN.test(value.projectId) ||
typeof value.provider !== 'string' ||
!IDENTITY_PATTERN.test(value.provider) ||
!Number.isSafeInteger(value.expectedGeneration) ||
value.expectedGeneration < 0 ||
value.expectedGeneration > 2_147_483_646
) {
throw new ClusterModelProviderCredentialManagementRequestError();
}
return value;
}
function mapMutationError(error: unknown): never {
if (
error instanceof
InvalidModelProviderCredentialAdministrationMutationError ||
error instanceof InvalidModelProviderCredentialTransitionError
) {
throw new ClusterModelProviderCredentialManagementRequestError();
}
if (
error instanceof
ModelProviderCredentialAdministrationAuthorizationFenceConflictError ||
error instanceof
ModelProviderCredentialAdministrationMutationConflictError ||
error instanceof ModelProviderCredentialTransitionConflictError
) {
throw new ClusterModelProviderCredentialManagementConflictError();
}
if (error instanceof ModelProviderCredentialCatalogUnavailableError) {
throw new ClusterModelProviderCredentialManagementUnavailableError();
}
throw new ClusterModelProviderCredentialManagementUnavailableError();
}
function mapAuditError(error: unknown): never {
if (
error instanceof InvalidModelProviderCredentialManagementAuditQueryError
) {
throw new ClusterModelProviderCredentialManagementRequestError();
}
if (
error instanceof
ModelProviderCredentialManagementAuditAuthorizationFenceConflictError ||
error instanceof ModelProviderCredentialManagementAuditConflictError
) {
throw new ClusterModelProviderCredentialManagementConflictError();
}
if (error instanceof ModelProviderCredentialManagementAuditUnavailableError) {
throw new ClusterModelProviderCredentialManagementUnavailableError();
}
throw new ClusterModelProviderCredentialManagementUnavailableError();
}
function mapTestPlanError(error: unknown): never {
if (error instanceof InvalidModelProviderCredentialTestConnectionError) {
throw new ClusterModelProviderCredentialManagementRequestError();
}
if (
error instanceof
ModelProviderCredentialTestPlanAuthorizationFenceConflictError ||
error instanceof ModelProviderCredentialTestPlanConflictError
) {
throw new ClusterModelProviderCredentialManagementConflictError();
}
if (error instanceof ModelProviderCredentialTestPlanQuotaExceededError) {
throw new ClusterModelProviderCredentialManagementQuotaExceededError(
error.retryAfterMs,
);
}
if (error instanceof ModelProviderCredentialTestPlanUnavailableError) {
throw new ClusterModelProviderCredentialManagementUnavailableError();
}
throw new ClusterModelProviderCredentialManagementUnavailableError();
}
export function createClusterModelProviderCredentialManagementService(
options: ClusterModelProviderCredentialManagementOptions,
): Readonly<ClusterModelProviderCredentialManagementService> {
if (
!options ||
typeof options !== 'object' ||
Array.isArray(options) ||
Object.keys(options).some(
(key) =>
key !== 'policy' &&
key !== 'credentials' &&
key !== 'audit' &&
key !== 'testPlans' &&
key !== 'testAllowlist' &&
key !== 'testPlanLifetimeMs' &&
key !== 'now',
) ||
!options.policy ||
typeof options.policy.authorize !== 'function' ||
!options.credentials ||
typeof options.credentials.commitAuthorized !== 'function' ||
typeof options.credentials.findCurrentTransition !== 'function' ||
typeof options.credentials.commit !== 'function' ||
!options.audit ||
typeof options.audit.listAuthorized !== 'function' ||
!options.testPlans ||
typeof options.testPlans.createAuthorized !== 'function' ||
(options.now !== undefined && typeof options.now !== 'function')
) {
throw new TypeError(
'Cluster model provider credential management options are invalid',
);
}
const now = options.now ?? Date.now;
let testAllowlist: Readonly<ModelProviderCredentialTestAllowlist>;
try {
testAllowlist = normalizeModelProviderCredentialTestAllowlist(
options.testAllowlist,
);
} catch {
throw new TypeError(
'Cluster model provider credential management options are invalid',
);
}
const testPlanLifetimeMs =
options.testPlanLifetimeMs ??
MAX_MODEL_PROVIDER_CREDENTIAL_TEST_PLAN_LIFETIME_MS;
if (
!Number.isSafeInteger(testPlanLifetimeMs) ||
testPlanLifetimeMs < 1_000 ||
testPlanLifetimeMs > MAX_MODEL_PROVIDER_CREDENTIAL_TEST_PLAN_LIFETIME_MS
) {
throw new TypeError(
'Cluster model provider credential management options are invalid',
);
}
const authorize = async (
principalValue: SecurityPrincipal,
projectId: string,
) => {
const observedAtMs = now();
if (!Number.isSafeInteger(observedAtMs) || observedAtMs < 0) {
throw new ClusterModelProviderCredentialManagementUnavailableError();
}
let principal: Readonly<SecurityPrincipal>;
try {
principal = normalizeSecurityPrincipal(principalValue, observedAtMs);
} catch {
throw new ClusterModelProviderCredentialManagementAuthenticationError();
}
if (
principal.subject.type !== 'user' ||
!STRONG_USER_ASSURANCES.has(principal.assurance) ||
observedAtMs - principal.authenticatedAtMs > MAX_PRINCIPAL_AGE_MS
) {
throw new ClusterModelProviderCredentialManagementAuthenticationError();
}
let decision: Readonly<SecurityPolicyDecision>;
try {
decision = await options.policy.authorize(
principal,
projectId,
'secret.manage',
);
} catch {
throw new ClusterModelProviderCredentialManagementUnavailableError();
}
if (
decision.effect !== 'allow' ||
decision.fence === null ||
decision.fence.bindingVersion === null
) {
throw new ClusterModelProviderCredentialManagementAuthorizationError();
}
return Object.freeze({ principal, decision, observedAtMs });
};
const commit = async (
request:
| Readonly<BindModelProviderCredentialRequest>
| Readonly<RevokeModelProviderCredentialRequest>,
action: 'bind' | 'revoke',
) => {
const authority = await authorize(request.principal, request.projectId);
let command;
try {
command = createModelProviderCredentialTransitionCommand({
schema: MODEL_PROVIDER_CREDENTIAL_TRANSITION_COMMAND_SCHEMA,
mutationId: request.mutationId,
projectId: request.projectId,
provider: request.provider,
expectedGeneration: request.expectedGeneration,
action,
binding:
action === 'bind'
? {
schema: MODEL_PROVIDER_CREDENTIAL_BINDING_SCHEMA,
projectId: request.projectId,
provider: request.provider,
revision: (request as BindModelProviderCredentialRequest)
.revision,
secretRef: (request as BindModelProviderCredentialRequest)
.secretRef,
scheme: 'bearer',
}
: null,
changedBy: authority.principal.subject,
});
} catch (error) {
return mapMutationError(error);
}
try {
return await options.credentials.commitAuthorized({
command,
actor: authority.principal.subject,
fence: authority.decision.fence!,
audit: {
eventId: command.mutationId,
requestId: request.requestId,
operationId: modelProviderCredentialAdministrationOperationId(
command.action,
),
projectId: command.projectId,
subject: authority.principal.subject,
authenticationId: authority.principal.authenticationId,
outcome: 'allowed',
reasons: authority.decision.reasons,
fence: authority.decision.fence,
occurredAtMs: authority.observedAtMs,
},
});
} catch (error) {
return mapMutationError(error);
}
};
return Object.freeze({
async bind(request: Readonly<BindModelProviderCredentialRequest>) {
normalizeBaseRequest(request, [
'expectedGeneration',
'mutationId',
'principal',
'projectId',
'provider',
'requestId',
'revision',
'secretRef',
]);
if (
typeof request.revision !== 'string' ||
!IDENTITY_PATTERN.test(request.revision) ||
typeof request.secretRef !== 'string'
) {
throw new ClusterModelProviderCredentialManagementRequestError();
}
return commit(request, 'bind');
},
async revoke(request: Readonly<RevokeModelProviderCredentialRequest>) {
normalizeBaseRequest(request, [
'expectedGeneration',
'mutationId',
'principal',
'projectId',
'provider',
'requestId',
]);
return commit(request, 'revoke');
},
async listAudit(
request: Readonly<ListModelProviderCredentialManagementAuditRequest>,
) {
if (
!request ||
typeof request !== 'object' ||
Array.isArray(request) ||
!exactKeys(
request,
request.before === undefined
? ['limit', 'principal', 'projectId', 'queryId', 'requestId']
: [
'before',
'limit',
'principal',
'projectId',
'queryId',
'requestId',
],
)
) {
throw new ClusterModelProviderCredentialManagementRequestError();
}
let query;
try {
query = normalizeModelProviderCredentialManagementAuditQuery({
schemaVersion: 1,
queryId: request.queryId,
requestId: request.requestId,
projectId: request.projectId,
limit: request.limit,
...(request.before === undefined ? {} : { before: request.before }),
});
} catch {
throw new ClusterModelProviderCredentialManagementRequestError();
}
const authority = await authorize(request.principal, request.projectId);
try {
return await options.audit.listAuthorized({
query,
actor: authority.principal.subject,
fence: authority.decision.fence!,
audit: {
eventId: request.queryId,
requestId: request.requestId,
operationId:
MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_AUDIT_QUERY_OPERATION_ID,
projectId: request.projectId,
subject: authority.principal.subject,
authenticationId: authority.principal.authenticationId,
outcome: 'allowed',
reasons: authority.decision.reasons,
fence: authority.decision.fence,
occurredAtMs: authority.observedAtMs,
},
});
} catch (error) {
return mapAuditError(error);
}
},
async planTestConnection(
request: Readonly<PlanModelProviderCredentialTestRequest>,
) {
if (
!request ||
typeof request !== 'object' ||
Array.isArray(request) ||
!exactKeys(request, [
'principal',
'projectId',
'provider',
'requestId',
'testId',
]) ||
typeof request.requestId !== 'string' ||
!REQUEST_ID_PATTERN.test(request.requestId) ||
typeof request.testId !== 'string' ||
!UUID_PATTERN.test(request.testId) ||
typeof request.projectId !== 'string' ||
!IDENTITY_PATTERN.test(request.projectId) ||
typeof request.provider !== 'string' ||
!IDENTITY_PATTERN.test(request.provider)
) {
throw new ClusterModelProviderCredentialManagementRequestError();
}
const authority = await authorize(request.principal, request.projectId);
let plan;
try {
const endpoint = resolveModelProviderCredentialTestEndpoint(
testAllowlist,
request.provider,
);
if (
authority.observedAtMs >
Number.MAX_SAFE_INTEGER - testPlanLifetimeMs
) {
throw new ModelProviderCredentialTestPlanUnavailableError();
}
plan = createModelProviderCredentialTestPlan({
testId: request.testId,
requestId: request.requestId,
projectId: request.projectId,
provider: request.provider,
endpoint,
requestedBy: authority.principal.subject,
fence: authority.decision.fence!,
plannedAtMs: authority.observedAtMs,
expiresAtMs: authority.observedAtMs + testPlanLifetimeMs,
});
return await options.testPlans.createAuthorized({
plan,
audit: {
eventId: plan.testId,
requestId: plan.requestId,
operationId: MODEL_PROVIDER_CREDENTIAL_TEST_PLAN_OPERATION_ID,
projectId: plan.projectId,
subject: authority.principal.subject,
authenticationId: authority.principal.authenticationId,
outcome: 'allowed',
reasons: authority.decision.reasons,
fence: authority.decision.fence,
occurredAtMs: authority.observedAtMs,
},
});
} catch (error) {
return mapTestPlanError(error);
}
},
});
}
@@ -0,0 +1,105 @@
#!/usr/bin/env node
import {
startClusterModelProviderCredentialManagementProcess,
type ClusterModelProviderCredentialManagementProcessRuntime,
} from './modelProviderCredentialManagementProcess';
const USAGE = 'Usage: ql3-provider-credential-manage';
function failureFact(error: unknown): Readonly<Record<string, unknown>> {
const candidate = error as { readonly name?: unknown; readonly code?: unknown };
return Object.freeze({
schemaVersion: 1,
component: 'qinglong3-model-provider-credential-management',
event: 'management_failed',
name:
typeof candidate?.name === 'string' && candidate.name.length <= 128
? candidate.name
: 'Error',
...(typeof candidate?.code === 'string' && candidate.code.length <= 128
? { code: candidate.code }
: {}),
});
}
function emit(value: Readonly<Record<string, unknown>>): void {
process.stdout.write(`${JSON.stringify(value)}\n`);
}
async function run(argv: readonly string[]): Promise<void> {
if (argv.length === 1 && (argv[0] === '--help' || argv[0] === '-h')) {
process.stdout.write(`${USAGE}\n`);
return;
}
if (argv.length !== 0) {
process.stderr.write(
`${JSON.stringify({
code: 'QL3_MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_CLI_USAGE_INVALID',
message: USAGE,
})}\n`,
);
process.exitCode = 64;
return;
}
let runtime: Readonly<ClusterModelProviderCredentialManagementProcessRuntime>;
try {
runtime = await startClusterModelProviderCredentialManagementProcess({
environment: process.env,
onError() {
emit({
schemaVersion: 1,
component: 'qinglong3-model-provider-credential-management',
event: 'management_unavailable',
});
},
});
} catch (error) {
process.stderr.write(`${JSON.stringify(failureFact(error))}\n`);
process.exitCode = 1;
return;
}
if (runtime.status === 'disabled') {
emit({
schemaVersion: 1,
component: 'qinglong3-model-provider-credential-management',
event: 'management_disabled',
});
return;
}
emit({
schemaVersion: 1,
component: 'qinglong3-model-provider-credential-management',
event: 'management_started',
address: runtime.address,
identityGeneration: runtime.identity.generation,
databaseMigrationCount: runtime.database.migrationIds.length,
});
let stopping: Promise<void> | undefined;
const stop = (): Promise<void> => {
stopping ??= runtime.close().then(() => {
emit({
schemaVersion: 1,
component: 'qinglong3-model-provider-credential-management',
event: 'management_stopped',
});
});
return stopping;
};
for (const signal of ['SIGINT', 'SIGTERM'] as const) {
process.once(signal, () => {
void stop().then(
() => {
process.exitCode = 0;
},
(error) => {
process.stderr.write(`${JSON.stringify(failureFact(error))}\n`);
process.exitCode = 1;
},
);
});
}
}
void run(process.argv.slice(2));
@@ -0,0 +1,312 @@
import {
ClusterPluginPackageManagementClientRequestError,
executeClusterAuthenticatedManagementClient,
type ClusterAuthenticatedManagementClientResult,
type ClusterPluginPackageManagementClientConnectionOptions,
type ClusterPluginPackageManagementClientPaths,
} from '../management-support/pluginPackageManagementClient';
import {
normalizeClusterModelProviderCredentialManagementCommand,
type ClusterModelProviderCredentialManagementCommand,
} from './modelProviderCredentialManagementTransport';
import {
normalizeModelProviderCredentialTestPlan,
type ModelProviderCredentialTestPlan,
} from '@qinglong/ai/model-provider-credential-test-connection';
const MANAGEMENT_PATH = '/api/v3/provider-credentials/management';
const CONTROL_PATTERN = /[\u0000-\u001f\u007f]/;
const DIGEST_PATTERN = /^[0-9a-f]{64}$/;
const UUID_V4_PATTERN =
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
export type ClusterModelProviderCredentialManagementClientPaths =
ClusterPluginPackageManagementClientPaths;
export type ClusterModelProviderCredentialManagementClientConnectionOptions =
ClusterPluginPackageManagementClientConnectionOptions;
export type ClusterModelProviderCredentialManagementClientTransportResult =
| Readonly<{
schemaVersion: 1;
operation: 'provider-credential.bind' | 'provider-credential.revoke';
status: 'created' | 'existing';
credential: Readonly<{
projectId: string;
provider: string;
generation: number;
action: 'bind' | 'revoke';
activeBindingRevision: string | null;
activeBindingDigest: string | null;
transitionDigest: string;
changedAtMs: number;
}>;
}>
| Readonly<{
schemaVersion: 1;
operation: 'provider-credential.audit.list';
audit: Readonly<{
projectId: string;
records: readonly Readonly<{
eventId: string;
requestId: string;
operation: 'provider-credential.bind' | 'provider-credential.revoke';
actor: Readonly<{ type: 'user'; id: string }>;
fence: Readonly<{
projectVersion: number;
bindingVersion: number;
}>;
occurredAtMs: number;
}>[];
nextCursor: Readonly<{
occurredAtMs: number;
eventId: string;
}> | null;
}>;
}>
| Readonly<{
schemaVersion: 1;
operation: 'provider-credential.test.plan';
status: 'created' | 'existing';
plan: Readonly<ModelProviderCredentialTestPlan>;
}>;
export type ClusterModelProviderCredentialManagementClientResult =
ClusterAuthenticatedManagementClientResult<ClusterModelProviderCredentialManagementClientTransportResult>;
function invalid(): never {
throw new ClusterPluginPackageManagementClientRequestError();
}
function exactRecord(
value: unknown,
keys: readonly string[],
): Record<string, unknown> {
if (!value || typeof value !== 'object' || Array.isArray(value)) invalid();
const record = value as Record<string, unknown>;
const actual = Object.keys(record).sort();
const expected = [...keys].sort();
if (
actual.length !== expected.length ||
actual.some((key, index) => key !== expected[index])
) {
invalid();
}
return record;
}
function identifier(value: unknown): string {
if (
typeof value !== 'string' ||
value.length < 1 ||
value.length > 128 ||
CONTROL_PATTERN.test(value)
) {
invalid();
}
return value;
}
function digest(value: unknown): string {
if (typeof value !== 'string' || !DIGEST_PATTERN.test(value)) invalid();
return value;
}
function uuid(value: unknown): string {
if (typeof value !== 'string' || !UUID_V4_PATTERN.test(value)) invalid();
return value;
}
function positiveInteger(value: unknown): number {
if (!Number.isSafeInteger(value) || (value as number) < 1) invalid();
return value as number;
}
function nonNegativeInteger(value: unknown): number {
if (!Number.isSafeInteger(value) || (value as number) < 0) invalid();
return value as number;
}
export function validateClusterModelProviderCredentialManagementClientResult(
value: unknown,
command: Readonly<ClusterModelProviderCredentialManagementCommand>,
): Readonly<ClusterModelProviderCredentialManagementClientTransportResult> {
if (command.operation === 'provider-credential.test.plan') {
const envelope = exactRecord(value, [
'operation',
'plan',
'schemaVersion',
'status',
]);
if (
envelope.schemaVersion !== 1 ||
envelope.operation !== command.operation ||
(envelope.status !== 'created' && envelope.status !== 'existing')
) {
invalid();
}
let plan: Readonly<ModelProviderCredentialTestPlan>;
try {
plan = normalizeModelProviderCredentialTestPlan(
envelope.plan as ModelProviderCredentialTestPlan,
);
} catch {
return invalid();
}
if (
plan.testId !== command.request.testId ||
plan.requestId !== command.request.requestId ||
plan.projectId !== command.request.projectId ||
plan.provider !== command.request.provider
) {
invalid();
}
return Object.freeze({
schemaVersion: 1 as const,
operation: command.operation,
status: envelope.status,
plan,
});
}
if (command.operation === 'provider-credential.audit.list') {
const envelope = exactRecord(value, [
'schemaVersion',
'operation',
'audit',
]);
if (
envelope.schemaVersion !== 1 ||
envelope.operation !== command.operation
) {
invalid();
}
const audit = exactRecord(envelope.audit, [
'projectId',
'records',
'nextCursor',
]);
if (
identifier(audit.projectId) !== command.request.projectId ||
!Array.isArray(audit.records) ||
audit.records.length > command.request.limit
) {
invalid();
}
const records = audit.records.map((value) => {
const record = exactRecord(value, [
'actor',
'eventId',
'fence',
'occurredAtMs',
'operation',
'requestId',
]);
uuid(record.eventId);
identifier(record.requestId);
if (
record.operation !== 'provider-credential.bind' &&
record.operation !== 'provider-credential.revoke'
) {
invalid();
}
const actor = exactRecord(record.actor, ['id', 'type']);
if (actor.type !== 'user') invalid();
identifier(actor.id);
const fence = exactRecord(record.fence, [
'bindingVersion',
'projectVersion',
]);
positiveInteger(fence.projectVersion);
positiveInteger(fence.bindingVersion);
nonNegativeInteger(record.occurredAtMs);
return record;
});
if (audit.nextCursor !== null) {
const cursor = exactRecord(audit.nextCursor, ['eventId', 'occurredAtMs']);
uuid(cursor.eventId);
nonNegativeInteger(cursor.occurredAtMs);
const last = records.at(-1);
if (
records.length !== command.request.limit ||
!last ||
cursor.eventId !== last.eventId ||
cursor.occurredAtMs !== last.occurredAtMs
) {
invalid();
}
}
return Object.freeze(
envelope as unknown as ClusterModelProviderCredentialManagementClientTransportResult,
);
}
const envelope = exactRecord(value, [
'schemaVersion',
'operation',
'status',
'credential',
]);
if (
envelope.schemaVersion !== 1 ||
envelope.operation !== command.operation ||
!['created', 'existing'].includes(String(envelope.status))
) {
invalid();
}
const credential = exactRecord(envelope.credential, [
'projectId',
'provider',
'generation',
'action',
'activeBindingRevision',
'activeBindingDigest',
'transitionDigest',
'changedAtMs',
]);
const expectedAction =
command.operation === 'provider-credential.bind' ? 'bind' : 'revoke';
if (
identifier(credential.projectId) !== command.request.projectId ||
identifier(credential.provider) !== command.request.provider ||
!Number.isSafeInteger(credential.generation) ||
(credential.generation as number) < 1 ||
credential.action !== expectedAction ||
!Number.isSafeInteger(credential.changedAtMs) ||
(credential.changedAtMs as number) < 0
) {
invalid();
}
digest(credential.transitionDigest);
if (command.operation === 'provider-credential.bind') {
if (
identifier(credential.activeBindingRevision) !== command.request.revision
) {
invalid();
}
digest(credential.activeBindingDigest);
} else if (
credential.activeBindingRevision !== null ||
credential.activeBindingDigest !== null
) {
invalid();
}
return Object.freeze(
envelope as unknown as ClusterModelProviderCredentialManagementClientTransportResult,
);
}
const PROTOCOL = Object.freeze({
managementPath: MANAGEMENT_PATH,
clientCertificate: 'required' as const,
normalizeCommand: normalizeClusterModelProviderCredentialManagementCommand,
validateResult: validateClusterModelProviderCredentialManagementClientResult,
});
export async function executeClusterModelProviderCredentialManagementClient(
paths: ClusterModelProviderCredentialManagementClientPaths,
connectionOptions?: ClusterModelProviderCredentialManagementClientConnectionOptions,
): Promise<Readonly<ClusterModelProviderCredentialManagementClientResult>> {
return executeClusterAuthenticatedManagementClient(
paths,
PROTOCOL,
connectionOptions,
);
}
@@ -0,0 +1,96 @@
#!/usr/bin/env node
import { executeClusterModelProviderCredentialManagementClient } from './modelProviderCredentialManagementClient';
import { ClusterPluginPackageManagementClientRemoteError } from '../management-support/pluginPackageManagementClient';
const USAGE =
'Usage: ql3-provider-credential-client --config=/absolute/client.json --command=/absolute/command.json --assertion=/absolute/assertion.jwt';
function parseArguments(
argv: readonly string[],
): Readonly<{
configFile: string;
commandFile: string;
assertionFile: string;
}> | null {
if (argv.length !== 3) return null;
const values = new Map<string, string>();
for (const argument of argv) {
const match = /^--(config|command|assertion)=(\/.+)$/.exec(argument);
if (!match || values.has(match[1]!)) return null;
values.set(match[1]!, match[2]!);
}
if (
!values.has('config') ||
!values.has('command') ||
!values.has('assertion')
) {
return null;
}
return Object.freeze({
configFile: values.get('config')!,
commandFile: values.get('command')!,
assertionFile: values.get('assertion')!,
});
}
function failureFact(error: unknown): Readonly<Record<string, unknown>> {
const candidate = error as { readonly code?: unknown };
return Object.freeze({
schemaVersion: 1,
component: 'qinglong3-model-provider-credential-management-client',
event: 'command_failed',
code:
typeof candidate?.code === 'string' && candidate.code.length <= 128
? candidate.code
: 'QL3_MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_CLIENT_FAILED',
...(error instanceof ClusterPluginPackageManagementClientRemoteError
? {
statusCode: error.statusCode,
responseCode: error.responseCode,
requestId: error.requestId,
...(error.retryAfterSeconds === null
? {}
: { retryAfterSeconds: error.retryAfterSeconds }),
}
: {}),
});
}
async function run(argv: readonly string[]): Promise<void> {
if (argv.length === 1 && (argv[0] === '--help' || argv[0] === '-h')) {
process.stdout.write(`${USAGE}\n`);
return;
}
const paths = parseArguments(argv);
if (!paths) {
process.stderr.write(
`${JSON.stringify({
schemaVersion: 1,
component: 'qinglong3-model-provider-credential-management-client',
event: 'usage_invalid',
code: 'QL3_MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_CLIENT_USAGE_INVALID',
})}\n`,
);
process.exitCode = 64;
return;
}
try {
const result =
await executeClusterModelProviderCredentialManagementClient(paths);
process.stdout.write(
`${JSON.stringify({
schemaVersion: 1,
component: 'qinglong3-model-provider-credential-management-client',
event: 'command_completed',
requestId: result.requestId,
result: result.result,
})}\n`,
);
} catch (error) {
process.stderr.write(`${JSON.stringify(failureFact(error))}\n`);
process.exitCode = 1;
}
}
void run(process.argv.slice(2));
@@ -0,0 +1,24 @@
import {
CLUSTER_MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_PATH,
startClusterPluginPackageManagementHttp,
type ClusterPluginPackageManagementHttpApplication,
type StartClusterPluginPackageManagementHttpOptions,
} from '../management-support/pluginPackageManagementHttp';
export type ClusterModelProviderCredentialManagementHttpApplication =
ClusterPluginPackageManagementHttpApplication;
export type StartClusterModelProviderCredentialManagementHttpOptions = Omit<
StartClusterPluginPackageManagementHttpOptions,
'managementPath'
>;
/** Starts the bounded OIDC/mTLS adapter on the provider-credential-only path. */
export function startClusterModelProviderCredentialManagementHttp(
options: StartClusterModelProviderCredentialManagementHttpOptions,
): Promise<Readonly<ClusterModelProviderCredentialManagementHttpApplication>> {
return startClusterPluginPackageManagementHttp({
...options,
managementPath: CLUSTER_MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_PATH,
});
}
@@ -0,0 +1,685 @@
import type {
OpenPostgresDatabase,
PostgresDatabaseResource,
} from '@qinglong/runtime-core';
import { ProjectPolicyEngine } from '@qinglong/runtime-core/project-policy';
import {
PostgresProjectPolicyRepository,
createPostgresDatabaseOpener,
isPostgresTlsDnsServername,
loadPostgresCertificateAuthorityFile,
loadPostgresConnectionEnvironment,
type PostgresConnectionOptions,
type PostgresPoolOptions,
} from '@qinglong/cluster-postgres/ai-credential-manager';
import { PostgresModelProviderCredentialRepository } from '@qinglong/ai/postgres-model-provider-credential-storage';
import { PostgresModelProviderCredentialManagementAuditQueryRepository } from '@qinglong/ai/postgres-model-provider-credential-management-audit-query';
import {
PostgresModelProviderCredentialManagementIdentityLedgerRepository,
assertPostgresModelProviderCredentialManagerReady,
type PostgresModelProviderCredentialManagerReadinessReport,
} from '@qinglong/ai/postgres-model-provider-credential-management-identity-ledger';
import {
MAX_MODEL_PROVIDER_CREDENTIAL_TEST_PLAN_LIFETIME_MS,
normalizeModelProviderCredentialTestAllowlist,
type ModelProviderCredentialTestAllowlist,
} from '@qinglong/ai/model-provider-credential-test-connection';
import { PostgresModelProviderCredentialTestPlanRepository } from '@qinglong/ai/postgres-model-provider-credential-test-connection';
import {
absoluteManagementEnvironmentFile,
booleanManagementEnvironmentValue,
boundedManagementEnvironmentValue,
integerManagementEnvironmentValue,
readManagementTlsFile,
} from '../management-support/managementProcessSupport';
import {
createClusterModelProviderCredentialIdentityKeysetFile,
type ClusterPluginPackageIdentityKeysetFile,
type ClusterPluginPackageIdentityKeysetSnapshot,
} from '../management-support/pluginPackageIdentityKeyset';
import { createClusterModelProviderCredentialManagementService } from './modelProviderCredentialManagement';
import {
startClusterModelProviderCredentialManagementHttp,
type ClusterModelProviderCredentialManagementHttpApplication,
type StartClusterModelProviderCredentialManagementHttpOptions,
} from './modelProviderCredentialManagementHttp';
import { createClusterModelProviderCredentialManagementTransport } from './modelProviderCredentialManagementTransport';
import { validateClusterManagementClientTrust } from '../worker-credential/management-server/workerCredentialManagementMutualTls';
const SAFE_HOST = /^[A-Za-z0-9][A-Za-z0-9.:-]{0,254}$/;
const SAFE_APPLICATION_NAME = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,62}$/;
export type ClusterModelProviderCredentialManagementProcessEnvironment =
Readonly<Record<string, string | undefined>>;
export type ClusterModelProviderCredentialManagementProcessConfig =
| Readonly<{ enabled: false }>
| Readonly<{
enabled: true;
profile: 'cluster-admin';
host: string;
port: number;
certificateFile: string;
privateKeyFile: string;
clientCertificateAuthorityFile: string;
clientCertificateRevocationListFile: string;
identityKeysetFile: string;
testConnection: Readonly<{
allowlistFile: string;
planLifetimeMs: number;
quotaWindowMs: number;
quotaLimit: number;
}>;
http: Readonly<{
maxBodyBytes: number;
maxConnections: number;
maxConcurrentRequests: number;
requestTimeoutMs: number;
drainTimeoutMs: number;
rateWindowMs: number;
peerRequestLimit: number;
globalRequestLimit: number;
maxRateLimitPeers: number;
}>;
database: Readonly<{
connection: PostgresConnectionOptions;
pool: PostgresPoolOptions;
}>;
}>;
export type ClusterModelProviderCredentialManagementProcessRuntime =
| Readonly<{
status: 'disabled';
close(): Promise<void>;
}>
| Readonly<{
status: 'active';
address: Readonly<{ host: string; port: number }>;
database: PostgresModelProviderCredentialManagerReadinessReport;
identity: ClusterPluginPackageIdentityKeysetSnapshot;
availabilityStatus(): 'ready' | 'unavailable' | 'stopped';
close(): Promise<void>;
}>;
export interface StartClusterModelProviderCredentialManagementProcessOptions {
readonly environment: ClusterModelProviderCredentialManagementProcessEnvironment;
readonly openDatabase?: OpenPostgresDatabase;
readonly identities?: ClusterPluginPackageIdentityKeysetFile;
readonly assertReady?: (
pool: PostgresDatabaseResource['pool'],
) => Promise<PostgresModelProviderCredentialManagerReadinessReport>;
readonly startHttp?: (
options: StartClusterModelProviderCredentialManagementHttpOptions,
) => Promise<
Readonly<ClusterModelProviderCredentialManagementHttpApplication>
>;
readonly now?: () => number;
readonly onError?: (error: unknown) => void;
}
export class ClusterModelProviderCredentialManagementProcessConfigError extends TypeError {
readonly code =
'QL3_MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_PROCESS_CONFIG_INVALID';
constructor(message: string) {
super(
`Model provider credential management process configuration is invalid: ${message}`,
);
this.name = 'ClusterModelProviderCredentialManagementProcessConfigError';
}
}
function configFailure(
message: string,
): ClusterModelProviderCredentialManagementProcessConfigError {
return new ClusterModelProviderCredentialManagementProcessConfigError(
message,
);
}
function boundedValue(
environment: ClusterModelProviderCredentialManagementProcessEnvironment,
name: string,
maximumLength: number,
): string | undefined {
return boundedManagementEnvironmentValue(
environment,
name,
maximumLength,
configFailure,
);
}
function booleanValue(
environment: ClusterModelProviderCredentialManagementProcessEnvironment,
name: string,
): boolean {
return booleanManagementEnvironmentValue(environment, name, configFailure);
}
function integerValue(
environment: ClusterModelProviderCredentialManagementProcessEnvironment,
name: string,
fallback: number,
minimum: number,
maximum: number,
): number {
return integerManagementEnvironmentValue(
environment,
name,
fallback,
minimum,
maximum,
configFailure,
);
}
function absoluteFile(
environment: ClusterModelProviderCredentialManagementProcessEnvironment,
name: string,
): string {
return absoluteManagementEnvironmentFile(environment, name, configFailure);
}
function loadConnection(
environment: ClusterModelProviderCredentialManagementProcessEnvironment,
): Readonly<{
connection: PostgresConnectionOptions;
pool: PostgresPoolOptions;
}> {
let connection: PostgresConnectionOptions;
try {
connection = loadPostgresConnectionEnvironment(environment, {
connectionString: 'QL3_POSTGRES_AI_CREDENTIAL_MANAGER_URL',
host: 'QL3_POSTGRES_AI_CREDENTIAL_MANAGER_HOST',
port: 'QL3_POSTGRES_AI_CREDENTIAL_MANAGER_PORT',
database: 'QL3_POSTGRES_AI_CREDENTIAL_MANAGER_DATABASE',
user: 'QL3_POSTGRES_AI_CREDENTIAL_MANAGER_USER',
password: 'QL3_POSTGRES_AI_CREDENTIAL_MANAGER_PASSWORD',
});
} catch (error) {
throw configFailure(
error instanceof Error
? error.message
: 'PostgreSQL AI credential manager connection is invalid',
);
}
const mode =
environment.QL3_POSTGRES_AI_CREDENTIAL_MANAGER_TLS_MODE ?? 'verify-full';
if (mode !== 'verify-full' && mode !== 'disable') {
throw configFailure(
'QL3_POSTGRES_AI_CREDENTIAL_MANAGER_TLS_MODE must be verify-full or disable',
);
}
if (
mode === 'disable' &&
!booleanValue(
environment,
'QL3_POSTGRES_AI_CREDENTIAL_MANAGER_ALLOW_INSECURE',
)
) {
throw configFailure(
'disabling AI credential manager PostgreSQL TLS requires QL3_POSTGRES_AI_CREDENTIAL_MANAGER_ALLOW_INSECURE=true',
);
}
const servername = boundedValue(
environment,
'QL3_POSTGRES_AI_CREDENTIAL_MANAGER_TLS_SERVERNAME',
253,
);
if (mode === 'verify-full' && !isPostgresTlsDnsServername(servername)) {
throw configFailure(
'QL3_POSTGRES_AI_CREDENTIAL_MANAGER_TLS_SERVERNAME must be an explicit DNS name',
);
}
const caFile = boundedValue(
environment,
'QL3_POSTGRES_AI_CREDENTIAL_MANAGER_TLS_CA_FILE',
4_096,
);
if (mode === 'disable' && caFile !== undefined) {
throw configFailure(
'QL3_POSTGRES_AI_CREDENTIAL_MANAGER_TLS_CA_FILE cannot be used when TLS is disabled',
);
}
let ca: string | undefined;
if (caFile !== undefined) {
try {
ca = loadPostgresCertificateAuthorityFile(caFile);
} catch {
throw configFailure(
'QL3_POSTGRES_AI_CREDENTIAL_MANAGER_TLS_CA_FILE is invalid',
);
}
}
const applicationName =
boundedValue(
environment,
'QL3_POSTGRES_AI_CREDENTIAL_MANAGER_APPLICATION_NAME',
63,
) ?? 'qinglong3-ai-credential-manager';
if (!SAFE_APPLICATION_NAME.test(applicationName)) {
throw configFailure(
'QL3_POSTGRES_AI_CREDENTIAL_MANAGER_APPLICATION_NAME is invalid',
);
}
return Object.freeze({
connection: Object.freeze({
...connection,
tls:
mode === 'disable'
? Object.freeze({ mode: 'disable' as const })
: Object.freeze({
mode: 'verify-full' as const,
servername: servername!,
...(ca === undefined ? {} : { ca }),
}),
}),
pool: Object.freeze({
applicationName,
maxConnections: integerValue(
environment,
'QL3_POSTGRES_AI_CREDENTIAL_MANAGER_POOL_MAX',
2,
1,
2,
),
idleTimeoutMs: integerValue(
environment,
'QL3_POSTGRES_AI_CREDENTIAL_MANAGER_IDLE_TIMEOUT_MS',
10_000,
1_000,
60_000,
),
connectionTimeoutMs: integerValue(
environment,
'QL3_POSTGRES_AI_CREDENTIAL_MANAGER_CONNECTION_TIMEOUT_MS',
5_000,
100,
60_000,
),
}),
});
}
export function loadClusterModelProviderCredentialManagementProcessConfig(
environment: ClusterModelProviderCredentialManagementProcessEnvironment,
): Readonly<ClusterModelProviderCredentialManagementProcessConfig> {
if (!environment || typeof environment !== 'object') {
throw configFailure('environment is invalid');
}
if (
!booleanValue(
environment,
'QL3_MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_ENABLED',
)
) {
return Object.freeze({ enabled: false as const });
}
if (environment.QL3_PROFILE !== 'cluster-admin') {
throw configFailure(
'QL3_PROFILE must be cluster-admin when model provider credential management is enabled',
);
}
const host =
boundedValue(
environment,
'QL3_MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_HOST',
255,
) ?? '0.0.0.0';
if (!SAFE_HOST.test(host)) throw configFailure('host is invalid');
const http = Object.freeze({
maxBodyBytes: integerValue(
environment,
'QL3_MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_MAX_BODY_BYTES',
32 * 1024,
1_024,
64 * 1024,
),
maxConnections: integerValue(
environment,
'QL3_MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_MAX_CONNECTIONS',
32,
1,
128,
),
maxConcurrentRequests: integerValue(
environment,
'QL3_MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_MAX_CONCURRENT_REQUESTS',
8,
1,
32,
),
requestTimeoutMs: integerValue(
environment,
'QL3_MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_REQUEST_TIMEOUT_MS',
10_000,
1_000,
30_000,
),
drainTimeoutMs: integerValue(
environment,
'QL3_MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_DRAIN_TIMEOUT_MS',
5_000,
100,
30_000,
),
rateWindowMs: integerValue(
environment,
'QL3_MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_RATE_WINDOW_MS',
60_000,
1_000,
5 * 60_000,
),
peerRequestLimit: integerValue(
environment,
'QL3_MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_PEER_REQUEST_LIMIT',
30,
1,
1_000,
),
globalRequestLimit: integerValue(
environment,
'QL3_MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_GLOBAL_REQUEST_LIMIT',
120,
1,
10_000,
),
maxRateLimitPeers: integerValue(
environment,
'QL3_MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_MAX_RATE_LIMIT_PEERS',
256,
1,
4_096,
),
});
if (http.globalRequestLimit < http.peerRequestLimit) {
throw configFailure(
'global request limit cannot be below the peer request limit',
);
}
return Object.freeze({
enabled: true as const,
profile: 'cluster-admin' as const,
host,
port: integerValue(
environment,
'QL3_MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_PORT',
8_446,
1,
65_535,
),
certificateFile: absoluteFile(
environment,
'QL3_MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_TLS_CERT_FILE',
),
privateKeyFile: absoluteFile(
environment,
'QL3_MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_TLS_KEY_FILE',
),
clientCertificateAuthorityFile: absoluteFile(
environment,
'QL3_MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_CLIENT_CA_FILE',
),
clientCertificateRevocationListFile: absoluteFile(
environment,
'QL3_MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_CLIENT_CRL_FILE',
),
identityKeysetFile: absoluteFile(
environment,
'QL3_MODEL_PROVIDER_CREDENTIAL_MANAGEMENT_IDENTITY_KEYSET_FILE',
),
testConnection: Object.freeze({
allowlistFile: absoluteFile(
environment,
'QL3_MODEL_PROVIDER_CREDENTIAL_TEST_ALLOWLIST_FILE',
),
planLifetimeMs: integerValue(
environment,
'QL3_MODEL_PROVIDER_CREDENTIAL_TEST_PLAN_LIFETIME_MS',
60_000,
1_000,
MAX_MODEL_PROVIDER_CREDENTIAL_TEST_PLAN_LIFETIME_MS,
),
quotaWindowMs: integerValue(
environment,
'QL3_MODEL_PROVIDER_CREDENTIAL_TEST_QUOTA_WINDOW_MS',
60_000,
1_000,
5 * 60_000,
),
quotaLimit: integerValue(
environment,
'QL3_MODEL_PROVIDER_CREDENTIAL_TEST_QUOTA_LIMIT',
5,
1,
32,
),
}),
http,
database: loadConnection(environment),
});
}
function readTlsFile(filePath: string, privateMaterial: boolean): Buffer {
return readManagementTlsFile(filePath, privateMaterial, configFailure);
}
function readTestAllowlist(
filePath: string,
): Readonly<ModelProviderCredentialTestAllowlist> {
const bytes = readManagementTlsFile(filePath, false, configFailure);
try {
if (bytes.length > 64 * 1_024) {
throw configFailure(
'model provider credential test allowlist is too large',
);
}
return normalizeModelProviderCredentialTestAllowlist(
JSON.parse(
bytes.toString('utf8'),
) as ModelProviderCredentialTestAllowlist,
);
} catch (error) {
if (
error instanceof
ClusterModelProviderCredentialManagementProcessConfigError
) {
throw error;
}
throw configFailure('model provider credential test allowlist is invalid');
}
}
export async function startClusterModelProviderCredentialManagementProcess(
options: StartClusterModelProviderCredentialManagementProcessOptions,
): Promise<Readonly<ClusterModelProviderCredentialManagementProcessRuntime>> {
if (
!options ||
typeof options !== 'object' ||
Array.isArray(options) ||
Object.keys(options).some(
(key) =>
![
'environment',
'openDatabase',
'identities',
'assertReady',
'startHttp',
'now',
'onError',
].includes(key),
) ||
!options.environment ||
typeof options.environment !== 'object' ||
(options.openDatabase !== undefined &&
typeof options.openDatabase !== 'function') ||
(options.identities !== undefined &&
(typeof options.identities.reload !== 'function' ||
typeof options.identities.bind !== 'function')) ||
(options.assertReady !== undefined &&
typeof options.assertReady !== 'function') ||
(options.startHttp !== undefined &&
typeof options.startHttp !== 'function') ||
(options.now !== undefined && typeof options.now !== 'function') ||
(options.onError !== undefined && typeof options.onError !== 'function')
) {
throw configFailure('options are invalid');
}
const config = loadClusterModelProviderCredentialManagementProcessConfig(
options.environment,
);
if (!config.enabled) {
return Object.freeze({
status: 'disabled' as const,
close: () => Promise.resolve(),
});
}
const now = options.now ?? Date.now;
let http:
| Readonly<ClusterModelProviderCredentialManagementHttpApplication>
| undefined;
let database: PostgresDatabaseResource | undefined;
let unavailableError: unknown;
let closePromise: Promise<void> | undefined;
const report = (error: unknown): void => {
try {
options.onError?.(error);
} catch {
// Diagnostics do not own availability or cleanup.
}
};
const openDatabase =
options.openDatabase ??
createPostgresDatabaseOpener({
role: 'ai-credential-manager',
connection: config.database.connection,
pool: config.database.pool,
onPoolError(error) {
const firstAvailabilityError = unavailableError === undefined;
unavailableError ??= error;
http?.withdraw(error);
if (firstAvailabilityError) report(error);
},
});
try {
database = await openDatabase();
const evidence = await (
options.assertReady ?? assertPostgresModelProviderCredentialManagerReady
)(database.pool);
if (unavailableError !== undefined) throw unavailableError;
const identities =
options.identities ??
createClusterModelProviderCredentialIdentityKeysetFile({
filePath: config.identityKeysetFile,
now,
ledger:
new PostgresModelProviderCredentialManagementIdentityLedgerRepository(
database.pool,
),
});
const identity = await identities.reload();
const testAllowlist = readTestAllowlist(
config.testConnection.allowlistFile,
);
const service = createClusterModelProviderCredentialManagementService({
policy: new ProjectPolicyEngine(
new PostgresProjectPolicyRepository(database.pool),
),
credentials: new PostgresModelProviderCredentialRepository(database.pool),
audit: new PostgresModelProviderCredentialManagementAuditQueryRepository(
database.pool,
),
testPlans: new PostgresModelProviderCredentialTestPlanRepository(
database.pool,
{
quotaWindowMs: config.testConnection.quotaWindowMs,
quotaLimit: config.testConnection.quotaLimit,
},
),
testAllowlist,
testPlanLifetimeMs: config.testConnection.planLifetimeMs,
now,
});
const transport = createClusterModelProviderCredentialManagementTransport({
service,
now,
});
const privateKey = readTlsFile(config.privateKeyFile, true);
try {
const certificate = readTlsFile(config.certificateFile, false);
const clientCertificateAuthority = readTlsFile(
config.clientCertificateAuthorityFile,
false,
);
const clientCertificateRevocationList = readTlsFile(
config.clientCertificateRevocationListFile,
false,
);
validateClusterManagementClientTrust(
clientCertificateAuthority,
clientCertificateRevocationList,
now(),
configFailure,
);
http = await (
options.startHttp ?? startClusterModelProviderCredentialManagementHttp
)({
host: config.host,
port: config.port,
tls: {
privateKey,
certificate,
clientCertificateAuthority,
clientCertificateRevocationList,
},
transport,
identities,
limits: config.http,
now,
onError: report,
});
} finally {
privateKey.fill(0);
}
if (unavailableError !== undefined) http.withdraw(unavailableError);
return Object.freeze({
status: 'active' as const,
address: http.address,
database: evidence,
identity,
availabilityStatus: () => http?.availabilityStatus() ?? 'stopped',
close(): Promise<void> {
if (closePromise) return closePromise;
closePromise = (async () => {
let primaryError: unknown;
try {
await http?.close();
} catch (error) {
primaryError = error;
}
try {
await database?.close();
} catch (error) {
primaryError ??= error;
}
if (primaryError) throw primaryError;
})();
return closePromise;
},
});
} catch (error) {
try {
await http?.close();
} catch {
// Preserve startup failure.
}
try {
await database?.close();
} catch {
// Preserve startup failure.
}
throw error;
}
}
@@ -0,0 +1,357 @@
import {
normalizeSecurityPrincipal,
type SecurityPrincipal,
} from '@qinglong/runtime-core/security';
import type { ModelProviderCredentialTestPlan } from '@qinglong/ai/model-provider-credential-test-connection';
import type {
BindModelProviderCredentialRequest,
ClusterModelProviderCredentialManagementService,
ListModelProviderCredentialManagementAuditRequest,
PlanModelProviderCredentialTestRequest,
RevokeModelProviderCredentialRequest,
} from './modelProviderCredentialManagement';
const STRONG_CLUSTER_ASSURANCES = new Set(['multi_factor', 'hardware']);
const MAX_PRINCIPAL_AGE_MS = 5 * 60 * 1_000;
interface BindTransportRequest
extends Omit<BindModelProviderCredentialRequest, 'principal'> {}
interface RevokeTransportRequest
extends Omit<RevokeModelProviderCredentialRequest, 'principal'> {}
interface AuditTransportRequest
extends Omit<
ListModelProviderCredentialManagementAuditRequest,
'principal'
> {}
interface TestPlanTransportRequest
extends Omit<PlanModelProviderCredentialTestRequest, 'principal'> {}
export type ClusterModelProviderCredentialManagementCommand =
| Readonly<{
schemaVersion: 1;
operation: 'provider-credential.bind';
request: BindTransportRequest;
}>
| Readonly<{
schemaVersion: 1;
operation: 'provider-credential.revoke';
request: RevokeTransportRequest;
}>
| Readonly<{
schemaVersion: 1;
operation: 'provider-credential.audit.list';
request: AuditTransportRequest;
}>
| Readonly<{
schemaVersion: 1;
operation: 'provider-credential.test.plan';
request: TestPlanTransportRequest;
}>;
export interface ClusterModelProviderCredentialManagementAuthentication {
authenticate(): Promise<Readonly<SecurityPrincipal> | null>;
}
export interface ClusterModelProviderCredentialManagementTransport {
execute(
command: unknown,
authentication: ClusterModelProviderCredentialManagementAuthentication,
): Promise<Readonly<ClusterModelProviderCredentialManagementTransportResult>>;
}
export type ClusterModelProviderCredentialManagementTransportResult =
| Readonly<{
schemaVersion: 1;
operation: 'provider-credential.bind' | 'provider-credential.revoke';
status: 'created' | 'existing';
credential: Readonly<{
projectId: string;
provider: string;
generation: number;
action: 'bind' | 'revoke';
activeBindingRevision: string | null;
activeBindingDigest: string | null;
transitionDigest: string;
changedAtMs: number;
}>;
}>
| Readonly<{
schemaVersion: 1;
operation: 'provider-credential.audit.list';
audit: Readonly<{
projectId: string;
records: readonly Readonly<{
eventId: string;
requestId: string;
operation: 'provider-credential.bind' | 'provider-credential.revoke';
actor: Readonly<{ type: 'user'; id: string }>;
fence: Readonly<{
projectVersion: number;
bindingVersion: number;
}>;
occurredAtMs: number;
}>[];
nextCursor: Readonly<{
occurredAtMs: number;
eventId: string;
}> | null;
}>;
}>
| Readonly<{
schemaVersion: 1;
operation: 'provider-credential.test.plan';
status: 'created' | 'existing';
plan: Readonly<ModelProviderCredentialTestPlan>;
}>;
export class ClusterModelProviderCredentialManagementTransportConfigurationError extends TypeError {
readonly code =
'CLUSTER_MODEL_PROVIDER_CREDENTIAL_TRANSPORT_CONFIGURATION_INVALID';
constructor() {
super(
'Cluster model provider credential transport configuration is invalid',
);
this.name =
'ClusterModelProviderCredentialManagementTransportConfigurationError';
}
}
export class ClusterModelProviderCredentialManagementTransportRequestError extends TypeError {
readonly code = 'CLUSTER_MODEL_PROVIDER_CREDENTIAL_TRANSPORT_REQUEST_INVALID';
constructor() {
super('Cluster model provider credential transport request is invalid');
this.name = 'ClusterModelProviderCredentialManagementTransportRequestError';
}
}
export class ClusterModelProviderCredentialManagementTransportAuthenticationError extends Error {
readonly code =
'CLUSTER_MODEL_PROVIDER_CREDENTIAL_TRANSPORT_AUTHENTICATION_REQUIRED';
constructor() {
super(
'Cluster model provider credential transport requires a recent strong User',
);
this.name =
'ClusterModelProviderCredentialManagementTransportAuthenticationError';
}
}
export class ClusterModelProviderCredentialManagementTransportUnavailableError extends Error {
readonly code = 'CLUSTER_MODEL_PROVIDER_CREDENTIAL_TRANSPORT_UNAVAILABLE';
constructor() {
super('Cluster model provider credential transport is unavailable');
this.name =
'ClusterModelProviderCredentialManagementTransportUnavailableError';
}
}
function exactKeys(value: object, expected: readonly string[]): boolean {
const actual = Object.keys(value).sort();
const canonical = [...expected].sort();
return (
actual.length === canonical.length &&
actual.every((key, index) => key === canonical[index])
);
}
function normalizeCommand(
value: unknown,
): Readonly<ClusterModelProviderCredentialManagementCommand> {
if (
!value ||
typeof value !== 'object' ||
Array.isArray(value) ||
!exactKeys(value, ['operation', 'request', 'schemaVersion']) ||
(value as { schemaVersion?: unknown }).schemaVersion !== 1 ||
((value as { operation?: unknown }).operation !==
'provider-credential.bind' &&
(value as { operation?: unknown }).operation !==
'provider-credential.revoke' &&
(value as { operation?: unknown }).operation !==
'provider-credential.audit.list' &&
(value as { operation?: unknown }).operation !==
'provider-credential.test.plan') ||
!(value as { request?: unknown }).request ||
typeof (value as { request: unknown }).request !== 'object' ||
Array.isArray((value as { request: unknown }).request)
) {
throw new ClusterModelProviderCredentialManagementTransportRequestError();
}
const command = value as ClusterModelProviderCredentialManagementCommand;
const common = [
'expectedGeneration',
'mutationId',
'projectId',
'provider',
'requestId',
];
if (command.operation === 'provider-credential.audit.list') {
const auditKeys = ['limit', 'projectId', 'queryId', 'requestId'];
if ('before' in command.request) auditKeys.push('before');
if (!exactKeys(command.request, auditKeys)) {
throw new ClusterModelProviderCredentialManagementTransportRequestError();
}
return command;
}
if (command.operation === 'provider-credential.test.plan') {
if (
!exactKeys(command.request, [
'projectId',
'provider',
'requestId',
'testId',
])
) {
throw new ClusterModelProviderCredentialManagementTransportRequestError();
}
return command;
}
if (
!exactKeys(
command.request,
command.operation === 'provider-credential.bind'
? [...common, 'revision', 'secretRef']
: common,
)
) {
throw new ClusterModelProviderCredentialManagementTransportRequestError();
}
return command;
}
export function normalizeClusterModelProviderCredentialManagementCommand(
value: unknown,
): Readonly<ClusterModelProviderCredentialManagementCommand> {
return normalizeCommand(value);
}
function summary(
transition: Readonly<{
projectId: string;
provider: string;
generation: number;
action: 'bind' | 'revoke';
activeBindingRevision: string | null;
activeBindingDigest: string | null;
transitionDigest: string;
changedAtMs: number;
}>,
) {
return Object.freeze({
projectId: transition.projectId,
provider: transition.provider,
generation: transition.generation,
action: transition.action,
activeBindingRevision: transition.activeBindingRevision,
activeBindingDigest: transition.activeBindingDigest,
transitionDigest: transition.transitionDigest,
changedAtMs: transition.changedAtMs,
});
}
export function createClusterModelProviderCredentialManagementTransport(
options: Readonly<{
service: ClusterModelProviderCredentialManagementService;
now?: () => number;
}>,
): Readonly<ClusterModelProviderCredentialManagementTransport> {
if (
!options ||
typeof options !== 'object' ||
Array.isArray(options) ||
Object.keys(options).some((key) => key !== 'service' && key !== 'now') ||
!options.service ||
typeof options.service.bind !== 'function' ||
typeof options.service.revoke !== 'function' ||
typeof options.service.listAudit !== 'function' ||
typeof options.service.planTestConnection !== 'function' ||
(options.now !== undefined && typeof options.now !== 'function')
) {
throw new ClusterModelProviderCredentialManagementTransportConfigurationError();
}
const now = options.now ?? Date.now;
return Object.freeze({
async execute(
commandValue: unknown,
authentication: ClusterModelProviderCredentialManagementAuthentication,
) {
const command = normalizeCommand(commandValue);
if (
!authentication ||
typeof authentication !== 'object' ||
Array.isArray(authentication) ||
!exactKeys(authentication, ['authenticate']) ||
typeof authentication.authenticate !== 'function'
) {
throw new ClusterModelProviderCredentialManagementTransportConfigurationError();
}
const observedAtMs = now();
if (!Number.isSafeInteger(observedAtMs) || observedAtMs < 0) {
throw new ClusterModelProviderCredentialManagementTransportUnavailableError();
}
let candidate: Readonly<SecurityPrincipal> | null;
try {
candidate = await authentication.authenticate();
} catch {
throw new ClusterModelProviderCredentialManagementTransportUnavailableError();
}
let principal: Readonly<SecurityPrincipal>;
try {
principal = normalizeSecurityPrincipal(
candidate as SecurityPrincipal,
observedAtMs,
);
} catch {
throw new ClusterModelProviderCredentialManagementTransportAuthenticationError();
}
if (
principal.subject.type !== 'user' ||
!STRONG_CLUSTER_ASSURANCES.has(principal.assurance) ||
observedAtMs - principal.authenticatedAtMs > MAX_PRINCIPAL_AGE_MS
) {
throw new ClusterModelProviderCredentialManagementTransportAuthenticationError();
}
if (command.operation === 'provider-credential.audit.list') {
const audit = await options.service.listAudit({
...command.request,
principal,
});
return Object.freeze({
schemaVersion: 1 as const,
operation: command.operation,
audit,
});
}
if (command.operation === 'provider-credential.test.plan') {
const result = await options.service.planTestConnection({
...command.request,
principal,
});
return Object.freeze({
schemaVersion: 1 as const,
operation: command.operation,
status: result.status,
plan: result.plan,
});
}
const result =
command.operation === 'provider-credential.bind'
? await options.service.bind({ ...command.request, principal })
: await options.service.revoke({ ...command.request, principal });
return Object.freeze({
schemaVersion: 1 as const,
operation: command.operation,
status: result.status,
credential: summary(result.transition),
});
},
});
}
@@ -0,0 +1,255 @@
import { performance } from 'node:perf_hooks';
/** One-shot model-provider credential connectivity executor. */
import {
createModelProviderCredentialTestResult,
type ModelProviderCredentialTestAllowlist,
type ModelProviderCredentialTestExecution,
type ModelProviderCredentialTestPlan,
type ModelProviderCredentialTestResult,
} from '@qinglong/ai/model-provider-credential-test-connection';
import {
ModelProviderCredentialTestExecutionUnavailableError,
type BeginModelProviderCredentialTestExecutionInput,
type ModelProviderCredentialTestExecutionRepository,
} from '@qinglong/ai/postgres-model-provider-credential-test-connection';
import { OpenAiCompatibleProvider } from '@qinglong/ai/openai-compatible';
import {
BoundModelProviderCredentialProvider,
type ModelProviderCredentialAuditSink,
type ModelProviderCredentialBindingSource,
type ModelProviderSecretMaterialProvider,
} from '@qinglong/ai/provider-credential';
export interface ExecuteModelProviderCredentialTestInput
extends BeginModelProviderCredentialTestExecutionInput {}
interface ModelProviderCredentialTestExecutorEvidence {
readonly plan: Readonly<ModelProviderCredentialTestPlan>;
readonly execution: Readonly<ModelProviderCredentialTestExecution>;
}
export type ExecuteModelProviderCredentialTestResult =
| Readonly<
ModelProviderCredentialTestExecutorEvidence & {
status: 'completed' | 'existing';
result: Readonly<ModelProviderCredentialTestResult>;
}
>
| Readonly<
ModelProviderCredentialTestExecutorEvidence & {
status: 'outcome_unknown';
result: null;
}
>;
export interface ModelProviderCredentialTestExecutor {
execute(
input: Readonly<ExecuteModelProviderCredentialTestInput>,
): Promise<Readonly<ExecuteModelProviderCredentialTestResult>>;
}
export interface ModelProviderCredentialTestExecutorOptions {
readonly repository: ModelProviderCredentialTestExecutionRepository;
readonly credentials: ModelProviderCredentialBindingSource &
ModelProviderCredentialAuditSink;
readonly secrets: ModelProviderSecretMaterialProvider;
readonly fetch?: typeof globalThis.fetch;
readonly now?: () => number;
readonly monotonicNow?: () => number;
readonly transportReady?: (
baseUrl: string,
signal: AbortSignal,
) => Promise<void>;
}
export class ModelProviderCredentialTestExecutorConfigurationError extends TypeError {
readonly code =
'MODEL_PROVIDER_CREDENTIAL_TEST_EXECUTOR_CONFIGURATION_INVALID';
constructor() {
super('Model provider credential test executor configuration is invalid');
this.name = 'ModelProviderCredentialTestExecutorConfigurationError';
}
}
export class ModelProviderCredentialTestExecutorUnavailableError extends Error {
readonly code = 'MODEL_PROVIDER_CREDENTIAL_TEST_EXECUTOR_UNAVAILABLE';
constructor(options?: ErrorOptions) {
super('Model provider credential test executor is unavailable', options);
this.name = 'ModelProviderCredentialTestExecutorUnavailableError';
}
}
function exact(value: unknown, keys: readonly string[]): boolean {
if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
const actual = Object.keys(value).sort();
const expected = [...keys].sort();
return (
actual.length === expected.length &&
actual.every((key, index) => key === expected[index])
);
}
function currentTime(now: () => number): number {
const value = now();
if (!Number.isSafeInteger(value) || value < 0) {
throw new ModelProviderCredentialTestExecutorUnavailableError();
}
return value;
}
function elapsedMs(startedAt: number, monotonicNow: () => number): number {
const value = monotonicNow() - startedAt;
if (!Number.isFinite(value) || value < 0) {
throw new ModelProviderCredentialTestExecutorUnavailableError();
}
return Math.floor(value);
}
async function completeExactly(
repository: ModelProviderCredentialTestExecutionRepository,
result: Readonly<ModelProviderCredentialTestResult>,
): Promise<void> {
try {
await repository.complete(result);
} catch (error) {
if (
!(error instanceof ModelProviderCredentialTestExecutionUnavailableError)
) {
throw error;
}
await repository.complete(result);
}
}
export function createModelProviderCredentialTestExecutor(
options: ModelProviderCredentialTestExecutorOptions,
): Readonly<ModelProviderCredentialTestExecutor> {
const expectedKeys = ['credentials', 'repository', 'secrets'];
if (options?.fetch !== undefined) expectedKeys.push('fetch');
if (options?.monotonicNow !== undefined) expectedKeys.push('monotonicNow');
if (options?.now !== undefined) expectedKeys.push('now');
if (options?.transportReady !== undefined)
expectedKeys.push('transportReady');
if (
!exact(options, expectedKeys) ||
typeof options.repository?.beginExecution !== 'function' ||
typeof options.repository?.complete !== 'function' ||
typeof options.credentials?.resolveModelProviderCredentialBinding !==
'function' ||
typeof options.credentials?.record !== 'function' ||
typeof options.secrets?.resolveProjectSecretMaterial !== 'function' ||
(options.fetch !== undefined && typeof options.fetch !== 'function') ||
(options.now !== undefined && typeof options.now !== 'function') ||
(options.monotonicNow !== undefined &&
typeof options.monotonicNow !== 'function') ||
(options.transportReady !== undefined &&
typeof options.transportReady !== 'function')
) {
throw new ModelProviderCredentialTestExecutorConfigurationError();
}
const now = options.now ?? Date.now;
const monotonicNow = options.monotonicNow ?? (() => performance.now());
const credentials = new BoundModelProviderCredentialProvider({
bindings: options.credentials,
secrets: options.secrets,
audit: options.credentials,
now,
});
return Object.freeze({
async execute(input: Readonly<ExecuteModelProviderCredentialTestInput>) {
if (!exact(input, ['allowlist', 'executionId', 'testId'])) {
throw new ModelProviderCredentialTestExecutorConfigurationError();
}
const begun = await options.repository.beginExecution(input);
if (begun.status === 'existing') {
return begun.result === null
? Object.freeze({
status: 'outcome_unknown' as const,
plan: begun.plan,
execution: begun.execution,
result: null,
})
: Object.freeze({
status: 'existing' as const,
plan: begun.plan,
execution: begun.execution,
result: begun.result,
});
}
const startedAt = monotonicNow();
if (!Number.isFinite(startedAt) || startedAt < 0) {
throw new ModelProviderCredentialTestExecutorUnavailableError();
}
const controller = new AbortController();
const timeout = setTimeout(
() => controller.abort(),
begun.plan.endpoint.deadlineMs,
);
timeout.unref?.();
let outcome: 'reachable' | 'unreachable' = 'unreachable';
let modelCount: number | null = null;
try {
await options.transportReady?.(
begun.plan.endpoint.baseUrl,
controller.signal,
);
const provider = new OpenAiCompatibleProvider({
type: begun.plan.provider,
baseUrl: begun.plan.endpoint.baseUrl,
credentials,
maxResponseBytes: begun.plan.endpoint.maxResponseBytes,
...(options.fetch === undefined ? {} : { fetch: options.fetch }),
});
const models = await provider.listModels({
projectId: begun.plan.projectId,
requestId: begun.execution.executionId,
signal: controller.signal,
});
if (
!controller.signal.aborted &&
models.length <= begun.plan.endpoint.maxModels &&
elapsedMs(startedAt, monotonicNow) <= begun.plan.endpoint.deadlineMs
) {
outcome = 'reachable';
modelCount = models.length;
}
} catch {
outcome = 'unreachable';
modelCount = null;
} finally {
clearTimeout(timeout);
}
const durationMs = Math.min(
begun.plan.endpoint.deadlineMs,
elapsedMs(startedAt, monotonicNow),
);
const result = createModelProviderCredentialTestResult({
executionId: begun.execution.executionId,
testId: begun.plan.testId,
planDigest: begun.plan.planDigest,
outcome,
modelCount,
durationMs,
completedAtMs: currentTime(now),
});
try {
await completeExactly(options.repository, result);
} catch (error) {
throw new ModelProviderCredentialTestExecutorUnavailableError({
cause: error instanceof Error ? error : undefined,
});
}
return Object.freeze({
status: 'completed' as const,
plan: begun.plan,
execution: begun.execution,
result,
});
},
});
}
@@ -0,0 +1,110 @@
#!/usr/bin/env node
import { writeFileSync } from 'node:fs';
import { runModelProviderCredentialTestExecutorProcess } from './modelProviderCredentialTestExecutorProcess';
const USAGE = 'Usage: ql3-provider-credential-test-execute';
const TERMINATION_MESSAGE_FILE = '/dev/termination-log';
function writeFact(
value: Readonly<Record<string, unknown>>,
stream: NodeJS.WriteStream,
): void {
const serialized = JSON.stringify(value);
stream.write(`${serialized}\n`);
if (
process.env.QL3_MODEL_PROVIDER_CREDENTIAL_TEST_WRITE_TERMINATION_MESSAGE ===
'true'
) {
writeFileSync(TERMINATION_MESSAGE_FILE, serialized, {
encoding: 'utf8',
mode: 0o600,
});
}
}
function failureFact(error: unknown): Readonly<Record<string, unknown>> {
const candidate = error as {
readonly name?: unknown;
readonly code?: unknown;
};
return Object.freeze({
schemaVersion: 1,
component: 'qinglong3-model-provider-credential-test-executor',
event: 'execution_failed',
name:
typeof candidate?.name === 'string' && candidate.name.length <= 128
? candidate.name
: 'Error',
...(typeof candidate?.code === 'string' && candidate.code.length <= 128
? { code: candidate.code }
: {}),
});
}
async function run(argv: readonly string[]): Promise<void> {
if (argv.length === 1 && (argv[0] === '--help' || argv[0] === '-h')) {
process.stdout.write(`${USAGE}\n`);
return;
}
if (argv.length !== 0) {
process.stderr.write(
`${JSON.stringify({
code: 'QL3_MODEL_PROVIDER_CREDENTIAL_TEST_EXECUTOR_CLI_USAGE_INVALID',
message: USAGE,
})}\n`,
);
process.exitCode = 64;
return;
}
try {
const result = await runModelProviderCredentialTestExecutorProcess({
environment: process.env,
});
writeFact(
result.status === 'disabled'
? {
schemaVersion: 1,
component: 'qinglong3-model-provider-credential-test-executor',
event: 'execution_disabled',
}
: {
schemaVersion: 1,
component: 'qinglong3-model-provider-credential-test-executor',
event:
result.test.status === 'outcome_unknown'
? 'execution_outcome_unknown'
: 'execution_completed',
testId: result.test.plan.testId,
executionId: result.test.execution.executionId,
status: result.test.status,
...(result.test.result === null
? {}
: {
outcome: result.test.result.outcome,
modelCount: result.test.result.modelCount,
durationMs: result.test.result.durationMs,
...(result.transportFailureCode === undefined
? {}
: {
transportFailureCode: result.transportFailureCode,
transportRequestDigest: result.transportRequestDigest,
...(result.transportAddressSha256 === undefined
? {}
: {
transportAddressSha256:
result.transportAddressSha256,
transportPort: result.transportPort,
}),
}),
}),
},
process.stdout,
);
} catch (error) {
writeFact(failureFact(error), process.stderr);
process.exitCode = 1;
}
}
void run(process.argv.slice(2));
@@ -0,0 +1,694 @@
import { Buffer } from 'node:buffer';
import { createHash } from 'node:crypto';
import { createConnection } from 'node:net';
import { normalize, parse } from 'node:path';
import { setTimeout as delay } from 'node:timers/promises';
import {
normalizeModelProviderCredentialTestAllowlist,
type ModelProviderCredentialTestAllowlist,
} from '@qinglong/ai/model-provider-credential-test-connection';
import {
PostgresModelProviderCredentialTestExecutionRepository,
assertPostgresModelProviderCredentialTesterReady,
type PostgresModelProviderCredentialTesterReadinessReport,
} from '@qinglong/ai/postgres-model-provider-credential-test-connection';
import { PostgresModelProviderCredentialReader } from '@qinglong/ai/postgres-model-provider-credential-storage';
import {
createProjectedModelProviderSecretMaterialProvider,
type ProjectedModelProviderSecretMaterialProvider,
} from '@qinglong/ai/projected-model-provider-secret-material';
import type { OpenPostgresDatabase } from '@qinglong/runtime-core';
import {
createPostgresDatabaseOpener,
isPostgresTlsDnsServername,
loadPostgresCertificateAuthorityFile,
loadPostgresConnectionEnvironment,
type PostgresConnectionOptions,
type PostgresPoolOptions,
} from '@qinglong/cluster-postgres/ai-credential-tester';
import {
absoluteManagementEnvironmentFile,
booleanManagementEnvironmentValue,
boundedManagementEnvironmentValue,
integerManagementEnvironmentValue,
readManagementTlsFile,
} from '../management-support/managementProcessSupport';
import {
createModelProviderCredentialTestExecutor,
type ExecuteModelProviderCredentialTestResult,
type ModelProviderCredentialTestExecutor,
} from './modelProviderCredentialTestExecutor';
const UUID_V4_PATTERN =
/^[0-9a-f]{8}-[0-9a-f]{4}-4[0-9a-f]{3}-[89ab][0-9a-f]{3}-[0-9a-f]{12}$/;
const SAFE_APPLICATION_NAME = /^[A-Za-z0-9][A-Za-z0-9._:-]{0,62}$/;
const SAFE_TRANSPORT_FAILURE_CODE = /^[A-Z][A-Z0-9_]{0,63}$/;
const MAX_COMMAND_BYTES = 4 * 1_024;
const MAX_ALLOWLIST_BYTES = 64 * 1_024;
export interface ModelProviderCredentialTestExecutorCommand {
readonly schemaVersion: 1;
readonly executionId: string;
readonly testId: string;
}
export type ModelProviderCredentialTestExecutorProcessEnvironment = Readonly<
Record<string, string | undefined>
>;
export type ModelProviderCredentialTestExecutorProcessConfig =
| Readonly<{ enabled: false }>
| Readonly<{
enabled: true;
profile: 'cluster-admin';
commandFile: string;
allowlistFile: string;
secretRootDirectory: string;
networkPolicyDenyCanary?: Readonly<{
host: string;
port: number;
}>;
database: Readonly<{
connection: PostgresConnectionOptions;
pool: PostgresPoolOptions;
}>;
}>;
export type ModelProviderCredentialTestExecutorProcessResult =
| Readonly<{ status: 'disabled' }>
| Readonly<{
status: 'completed';
database: PostgresModelProviderCredentialTesterReadinessReport;
test: Readonly<ExecuteModelProviderCredentialTestResult>;
readonly transportFailureCode?: string;
readonly transportRequestDigest?: string;
readonly transportAddressSha256?: string;
readonly transportPort?: number;
}>;
export interface RunModelProviderCredentialTestExecutorProcessOptions {
readonly environment: ModelProviderCredentialTestExecutorProcessEnvironment;
readonly command?: Readonly<ModelProviderCredentialTestExecutorCommand>;
readonly allowlist?: Readonly<ModelProviderCredentialTestAllowlist>;
readonly openDatabase?: OpenPostgresDatabase;
readonly assertReady?: typeof assertPostgresModelProviderCredentialTesterReady;
readonly secrets?: Readonly<ProjectedModelProviderSecretMaterialProvider>;
readonly executor?: Readonly<ModelProviderCredentialTestExecutor>;
readonly fetch?: typeof globalThis.fetch;
readonly now?: () => number;
readonly monotonicNow?: () => number;
readonly transportReady?: (
baseUrl: string,
signal: AbortSignal,
) => Promise<void>;
}
export class ModelProviderCredentialTestExecutorProcessConfigError extends TypeError {
readonly code = 'QL3_MODEL_PROVIDER_CREDENTIAL_TEST_EXECUTOR_CONFIG_INVALID';
constructor(message: string) {
super(
`Model provider credential test executor config is invalid: ${message}`,
);
this.name = 'ModelProviderCredentialTestExecutorProcessConfigError';
}
}
function configFailure(
message: string,
): ModelProviderCredentialTestExecutorProcessConfigError {
return new ModelProviderCredentialTestExecutorProcessConfigError(message);
}
function transportFailureCode(error: unknown): string {
let candidate: unknown = error;
for (let depth = 0; depth < 4; depth += 1) {
if (!candidate || typeof candidate !== 'object') break;
const value = candidate as {
readonly cause?: unknown;
readonly code?: unknown;
readonly message?: unknown;
};
if (
typeof value.code === 'string' &&
SAFE_TRANSPORT_FAILURE_CODE.test(value.code)
) {
return value.code;
}
const message =
typeof value.message === 'string' ? value.message.toLowerCase() : '';
if (
message.includes('certificate') ||
message.includes('self signed') ||
message.includes('unable to verify')
) {
return 'TLS_VALIDATION_FAILED';
}
if (message.includes('getaddrinfo')) return 'DNS_LOOKUP_FAILED';
if (message.includes('bad port')) return 'PORT_REJECTED';
candidate = value.cause;
}
return 'TRANSPORT_FAILED';
}
function transportRequestDigest(
input: Parameters<typeof globalThis.fetch>[0],
init?: Parameters<typeof globalThis.fetch>[1],
): string {
const request = input instanceof Request ? input : undefined;
const url = request?.url ?? String(input);
const method = init?.method ?? request?.method ?? 'GET';
return `sha256:${createHash('sha256')
.update(method.toUpperCase(), 'utf8')
.update('\0', 'utf8')
.update(url, 'utf8')
.digest('hex')}`;
}
function transportFailureEndpoint(
error: unknown,
): Readonly<{ addressSha256: string; port: number }> | undefined {
let candidate: unknown = error;
for (let depth = 0; depth < 4; depth += 1) {
if (!candidate || typeof candidate !== 'object') break;
const value = candidate as {
readonly address?: unknown;
readonly cause?: unknown;
readonly port?: unknown;
};
if (
typeof value.address === 'string' &&
value.address.length >= 1 &&
value.address.length <= 128 &&
Number.isInteger(value.port) &&
(value.port as number) >= 1 &&
(value.port as number) <= 65_535
) {
return Object.freeze({
addressSha256: `sha256:${createHash('sha256')
.update(value.address, 'utf8')
.digest('hex')}`,
port: value.port as number,
});
}
candidate = value.cause;
}
return undefined;
}
async function connectOnce(
host: string,
port: number,
signal: AbortSignal,
timeoutMs: number,
): Promise<void> {
await new Promise<void>((resolve, reject) => {
let settled = false;
const socket = createConnection({ host, port });
const finish = (error?: Error): void => {
if (settled) return;
settled = true;
signal.removeEventListener('abort', onAbort);
socket.destroy();
if (error) reject(error);
else resolve();
};
const onAbort = (): void =>
finish(
signal.reason instanceof Error
? signal.reason
: new Error('transport readiness aborted'),
);
signal.addEventListener('abort', onAbort, { once: true });
socket.setTimeout(timeoutMs);
socket.once('connect', () => finish());
socket.once('timeout', () => finish(new Error('transport timeout')));
socket.once('error', (error) => finish(error));
});
}
async function waitForTransportReady(
baseUrl: string,
signal: AbortSignal,
denyCanary?: Readonly<{ host: string; port: number }>,
): Promise<void> {
const endpoint = new URL(baseUrl);
const hostname = endpoint.hostname.replace(/^\[|\]$/g, '');
const port = endpoint.port
? Number(endpoint.port)
: endpoint.protocol === 'https:'
? 443
: 80;
while (true) {
if (signal.aborted) throw signal.reason;
try {
await connectOnce(hostname, port, signal, 500);
if (denyCanary !== undefined) {
let denied = false;
try {
await connectOnce(denyCanary.host, denyCanary.port, signal, 150);
} catch (error) {
if (signal.aborted) throw signal.reason ?? error;
denied = true;
}
if (!denied) {
await delay(50, undefined, { signal });
continue;
}
}
return;
} catch (error) {
if (signal.aborted) throw signal.reason ?? error;
await delay(50, undefined, { signal });
}
}
}
function boundedValue(
environment: ModelProviderCredentialTestExecutorProcessEnvironment,
name: string,
maximumLength: number,
): string | undefined {
return boundedManagementEnvironmentValue(
environment,
name,
maximumLength,
configFailure,
);
}
function booleanValue(
environment: ModelProviderCredentialTestExecutorProcessEnvironment,
name: string,
): boolean {
return booleanManagementEnvironmentValue(environment, name, configFailure);
}
function integerValue(
environment: ModelProviderCredentialTestExecutorProcessEnvironment,
name: string,
fallback: number,
minimum: number,
maximum: number,
): number {
return integerManagementEnvironmentValue(
environment,
name,
fallback,
minimum,
maximum,
configFailure,
);
}
function absolutePath(
environment: ModelProviderCredentialTestExecutorProcessEnvironment,
name: string,
): string {
const value = absoluteManagementEnvironmentFile(
environment,
name,
configFailure,
);
if (normalize(value) !== value || parse(value).root === value) {
throw configFailure(`${name} is invalid`);
}
return value;
}
function loadConnection(
environment: ModelProviderCredentialTestExecutorProcessEnvironment,
): Readonly<{
connection: PostgresConnectionOptions;
pool: PostgresPoolOptions;
}> {
let connection: PostgresConnectionOptions;
try {
connection = loadPostgresConnectionEnvironment(environment, {
connectionString: 'QL3_POSTGRES_AI_CREDENTIAL_TESTER_URL',
host: 'QL3_POSTGRES_AI_CREDENTIAL_TESTER_HOST',
port: 'QL3_POSTGRES_AI_CREDENTIAL_TESTER_PORT',
database: 'QL3_POSTGRES_AI_CREDENTIAL_TESTER_DATABASE',
user: 'QL3_POSTGRES_AI_CREDENTIAL_TESTER_USER',
password: 'QL3_POSTGRES_AI_CREDENTIAL_TESTER_PASSWORD',
});
} catch (error) {
throw configFailure(
error instanceof Error
? error.message
: 'PostgreSQL AI credential tester connection is invalid',
);
}
const mode =
environment.QL3_POSTGRES_AI_CREDENTIAL_TESTER_TLS_MODE ?? 'verify-full';
if (mode !== 'verify-full' && mode !== 'disable') {
throw configFailure('PostgreSQL TLS mode must be verify-full or disable');
}
if (
mode === 'disable' &&
!booleanValue(
environment,
'QL3_POSTGRES_AI_CREDENTIAL_TESTER_ALLOW_INSECURE',
)
) {
throw configFailure('disabling PostgreSQL TLS requires explicit opt-in');
}
const servername = boundedValue(
environment,
'QL3_POSTGRES_AI_CREDENTIAL_TESTER_TLS_SERVERNAME',
253,
);
if (mode === 'verify-full' && !isPostgresTlsDnsServername(servername)) {
throw configFailure(
'PostgreSQL TLS servername must be an explicit DNS name',
);
}
const caFile = boundedValue(
environment,
'QL3_POSTGRES_AI_CREDENTIAL_TESTER_TLS_CA_FILE',
4_096,
);
if (mode === 'disable' && caFile !== undefined) {
throw configFailure('PostgreSQL CA file cannot be used with disabled TLS');
}
let ca: string | undefined;
if (caFile !== undefined) {
try {
ca = loadPostgresCertificateAuthorityFile(caFile);
} catch {
throw configFailure('PostgreSQL CA file is invalid');
}
}
const applicationName =
boundedValue(
environment,
'QL3_POSTGRES_AI_CREDENTIAL_TESTER_APPLICATION_NAME',
63,
) ?? 'qinglong3-ai-credential-tester';
if (!SAFE_APPLICATION_NAME.test(applicationName)) {
throw configFailure('PostgreSQL application name is invalid');
}
return Object.freeze({
connection: Object.freeze({
...connection,
tls:
mode === 'disable'
? Object.freeze({ mode: 'disable' as const })
: Object.freeze({
mode: 'verify-full' as const,
servername: servername!,
...(ca === undefined ? {} : { ca }),
}),
}),
pool: Object.freeze({
applicationName,
maxConnections: integerValue(
environment,
'QL3_POSTGRES_AI_CREDENTIAL_TESTER_POOL_MAX',
1,
1,
1,
),
idleTimeoutMs: integerValue(
environment,
'QL3_POSTGRES_AI_CREDENTIAL_TESTER_IDLE_TIMEOUT_MS',
1_000,
100,
10_000,
),
connectionTimeoutMs: integerValue(
environment,
'QL3_POSTGRES_AI_CREDENTIAL_TESTER_CONNECTION_TIMEOUT_MS',
5_000,
100,
60_000,
),
}),
});
}
function loadNetworkPolicyDenyCanary(
environment: ModelProviderCredentialTestExecutorProcessEnvironment,
): Readonly<{ host: string; port: number }> | undefined {
const host = boundedValue(
environment,
'QL3_MODEL_PROVIDER_CREDENTIAL_TEST_DENY_CANARY_HOST',
253,
);
const portValue = boundedValue(
environment,
'QL3_MODEL_PROVIDER_CREDENTIAL_TEST_DENY_CANARY_PORT',
5,
);
if (host === undefined && portValue === undefined) return undefined;
if (
!isPostgresTlsDnsServername(host) ||
portValue === undefined ||
!/^[1-9][0-9]{0,4}$/.test(portValue)
) {
throw configFailure('network policy deny canary is invalid');
}
const port = Number(portValue);
if (port > 65_535) {
throw configFailure('network policy deny canary is invalid');
}
return Object.freeze({ host, port });
}
export function loadModelProviderCredentialTestExecutorProcessConfig(
environment: ModelProviderCredentialTestExecutorProcessEnvironment,
): Readonly<ModelProviderCredentialTestExecutorProcessConfig> {
if (!environment || typeof environment !== 'object') {
throw configFailure('environment is invalid');
}
if (
!booleanValue(
environment,
'QL3_MODEL_PROVIDER_CREDENTIAL_TEST_EXECUTOR_ENABLED',
)
) {
return Object.freeze({ enabled: false as const });
}
if (environment.QL3_PROFILE !== 'cluster-admin') {
throw configFailure('QL3_PROFILE must be cluster-admin');
}
const networkPolicyDenyCanary = loadNetworkPolicyDenyCanary(environment);
return Object.freeze({
enabled: true as const,
profile: 'cluster-admin' as const,
commandFile: absolutePath(
environment,
'QL3_MODEL_PROVIDER_CREDENTIAL_TEST_COMMAND_FILE',
),
allowlistFile: absolutePath(
environment,
'QL3_MODEL_PROVIDER_CREDENTIAL_TEST_ALLOWLIST_FILE',
),
secretRootDirectory: absolutePath(
environment,
'QL3_MODEL_PROVIDER_CREDENTIAL_TEST_SECRET_ROOT',
),
...(networkPolicyDenyCanary === undefined
? {}
: { networkPolicyDenyCanary }),
database: loadConnection(environment),
});
}
function exact(value: unknown, keys: readonly string[]): boolean {
if (!value || typeof value !== 'object' || Array.isArray(value)) return false;
const actual = Object.keys(value).sort();
const expected = [...keys].sort();
return (
actual.length === expected.length &&
actual.every((key, index) => key === expected[index])
);
}
function normalizeCommand(
value: unknown,
): Readonly<ModelProviderCredentialTestExecutorCommand> {
if (
!exact(value, ['executionId', 'schemaVersion', 'testId']) ||
(value as { schemaVersion?: unknown }).schemaVersion !== 1 ||
typeof (value as { executionId?: unknown }).executionId !== 'string' ||
!UUID_V4_PATTERN.test((value as { executionId: string }).executionId) ||
typeof (value as { testId?: unknown }).testId !== 'string' ||
!UUID_V4_PATTERN.test((value as { testId: string }).testId)
) {
throw configFailure('command is invalid');
}
const command = value as ModelProviderCredentialTestExecutorCommand;
return Object.freeze({
schemaVersion: 1 as const,
executionId: command.executionId,
testId: command.testId,
});
}
function readJson(filePath: string, maximumBytes: number): unknown {
const bytes = readManagementTlsFile(filePath, false, configFailure);
try {
if (bytes.length > maximumBytes)
throw configFailure('authority file is too large');
return JSON.parse(new TextDecoder('utf8', { fatal: true }).decode(bytes));
} catch (error) {
if (
error instanceof ModelProviderCredentialTestExecutorProcessConfigError
) {
throw error;
}
throw configFailure('authority file is invalid');
} finally {
bytes.fill(0);
}
}
function readCommand(
filePath: string,
): Readonly<ModelProviderCredentialTestExecutorCommand> {
return normalizeCommand(readJson(filePath, MAX_COMMAND_BYTES));
}
function readAllowlist(
filePath: string,
): Readonly<ModelProviderCredentialTestAllowlist> {
try {
return normalizeModelProviderCredentialTestAllowlist(
readJson(
filePath,
MAX_ALLOWLIST_BYTES,
) as ModelProviderCredentialTestAllowlist,
);
} catch (error) {
if (
error instanceof ModelProviderCredentialTestExecutorProcessConfigError
) {
throw error;
}
throw configFailure('allowlist is invalid');
}
}
export async function runModelProviderCredentialTestExecutorProcess(
options: RunModelProviderCredentialTestExecutorProcessOptions,
): Promise<Readonly<ModelProviderCredentialTestExecutorProcessResult>> {
const expectedKeys = ['environment'];
for (const key of [
'allowlist',
'assertReady',
'command',
'executor',
'fetch',
'monotonicNow',
'now',
'openDatabase',
'secrets',
'transportReady',
]) {
if (
(options as unknown as Record<string, unknown> | undefined)?.[key] !==
undefined
) {
expectedKeys.push(key);
}
}
if (!exact(options, expectedKeys)) throw configFailure('options are invalid');
const config = loadModelProviderCredentialTestExecutorProcessConfig(
options.environment,
);
if (!config.enabled) return Object.freeze({ status: 'disabled' as const });
const command = options.command
? normalizeCommand(options.command)
: readCommand(config.commandFile);
const allowlist = options.allowlist
? normalizeModelProviderCredentialTestAllowlist(options.allowlist)
: readAllowlist(config.allowlistFile);
const openDatabase =
options.openDatabase ??
createPostgresDatabaseOpener({
role: 'ai-credential-tester',
connection: config.database.connection,
pool: config.database.pool,
onPoolError() {
// In-flight queries own one-shot availability; there is no listener to withdraw.
},
});
const database = await openDatabase();
try {
const evidence = await (
options.assertReady ?? assertPostgresModelProviderCredentialTesterReady
)(database.pool);
const secrets =
options.secrets ??
(await createProjectedModelProviderSecretMaterialProvider({
rootDirectory: config.secretRootDirectory,
}));
let observedTransportFailureCode: string | undefined;
let observedTransportRequestDigest: string | undefined;
let observedTransportEndpoint:
| Readonly<{ addressSha256: string; port: number }>
| undefined;
const configuredFetch = options.fetch ?? globalThis.fetch;
const observedFetch: typeof globalThis.fetch = async (input, init) => {
const requestDigest = transportRequestDigest(input, init);
try {
return await configuredFetch(input, init);
} catch (error) {
observedTransportFailureCode = transportFailureCode(error);
observedTransportRequestDigest = requestDigest;
observedTransportEndpoint = transportFailureEndpoint(error);
throw error;
}
};
const executor =
options.executor ??
createModelProviderCredentialTestExecutor({
repository: new PostgresModelProviderCredentialTestExecutionRepository(
database.pool,
),
credentials: new PostgresModelProviderCredentialReader(database.pool),
secrets,
fetch: observedFetch,
transportReady:
options.transportReady ??
((baseUrl, signal) =>
waitForTransportReady(
baseUrl,
signal,
config.networkPolicyDenyCanary,
)),
...(options.now === undefined ? {} : { now: options.now }),
...(options.monotonicNow === undefined
? {}
: { monotonicNow: options.monotonicNow }),
});
const result = await executor.execute({
executionId: command.executionId,
testId: command.testId,
allowlist,
});
return Object.freeze({
status: 'completed' as const,
database: evidence,
test: result,
...(observedTransportFailureCode === undefined
? {}
: {
transportFailureCode: observedTransportFailureCode,
transportRequestDigest: observedTransportRequestDigest!,
...(observedTransportEndpoint === undefined
? {}
: {
transportAddressSha256:
observedTransportEndpoint.addressSha256,
transportPort: observedTransportEndpoint.port,
}),
}),
});
} finally {
await database.close();
}
}