Infisical is the open-source platform for securing secrets, certificates, access, and AI Agents.
TypeScript acmeagentsai-agentscertificate-managementdevsecopsenvironment-variableskubernetesopen-sourcepampkipostgresprivate-caprivileged-access-managementsecret-managementsecret-managersecretssecrets-managementsecuritysecurity-toolsvault
Merge remote-tracking branch 'origin/main' into agent-vault-on-behalf-of
Scott Wilsone87c41858ae3
diff --cc .infisicalignoreindex 87d57e5ef7,87d57e5ef7..08865909a8--- a/.infisicalignore+++ b/.infisicalignore@@@ -81,3 -81,3 +81,7 @@@ frontend/src/pages/secret-scanning/layofrontend/src/pages/organization/BillingV2Page/billing-v2-offline-usage.ts:generic-api-key:18tests/suites/sso/scim/tokens_test.go:jwt:342frontend/src/hooks/api/appConnections/types/app-options.ts:atlassian-api-token:386++tests/clients/api/api.gen.go:generic-api-key:15743++tests/clients/api/api.gen.go:generic-api-key:15744++tests/clients/api/api.gen.go:generic-api-key:15770++tests/clients/api/api.gen.go:generic-api-key:15771diff --cc backend/src/@types/fastify.d.tsindex 777eac7af9,e3a25df0e7..f293d7de4f--- a/backend/src/@types/fastify.d.ts+++ b/backend/src/@types/fastify.d.ts@@@ -306,206 -309,215 +310,216 @@@ declare module "fastify"interface FastifyInstance {redis: Redis | Cluster;cookieSigningKey: string;- services: {- login: TAuthLoginFactory;- password: TAuthPasswordFactory;- accountRecovery: TAccountRecoveryServiceFactory;- signup: TAuthSignupFactory;- authToken: TAuthTokenServiceFactory;- oauthClient: TOauthClientServiceFactory;- permission: TPermissionServiceFactory;- org: TOrgServiceFactory;- oidc: TOidcConfigServiceFactory;- superAdmin: TSuperAdminServiceFactory;- encryptionKeyRotation: TEncryptionKeyRotationServiceFactory;- user: TUserServiceFactory;- group: TGroupServiceFactory;- groupProject: TGroupProjectServiceFactory;- pkiAlert: TPkiAlertServiceFactory;- project: TProjectServiceFactory;- projectMembership: TProjectMembershipServiceFactory;- projectEnv: TProjectEnvServiceFactory;- projectKey: TProjectKeyServiceFactory;- secret: TSecretServiceFactory;- secretValueTracking: TSecretValueTrackingServiceFactory;- secretReplication: TSecretReplicationServiceFactory;- secretTag: TSecretTagServiceFactory;- secretValidationRule: TSecretValidationRuleServiceFactory;- secretImport: TSecretImportServiceFactory;- resourceMetadata: TResourceMetadataServiceFactory;- projectFolderGrant: TProjectFolderGrantServiceFactory;- projectBot: TProjectBotServiceFactory;- folder: TSecretFolderServiceFactory;- integration: TIntegrationServiceFactory;- integrationAuth: TIntegrationAuthServiceFactory;- webhook: TWebhookServiceFactory;- serviceToken: TServiceTokenServiceFactory;- identityV1: TIdentityServiceFactory;- identityV2: TScopedIdentityV2ServiceFactory;- identityAccessToken: TIdentityAccessTokenServiceFactory;- identityProject: TIdentityProjectServiceFactory;- identityTokenAuth: TIdentityTokenAuthServiceFactory;- identityUa: TIdentityUaServiceFactory;- identityKubernetesAuth: TIdentityKubernetesAuthServiceFactory;- identityGcpAuth: TIdentityGcpAuthServiceFactory;- identityAliCloudAuth: TIdentityAliCloudAuthServiceFactory;- identityTlsCertAuth: TIdentityTlsCertAuthServiceFactory;- identityAwsAuth: TIdentityAwsAuthServiceFactory;- identityAzureAuth: TIdentityAzureAuthServiceFactory;- identityOciAuth: TIdentityOciAuthServiceFactory;- identityOidcAuth: TIdentityOidcAuthServiceFactory;- identityJwtAuth: TIdentityJwtAuthServiceFactory;- identitySpiffeAuth: TIdentitySpiffeAuthServiceFactory;- identityLdapAuth: TIdentityLdapAuthServiceFactory;- accessApprovalPolicy: TAccessApprovalPolicyServiceFactory;- secretAccessApprovalGlobalPolicyBridge: TSecretAccessApprovalGlobalPolicyBridgeServiceFactory;- secretAccessApprovalGlobalRequestBridge: TSecretAccessApprovalGlobalRequestBridgeServiceFactory;- accessApprovalRequest: TAccessApprovalRequestServiceFactory;- secretApprovalPolicy: TSecretApprovalPolicyServiceFactory;- secretChangeGlobalPolicyBridge: TSecretChangeGlobalPolicyBridgeServiceFactory;- secretApprovalRequest: TSecretApprovalRequestServiceFactory;- saml: TSamlConfigServiceFactory;- scim: TScimServiceFactory;- ldap: TLdapConfigServiceFactory;- auditLog: TAuditLogServiceFactory;- auditLogStream: TAuditLogStreamServiceFactory;- auditLogSettings: TAuditLogSettingsServiceFactory;- certificate: TCertificateServiceFactory;- certificateCleanup: TCertificateCleanupServiceFactory;- certificateInventoryView: TCertificateInventoryViewServiceFactory;- certificateV3: TCertificateV3ServiceFactory;- certificateRequest: TCertificateRequestServiceFactory;- certificateTemplate: TCertificateTemplateServiceFactory;- certificatePolicy: TCertificatePolicyServiceFactory;- certificateProfile: TCertificateProfileServiceFactory;- pkiApplication: TPkiApplicationServiceFactory;- pkiApplicationMembership: TPkiApplicationMembershipServiceFactory;- signerMembership: TSignerMembershipServiceFactory;- signerPolicy: TSignerPolicyServiceFactory;- pkiApplicationEnrollment: TPkiApplicationEnrollmentServiceFactory;- certManagerProjectResolver: TCertManagerProjectResolverFactory;- pamProjectResolver: TPamProjectResolverFactory;- secretScanningV2Instance: TSecretScanningV2InstanceServiceFactory;- secretScanningV2ProjectResolver: TSecretScanningV2ProjectResolverFactory;- agentVaultProjectResolver: TAgentVaultProjectResolverFactory;- agentVaultAccessBundle: TAgentVaultAccessBundleServiceFactory;- agentVaultOauth: TAgentVaultOauthServiceFactory;- agentVaultVariable: TAgentVaultVariableServiceFactory;- agentVaultPersonalValue: TAgentVaultPersonalValueServiceFactory;- agentVaultProxy: TAgentVaultProxyServiceFactory;- agentVaultSession: TAgentVaultSessionServiceFactory;- agentVaultSessionLog: TAgentVaultSessionLogServiceFactory;- agentVaultMembership: TAgentVaultMembershipServiceFactory;- agentVaultDelegation: TAgentVaultDelegationServiceFactory;- certManagerInstance: TCertManagerInstanceServiceFactory;- certManagerExport: TCertManagerExportServiceFactory;- certificateAuthority: TCertificateAuthorityServiceFactory;- certificateAuthorityCrl: TCertificateAuthorityCrlServiceFactory;- certificateAuthorityOcsp: TCertificateAuthorityOcspServiceFactory;- certificateEst: TCertificateEstServiceFactory;- pkiAcme: TPkiAcmeServiceFactory;- pkiScep: TPkiScepServiceFactory;- certificateEstV3: TCertificateEstV3ServiceFactory;- pkiCollection: TPkiCollectionServiceFactory;- pkiSubscriber: TPkiSubscriberServiceFactory;- pkiSync: TPkiSyncServiceFactory;- pkiDiscovery: TPkiDiscoveryServiceFactory;- pkiInstallation: TPkiInstallationServiceFactory;- pkiSigner: TSignerServiceFactory;- secretScanning: TSecretScanningServiceFactory;- license: TLicenseServiceFactory;- licenseClient: TLicenseClientFactory;- licenseV2: TLicenseV2ServiceFactory;- trustedIp: TTrustedIpServiceFactory;- secretBlindIndex: TSecretBlindIndexServiceFactory;- telemetry: TTelemetryServiceFactory;- updateCheck: TUpdateCheckServiceFactory;- dynamicSecret: TDynamicSecretServiceFactory;- dynamicSecretLease: TDynamicSecretLeaseServiceFactory;- emailDomain: TEmailDomainServiceFactory;- secretSharing: TSecretSharingServiceFactory;- userActivation: TUserActivationServiceFactory;- userEngagement: TUserEngagementServiceFactory;- externalKms: TExternalKmsServiceFactory;- hsm: THsmServiceFactory;- orgAdmin: TOrgAdminServiceFactory;- slack: TSlackServiceFactory;- workflowIntegration: TWorkflowIntegrationServiceFactory;- cmek: TCmekServiceFactory;- migration: TExternalMigrationServiceFactory;- externalGroupOrgRoleMapping: TExternalGroupOrgRoleMappingServiceFactory;- projectTemplate: TProjectTemplateServiceFactory;- totp: TTotpServiceFactory;- webAuthn: TWebAuthnServiceFactory;- mfaRecoveryCode: TMfaRecoveryCodeServiceFactory;- appConnection: TAppConnectionServiceFactory;- hsmConnector: THsmConnectorServiceFactory;- secretSync: TSecretSyncServiceFactory;- kmip: TKmipServiceFactory;- kmipOperation: TKmipOperationServiceFactory;- kmipServer: TKmipServerServiceFactory;- secretRotationV2: TSecretRotationV2ServiceFactory;- microsoftTeams: TMicrosoftTeamsServiceFactory;- assumePrivileges: TAssumePrivilegeServiceFactory;- insights: TInsightsServiceFactory;- auditReport: TAuditReportServiceFactory;- relay: TRelayServiceFactory;- gatewayV2: TGatewayV2ServiceFactory;- gatewayPool: TGatewayPoolServiceFactory;- resourceAuthMethod: TResourceAuthMethodServiceFactory;- githubOrgSync: TGithubOrgSyncServiceFactory;- gitHubApp: TGitHubAppServiceFactory;- honeyTokenConfig: THoneyTokenConfigServiceFactory;- honeyToken: THoneyTokenServiceFactory;- proxiedService: TProxiedServiceServiceFactory;- agentProxyCa: TAgentProxyCaServiceFactory;- folderCommit: TFolderCommitServiceFactory;- pit: TPitServiceFactory;- secretScanningV2: TSecretScanningV2ServiceFactory;- internalCertificateAuthority: TInternalCertificateAuthorityServiceFactory;- pkiTemplate: TPkiTemplatesServiceFactory;- reminder: TReminderServiceFactory;- eventBus: TInternalEventBusService;- projectEvents: TProjectEventsService;- projectEventsSSE: TProjectEventsSSEService;- identityAuthTemplate: TIdentityAuthTemplateServiceFactory;- notification: TNotificationServiceFactory;- alert: TAlertServiceFactory;- alertChannelTest: TAlertChannelTestServiceFactory;- announcement: TAnnouncementServiceFactory;- offlineUsageReport: TOfflineUsageReportServiceFactory;- orgProductStats: TOrgProductStatsServiceFactory;- pamAccountTemplate: TPamAccountTemplateServiceFactory;- pamFolder: TPamFolderServiceFactory;- pamAccount: TPamAccountServiceFactory;- pamDiscovery: TPamDiscoverySourceServiceFactory;- pamAccountRotation: TPamAccountRotationServiceFactory;- pamAccountHeartbeat: TPamAccountHeartbeatServiceFactory;- pamMembership: TPamMembershipServiceFactory;- pamSession: TPamSessionServiceFactory;- pamSessionChunk: TPamSessionChunkServiceFactory;- pamAccessRequest: TPamAccessRequestServiceFactory;- pamWebAccess: TPamWebAccessServiceFactory;- mfaSession: TMfaSessionServiceFactory;- membershipUser: TMembershipUserServiceFactory;- membershipIdentity: TMembershipIdentityServiceFactory;- membershipGroup: TMembershipGroupServiceFactory;- additionalPrivilege: TAdditionalPrivilegeServiceFactory;- folderPermission: TFolderPermissionServiceFactory;- role: TRoleServiceFactory;- convertor: TConvertorServiceFactory;- subOrganization: TSubOrgServiceFactory;- pkiAlertV2: TPkiAlertV2ServiceFactory;- approvalPolicy: TApprovalPolicyServiceFactory;- appConnectionCredentialRotation: TAppConnectionCredentialRotationServiceFactory;- caSigningConfig: TCaSigningConfigServiceFactory;- caAutoRenewalQueue: TCaAutoRenewalQueueFactory;- };+ services: FastifyServices;// this is exclusive use for middlewares in which we need to inject data// everywhere else access using service layer- store: {- user: Pick<TUserDALFactory, "findById">;- kmipClient: Pick<TKmipClientDALFactory, "findByProjectAndClientId">;- };+ store: FastifyStore;+ }++ // Kept as named interfaces, not inline object types: an inline type in the generic FastifyInstance is copied per+ // instantiation, and comparing those copies resolves every service type on each route check (~3s per edit in the LSP).+ interface FastifyServices {+ login: TAuthLoginFactory;+ password: TAuthPasswordFactory;+ accountRecovery: TAccountRecoveryServiceFactory;+ signup: TAuthSignupFactory;+ authToken: TAuthTokenServiceFactory;+ oauthClient: TOauthClientServiceFactory;+ oidcIssuer: TOidcIssuerServiceFactory;+ permission: TPermissionServiceFactory;+ org: TOrgServiceFactory;+ oidc: TOidcConfigServiceFactory;+ superAdmin: TSuperAdminServiceFactory;+ encryptionKeyRotation: TEncryptionKeyRotationServiceFactory;+ user: TUserServiceFactory;+ group: TGroupServiceFactory;+ groupProject: TGroupProjectServiceFactory;+ pkiAlert: TPkiAlertServiceFactory;+ project: TProjectServiceFactory;+ projectMembership: TProjectMembershipServiceFactory;+ projectEnv: TProjectEnvServiceFactory;+ projectKey: TProjectKeyServiceFactory;+ secret: TSecretServiceFactory;+ secretValueTracking: TSecretValueTrackingServiceFactory;+ secretReplication: TSecretReplicationServiceFactory;+ secretTag: TSecretTagServiceFactory;+ secretValidationRule: TSecretValidationRuleServiceFactory;+ secretImport: TSecretImportServiceFactory;+ resourceMetadata: TResourceMetadataServiceFactory;+ projectFolderGrant: TProjectFolderGrantServiceFactory;+ projectBot: TProjectBotServiceFactory;+ folder: TSecretFolderServiceFactory;+ integration: TIntegrationServiceFactory;+ integrationAuth: TIntegrationAuthServiceFactory;+ webhook: TWebhookServiceFactory;+ serviceToken: TServiceTokenServiceFactory;+ identityV1: TIdentityServiceFactory;+ identityV2: TScopedIdentityV2ServiceFactory;+ identityAccessToken: TIdentityAccessTokenServiceFactory;+ identityProject: TIdentityProjectServiceFactory;+ identityTokenAuth: TIdentityTokenAuthServiceFactory;+ identityUa: TIdentityUaServiceFactory;+ identityKubernetesAuth: TIdentityKubernetesAuthServiceFactory;+ identityGcpAuth: TIdentityGcpAuthServiceFactory;+ identityAliCloudAuth: TIdentityAliCloudAuthServiceFactory;+ identityTlsCertAuth: TIdentityTlsCertAuthServiceFactory;+ identityAwsAuth: TIdentityAwsAuthServiceFactory;+ identityAzureAuth: TIdentityAzureAuthServiceFactory;+ identityOciAuth: TIdentityOciAuthServiceFactory;+ identityOidcAuth: TIdentityOidcAuthServiceFactory;+ identityJwtAuth: TIdentityJwtAuthServiceFactory;+ identitySpiffeAuth: TIdentitySpiffeAuthServiceFactory;+ identityLdapAuth: TIdentityLdapAuthServiceFactory;+ accessApprovalPolicy: TAccessApprovalPolicyServiceFactory;+ secretAccessApprovalGlobalPolicyBridge: TSecretAccessApprovalGlobalPolicyBridgeServiceFactory;+ secretAccessApprovalGlobalRequestBridge: TSecretAccessApprovalGlobalRequestBridgeServiceFactory;+ accessApprovalRequest: TAccessApprovalRequestServiceFactory;+ secretApprovalPolicy: TSecretApprovalPolicyServiceFactory;+ secretChangeGlobalPolicyBridge: TSecretChangeGlobalPolicyBridgeServiceFactory;+ secretApprovalRequest: TSecretApprovalRequestServiceFactory;+ saml: TSamlConfigServiceFactory;+ scim: TScimServiceFactory;+ ldap: TLdapConfigServiceFactory;+ auditLog: TAuditLogServiceFactory;+ auditLogStream: TAuditLogStreamServiceFactory;+ auditLogSettings: TAuditLogSettingsServiceFactory;+ certificate: TCertificateServiceFactory;+ certificateCleanup: TCertificateCleanupServiceFactory;+ certificateInventoryView: TCertificateInventoryViewServiceFactory;+ certificateV3: TCertificateV3ServiceFactory;+ certificateRequest: TCertificateRequestServiceFactory;+ certificateTemplate: TCertificateTemplateServiceFactory;+ certificatePolicy: TCertificatePolicyServiceFactory;+ certificateProfile: TCertificateProfileServiceFactory;+ pkiApplication: TPkiApplicationServiceFactory;+ pkiApplicationMembership: TPkiApplicationMembershipServiceFactory;+ signerMembership: TSignerMembershipServiceFactory;+ signerPolicy: TSignerPolicyServiceFactory;+ pkiApplicationEnrollment: TPkiApplicationEnrollmentServiceFactory;+ certManagerProjectResolver: TCertManagerProjectResolverFactory;+ pamProjectResolver: TPamProjectResolverFactory;+ secretScanningV2Instance: TSecretScanningV2InstanceServiceFactory;+ secretScanningV2ProjectResolver: TSecretScanningV2ProjectResolverFactory;+ agentVaultProjectResolver: TAgentVaultProjectResolverFactory;+ agentVaultAccessBundle: TAgentVaultAccessBundleServiceFactory;+ agentVaultOauth: TAgentVaultOauthServiceFactory;+ agentVaultVariable: TAgentVaultVariableServiceFactory;+ agentVaultPersonalValue: TAgentVaultPersonalValueServiceFactory;+ agentVaultProxy: TAgentVaultProxyServiceFactory;+ agentVaultSession: TAgentVaultSessionServiceFactory;+ agentVaultSessionLog: TAgentVaultSessionLogServiceFactory;+ agentVaultMembership: TAgentVaultMembershipServiceFactory;++ agentVaultDelegation: TAgentVaultDelegationServiceFactory;+ certManagerInstance: TCertManagerInstanceServiceFactory;+ certManagerExport: TCertManagerExportServiceFactory;+ certificateAuthority: TCertificateAuthorityServiceFactory;+ certificateAuthorityCrl: TCertificateAuthorityCrlServiceFactory;+ certificateAuthorityOcsp: TCertificateAuthorityOcspServiceFactory;+ certificateEst: TCertificateEstServiceFactory;+ pkiAcme: TPkiAcmeServiceFactory;+ pkiScep: TPkiScepServiceFactory;+ certificateEstV3: TCertificateEstV3ServiceFactory;+ pkiCollection: TPkiCollectionServiceFactory;+ pkiSubscriber: TPkiSubscriberServiceFactory;+ pkiSync: TPkiSyncServiceFactory;+ pkiDiscovery: TPkiDiscoveryServiceFactory;+ pkiInstallation: TPkiInstallationServiceFactory;+ pkiSigner: TSignerServiceFactory;+ secretScanning: TSecretScanningServiceFactory;+ license: TLicenseServiceFactory;+ licenseClient: TLicenseClientFactory;+ licenseV2: TLicenseV2ServiceFactory;+ trustedIp: TTrustedIpServiceFactory;+ secretBlindIndex: TSecretBlindIndexServiceFactory;+ telemetry: TTelemetryServiceFactory;+ updateCheck: TUpdateCheckServiceFactory;+ dynamicSecret: TDynamicSecretServiceFactory;+ dynamicSecretLease: TDynamicSecretLeaseServiceFactory;+ emailDomain: TEmailDomainServiceFactory;+ secretSharing: TSecretSharingServiceFactory;+ userActivation: TUserActivationServiceFactory;+ userEngagement: TUserEngagementServiceFactory;+ externalKms: TExternalKmsServiceFactory;+ hsm: THsmServiceFactory;+ orgAdmin: TOrgAdminServiceFactory;+ slack: TSlackServiceFactory;+ workflowIntegration: TWorkflowIntegrationServiceFactory;+ cmek: TCmekServiceFactory;+ migration: TExternalMigrationServiceFactory;+ externalGroupOrgRoleMapping: TExternalGroupOrgRoleMappingServiceFactory;+ projectTemplate: TProjectTemplateServiceFactory;+ totp: TTotpServiceFactory;+ webAuthn: TWebAuthnServiceFactory;+ mfaRecoveryCode: TMfaRecoveryCodeServiceFactory;+ appConnection: TAppConnectionServiceFactory;+ hsmConnector: THsmConnectorServiceFactory;+ secretSync: TSecretSyncServiceFactory;+ kmip: TKmipServiceFactory;+ kmipOperation: TKmipOperationServiceFactory;+ kmipServer: TKmipServerServiceFactory;+ secretRotationV2: TSecretRotationV2ServiceFactory;+ microsoftTeams: TMicrosoftTeamsServiceFactory;+ assumePrivileges: TAssumePrivilegeServiceFactory;+ insights: TInsightsServiceFactory;+ secretReadActivity: TSecretReadActivityServiceFactory;+ auditReport: TAuditReportServiceFactory;+ relay: TRelayServiceFactory;+ gatewayV2: TGatewayV2ServiceFactory;+ gatewayPool: TGatewayPoolServiceFactory;+ resourceAuthMethod: TResourceAuthMethodServiceFactory;+ githubOrgSync: TGithubOrgSyncServiceFactory;+ gitHubApp: TGitHubAppServiceFactory;+ honeyTokenConfig: THoneyTokenConfigServiceFactory;+ honeyToken: THoneyTokenServiceFactory;+ proxiedService: TProxiedServiceServiceFactory;+ agentProxyCa: TAgentProxyCaServiceFactory;+ folderCommit: TFolderCommitServiceFactory;+ pit: TPitServiceFactory;+ secretScanningV2: TSecretScanningV2ServiceFactory;+ internalCertificateAuthority: TInternalCertificateAuthorityServiceFactory;+ pkiTemplate: TPkiTemplatesServiceFactory;+ reminder: TReminderServiceFactory;+ eventBus: TInternalEventBusService;+ projectEvents: TProjectEventsService;+ projectEventsSSE: TProjectEventsSSEService;+ identityAuthTemplate: TIdentityAuthTemplateServiceFactory;+ notification: TNotificationServiceFactory;+ alert: TAlertServiceFactory;+ alertChannelTest: TAlertChannelTestServiceFactory;+ announcement: TAnnouncementServiceFactory;+ offlineUsageReport: TOfflineUsageReportServiceFactory;+ orgProductStats: TOrgProductStatsServiceFactory;+ pamAccountTemplate: TPamAccountTemplateServiceFactory;+ pamFolder: TPamFolderServiceFactory;+ pamAccount: TPamAccountServiceFactory;+ pamDiscovery: TPamDiscoverySourceServiceFactory;+ pamAccountRotation: TPamAccountRotationServiceFactory;+ pamAccountHeartbeat: TPamAccountHeartbeatServiceFactory;+ pamMembership: TPamMembershipServiceFactory;+ pamSession: TPamSessionServiceFactory;+ pamSessionChunk: TPamSessionChunkServiceFactory;+ pamAccessRequest: TPamAccessRequestServiceFactory;+ pamWebAccess: TPamWebAccessServiceFactory;+ mfaSession: TMfaSessionServiceFactory;+ membershipUser: TMembershipUserServiceFactory;+ membershipIdentity: TMembershipIdentityServiceFactory;+ membershipGroup: TMembershipGroupServiceFactory;+ additionalPrivilege: TAdditionalPrivilegeServiceFactory;+ folderPermission: TFolderPermissionServiceFactory;+ role: TRoleServiceFactory;+ convertor: TConvertorServiceFactory;+ subOrganization: TSubOrgServiceFactory;+ pkiAlertV2: TPkiAlertV2ServiceFactory;+ approvalPolicy: TApprovalPolicyServiceFactory;+ delegatedApproval: TDelegatedApprovalServiceFactory;+ delegatedApprovalCallback: TDelegatedApprovalCallbackServiceFactory;+ appConnectionCredentialRotation: TAppConnectionCredentialRotationServiceFactory;+ caSigningConfig: TCaSigningConfigServiceFactory;+ caAutoRenewalQueue: TCaAutoRenewalQueueFactory;+ }++ interface FastifyStore {+ user: Pick<TUserDALFactory, "findById">;+ kmipClient: Pick<TKmipClientDALFactory, "findByProjectAndClientId">;}}diff --cc backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.tsindex 54be7a4934,b904a1385a..853936cb9c--- a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-service.ts@@@ -28,6 -28,21 +28,26 @@@ import { KmsDataKey } from "@app/servicimport { TMembershipDALFactory } from "@app/services/membership/membership-dal";import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";++import {++ findCallerDelegation,++ resolveOnBehalfOfUser,++ TOnBehalfOfDeps++} from "../agent-vault-delegation/agent-vault-on-behalf-of-fns";+ import { TAgentVaultMemberDALFactory } from "../agent-vault-member/agent-vault-member-dal";+ import {+ checkOauthClaimUnderLock,+ checkOauthServerUnderLock,+ OAUTH_SERVER_URL_NEEDS_AUTHORIZATION_MESSAGE,+ TAgentVaultOauthServiceFactory+ } from "../agent-vault-oauth/agent-vault-oauth-service";+ import { AGENT_VAULT_OAUTH_HEADER_NAME, TAgentVaultOauthConfig } from "../agent-vault-oauth/agent-vault-oauth-types";+ import { TAgentVaultPersonalValueDALFactory } from "../agent-vault-personal-value/agent-vault-personal-value-dal";+ import {+ clearPersonalValuesAfterRevoke,+ sameMemberProvidedFields+ } from "../agent-vault-personal-value/agent-vault-personal-value-fns";+ import { TAgentVaultPersonalValueServiceFactory } from "../agent-vault-personal-value/agent-vault-personal-value-service";+ import { TAgentVaultVariableDALFactory } from "../agent-vault-variable/agent-vault-variable-dal";import {agentVaultActorKey,resolveAgentVaultActorNames,diff --cc backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.tsindex 916495abbc,dba68e7432..5e19ed43b4--- a/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.ts+++ b/backend/src/ee/services/agent-vault-access-bundle/agent-vault-access-bundle-types.ts@@@ -1,5 -1,5 +1,6 @@@import { TGenericPermission } from "@app/lib/types";++import { TOnBehalfOfUser } from "../agent-vault-session/agent-vault-session-types";import {AgentVaultCredentialType,AgentVaultHttpMethod,diff --cc backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-dal.tsindex e1a839bfef,0000000000..4624f2131cmode 100644,000000..100644--- a/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-dal.ts+++ b/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-dal.ts@@@ -1,276 -1,0 +1,274 @@@+import { Knex } from "knex";++import { TDbClient } from "@app/db";+import { AccessScope, TableName, TAgentVaultDelegations, TMemberships } from "@app/db/schemas";+import { DatabaseError } from "@app/lib/errors";+import { ormify, selectAllTableCols } from "@app/lib/knex";++import { AgentVaultDelegationScope } from "../agent-vault/agent-vault-enums";++export type TAgentVaultDelegationDALFactory = ReturnType<typeof agentVaultDelegationDALFactory>;+export type TAgentVaultDelegationSubjectDALFactory = ReturnType<typeof agentVaultDelegationSubjectDALFactory>;++export type TAgentVaultDelegationView = {+ id: string;+ machineIdentity: { id: string; name: string };+ scope: AgentVaultDelegationScope;+ users: {+ id: string;+ username: string;+ email: string | null;+ firstName: string | null;+ lastName: string | null;+ addedAt: Date;+ }[];+ groups: { id: string; name: string; addedAt: Date }[];+ createdAt: Date;+ updatedAt: Date;+};++const DELEGATION = TableName.AgentVaultDelegation;+const SUBJECTS = TableName.AgentVaultDelegationSubject;++/**+ * A selected delegation counts only while it names someone. Each subject cascades away with its Agent Vault membership,+ * which can empty one, and an empty one covers no one, so it reads exactly like no delegation at all.+ */+const whereNamesSomeone = (query: Knex.QueryBuilder, conn: Knex) =>+ query.where((live) => {+ void live+ .where(`${DELEGATION}.scope`, AgentVaultDelegationScope.AllMembers)+ .orWhereExists(+ conn(SUBJECTS).whereRaw(`??.?? = ??.??`, [SUBJECTS, "delegationId", DELEGATION, "id"]).select(conn.raw("1"))+ );+ });++export const agentVaultDelegationDALFactory = (db: TDbClient) => {+ const orm = ormify(db, TableName.AgentVaultDelegation);++ // The row a conflict hits stays locked until the transaction ends, so two writes to one identity's delegation+ // run one after the other.+ const upsertScope = async (+ {+ projectId,+ identityId,+ membershipId,+ scope+ }: { projectId: string; identityId: string; membershipId: string; scope: AgentVaultDelegationScope },+ tx: Knex+ ): Promise<TAgentVaultDelegations> => {+ try {+ const [row] = (await tx(TableName.AgentVaultDelegation)+ .insert({ projectId, identityId, membershipId, scope })+ .onConflict(["identityId", "projectId"])+ .merge({ membershipId, scope })+ .returning("*")) as TAgentVaultDelegations[];+ return row;+ } catch (error) {+ throw new DatabaseError({ error, name: "Upsert Agent Vault delegation" });+ }+ };++ const findViews = async (+ {+ projectId,+ identityIds,+ limit,+ offset = 0+ }: { projectId: string; identityIds?: string[]; limit?: number; offset?: number },+ tx?: Knex+ ): Promise<{ delegations: TAgentVaultDelegationView[]; totalCount: number }> => {+ try {+ const conn = tx || db.replicaNode();+ const filtered = () => {+ const query = conn(TableName.AgentVaultDelegation).where(+ `${TableName.AgentVaultDelegation}.projectId`,+ projectId+ );+ if (identityIds) void query.whereIn(`${TableName.AgentVaultDelegation}.identityId`, identityIds);+ return whereNamesSomeone(query, conn);+ };++ const countResult = (await filtered().count(`${TableName.AgentVaultDelegation}.id as count`).first()) as+ | { count: string }+ | undefined;+ const totalCount = parseInt(countResult?.count || "0", 10);++ const pageQuery = filtered()+ .join(TableName.Identity, `${TableName.Identity}.id`, `${TableName.AgentVaultDelegation}.identityId`)+ .select(+ selectAllTableCols(TableName.AgentVaultDelegation),+ db.ref("name").withSchema(TableName.Identity).as("identityName")+ )+ .orderBy(`${TableName.Identity}.name`, "asc")+ .orderBy(`${TableName.AgentVaultDelegation}.id`, "asc");+ if (limit !== undefined) void pageQuery.limit(limit).offset(offset);+ const rows = (await pageQuery) as (TAgentVaultDelegations & { identityName: string })[];+ if (!rows.length) return { delegations: [], totalCount };++ const subjects = (await conn(TableName.AgentVaultDelegationSubject)+ .whereIn(+ `${TableName.AgentVaultDelegationSubject}.delegationId`,+ rows.map((row) => row.id)+ )+ .join(+ TableName.Membership,+ `${TableName.Membership}.id`,+ `${TableName.AgentVaultDelegationSubject}.membershipId`+ )+ .leftJoin(TableName.Users, `${TableName.Users}.id`, `${TableName.Membership}.actorUserId`)+ .leftJoin(TableName.Groups, `${TableName.Groups}.id`, `${TableName.Membership}.actorGroupId`)+ .select(+ db.ref("delegationId").withSchema(TableName.AgentVaultDelegationSubject),+ db.ref("actorUserId").withSchema(TableName.Membership).as("userId"),+ db.ref("actorGroupId").withSchema(TableName.Membership).as("groupId"),+ db.ref("createdAt").withSchema(TableName.AgentVaultDelegationSubject).as("addedAt"),+ db.ref("username").withSchema(TableName.Users),+ db.ref("email").withSchema(TableName.Users),+ db.ref("firstName").withSchema(TableName.Users),+ db.ref("lastName").withSchema(TableName.Users),+ db.ref("name").withSchema(TableName.Groups).as("groupName")+ )+ .orderBy(`${TableName.Users}.username`, "asc")+ .orderBy(`${TableName.Groups}.name`, "asc")) as {+ delegationId: string;+ userId: string | null;+ groupId: string | null;+ username: string | null;+ email: string | null;+ firstName: string | null;+ lastName: string | null;+ groupName: string | null;+ addedAt: Date;+ }[];+- const delegations = rows.map(- (row): TAgentVaultDelegationView => ({- id: row.id,- machineIdentity: { id: row.identityId, name: row.identityName },- scope: row.scope as AgentVaultDelegationScope,- users: subjects- .filter((subject) => subject.delegationId === row.id && subject.userId && subject.username)- .map((subject) => ({- id: subject.userId!,- username: subject.username!,- email: subject.email,- firstName: subject.firstName,- lastName: subject.lastName,- addedAt: subject.addedAt- })),- groups: subjects- .filter((subject) => subject.delegationId === row.id && subject.groupId && subject.groupName)- .map((subject) => ({ id: subject.groupId!, name: subject.groupName!, addedAt: subject.addedAt })),- createdAt: row.createdAt,- updatedAt: row.updatedAt- })- );++ const delegations = rows.map((row): TAgentVaultDelegationView => ({++ id: row.id,++ machineIdentity: { id: row.identityId, name: row.identityName },++ scope: row.scope as AgentVaultDelegationScope,++ users: subjects++ .filter((subject) => subject.delegationId === row.id && subject.userId && subject.username)++ .map((subject) => ({++ id: subject.userId!,++ username: subject.username!,++ email: subject.email,++ firstName: subject.firstName,++ lastName: subject.lastName,++ addedAt: subject.addedAt++ })),++ groups: subjects++ .filter((subject) => subject.delegationId === row.id && subject.groupId && subject.groupName)++ .map((subject) => ({ id: subject.groupId!, name: subject.groupName!, addedAt: subject.addedAt })),++ createdAt: row.createdAt,++ updatedAt: row.updatedAt++ }));++ return { delegations, totalCount };+ } catch (error) {+ throw new DatabaseError({ error, name: "Find Agent Vault delegations" });+ }+ };++ /**+ * Under all-members every user is covered, otherwise the users the delegation names and the members of the groups+ * it names. Group membership is read the way the permission engine reads it, without isPending. A subject exists+ * only while its user's or group's own Agent Vault membership does, so this needs no membership check of its own.+ */+ const coversUser = async (+ { delegation, userId }: { delegation: Pick<TAgentVaultDelegations, "id" | "scope">; userId: string },+ tx?: Knex+ ): Promise<boolean> => {+ if (delegation.scope === AgentVaultDelegationScope.AllMembers) return true;+ try {+ const conn = tx || db.replicaNode();+ const subject = await conn(SUBJECTS)+ .join(TableName.Membership, `${TableName.Membership}.id`, `${SUBJECTS}.membershipId`)+ .where(`${SUBJECTS}.delegationId`, delegation.id)+ .where((qb) => {+ void qb+ .where(`${TableName.Membership}.actorUserId`, userId)+ .orWhereIn(+ `${TableName.Membership}.actorGroupId`,+ conn(TableName.UserGroupMembership).select("groupId").where({ userId })+ );+ })+ .select(db.ref("id").withSchema(SUBJECTS))+ .first();+ return Boolean(subject);+ } catch (error) {+ throw new DatabaseError({ error, name: "Check Agent Vault delegation coverage" });+ }+ };++ // Undefined when the identity has no delegation, or only one left naming no one.+ const findForIdentity = async (+ { projectId, identityId }: { projectId: string; identityId: string },+ tx?: Knex+ ): Promise<TAgentVaultDelegations | undefined> => {+ try {+ const conn = tx || db.replicaNode();+ return (await whereNamesSomeone(+ conn(DELEGATION).where(`${DELEGATION}.projectId`, projectId).where(`${DELEGATION}.identityId`, identityId),+ conn+ )+ .select(selectAllTableCols(DELEGATION))+ .first()) as TAgentVaultDelegations | undefined;+ } catch (error) {+ throw new DatabaseError({ error, name: "Find Agent Vault delegation" });+ }+ };++ // False when the identity has no delegation at all.+ const identityCoversUser = async (+ { projectId, identityId, userId }: { projectId: string; identityId: string; userId: string },+ tx?: Knex+ ): Promise<boolean> => {+ const delegation = await findForIdentity({ projectId, identityId }, tx);+ return delegation ? coversUser({ delegation, userId }, tx) : false;+ };++ /**+ * The Agent Vault memberships of the identity and of the users and groups a save names, taken FOR SHARE. Removing a+ * member deletes its row in a transaction of its own, so a save waits for a removal in flight and then sees the row+ * gone, and a removal that starts later waits for the save and then clears what it wrote. The identity, user and+ * group rows are taken FOR KEY SHARE first, the lock the save's foreign keys take anyway: deleting one of them+ * deletes it before the cascade reaches its memberships, so locking in that order keeps the two from deadlocking.+ */+ const lockMemberships = async (+ {+ projectId,+ identityId,+ userIds,+ groupIds+ }: { projectId: string; identityId: string; userIds: string[]; groupIds: string[] },+ tx: Knex+ ) => {+ try {+ await tx(TableName.Identity).where({ id: identityId }).forKeyShare().select("id");+ if (userIds.length) await tx(TableName.Users).whereIn("id", userIds).orderBy("id").forKeyShare().select("id");+ if (groupIds.length) await tx(TableName.Groups).whereIn("id", groupIds).orderBy("id").forKeyShare().select("id");+ return (await tx(TableName.Membership)+ .where(`${TableName.Membership}.scope`, AccessScope.Project)+ .where(`${TableName.Membership}.scopeProjectId`, projectId)+ .where((actor) => {+ void actor.where(`${TableName.Membership}.actorIdentityId`, identityId);+ if (userIds.length) void actor.orWhereIn(`${TableName.Membership}.actorUserId`, userIds);+ if (groupIds.length) void actor.orWhereIn(`${TableName.Membership}.actorGroupId`, groupIds);+ })+ .forShare()+ .select(+ db.ref("id").withSchema(TableName.Membership),+ db.ref("actorIdentityId").withSchema(TableName.Membership),+ db.ref("actorUserId").withSchema(TableName.Membership),+ db.ref("actorGroupId").withSchema(TableName.Membership)+ )) as Pick<TMemberships, "id" | "actorIdentityId" | "actorUserId" | "actorGroupId">[];+ } catch (error) {+ throw new DatabaseError({ error, name: "Lock Agent Vault memberships for a delegation" });+ }+ };++ return { ...orm, upsertScope, findViews, coversUser, findForIdentity, identityCoversUser, lockMemberships };+};++export const agentVaultDelegationSubjectDALFactory = (db: TDbClient) =>+ ormify(db, TableName.AgentVaultDelegationSubject);diff --cc backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-service.tsindex dc4cf91da2,0000000000..23fb65a5dbmode 100644,000000..100644--- a/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-service.ts+++ b/backend/src/ee/services/agent-vault-delegation/agent-vault-delegation-service.ts@@@ -1,381 -1,0 +1,381 @@@+import { ForbiddenError, subject } from "@casl/ability";+import { Knex } from "knex";++import { AccessScope, ProjectMembershipRole, RESOURCE_SCOPE, ResourceType, TMemberships } from "@app/db/schemas";+import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";+import { isActiveRole } from "@app/ee/services/permission/permission-fns";+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import { ProjectPermissionIdentityActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";+import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";+import { TGenericPermission } from "@app/lib/types";+import { ActorType } from "@app/services/auth/auth-type";+import { TMembershipDALFactory } from "@app/services/membership/membership-dal";+import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";+++import { TAgentVaultAccessBundleDALFactory } from "../agent-vault-access-bundle/agent-vault-access-bundle-dal";+import { AgentVaultDelegationScope } from "../agent-vault/agent-vault-enums";+import { getAgentVaultPermission, getAgentVaultReachability } from "../agent-vault/agent-vault-permission";- import { TAgentVaultAccessBundleDALFactory } from "../agent-vault-access-bundle/agent-vault-access-bundle-dal";+import {+ TAgentVaultDelegationDALFactory,+ TAgentVaultDelegationSubjectDALFactory,+ TAgentVaultDelegationView+} from "./agent-vault-delegation-dal";+import {+ TDeleteDelegationDTO,+ TGetDelegationDTO,+ TListDelegationsDTO,+ TSetDelegationDTO+} from "./agent-vault-delegation-types";++type TAgentVaultDelegationServiceFactoryDep = {+ agentVaultDelegationDAL: Pick<+ TAgentVaultDelegationDALFactory,+ "upsertScope" | "findViews" | "delete" | "transaction" | "lockMemberships"+ >;+ agentVaultDelegationSubjectDAL: Pick<TAgentVaultDelegationSubjectDALFactory, "find" | "delete" | "insertMany">;+ agentVaultAccessBundleDAL: Pick<TAgentVaultAccessBundleDALFactory, "find">;+ membershipDAL: Pick<TMembershipDALFactory, "find" | "findResourceMembershipsForActor">;+ membershipRoleDAL: Pick<TMembershipRoleDALFactory, "find">;+ userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find">;+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;+};++export type TAgentVaultDelegationServiceFactory = ReturnType<typeof agentVaultDelegationServiceFactory>;++type TMissingAccessBundle = { id: string; name: string };++// The row id stays internal: a delegation is named by its machine identity, the one id a client sends back.+const toDelegation = ({ id, ...delegation }: TAgentVaultDelegationView) => delegation;++const withNoMissingAccessBundles = (delegation: TAgentVaultDelegationView) => ({+ ...toDelegation(delegation),+ users: delegation.users.map((user) => ({ ...user, missingAccessBundles: [] as TMissingAccessBundle[] })),+ groups: delegation.groups.map((group) => ({ ...group, missingAccessBundles: [] as TMissingAccessBundle[] })),+ missingAccessBundles: [] as TMissingAccessBundle[]+});++const quoted = (ids: string[]) => ids.map((id) => `'${id}'`).join(", ");++export const agentVaultDelegationServiceFactory = ({+ agentVaultDelegationDAL,+ agentVaultDelegationSubjectDAL,+ agentVaultAccessBundleDAL,+ membershipDAL,+ membershipRoleDAL,+ userGroupMembershipDAL,+ permissionService+}: TAgentVaultDelegationServiceFactoryDep) => {+ // A delegation says whom an identity can act as, so managing one is managing the identity, which in Agent Vault only+ // the admin role can do.+ const checkIdentityPermission = async (+ { projectId, ctx, machineIdentityId }: { projectId: string; ctx: TGenericPermission; machineIdentityId?: string },+ action: ProjectPermissionIdentityActions+ ) => {+ const { permission } = await getAgentVaultPermission({ permissionService }, { projectId, ctx });+ ForbiddenError.from(permission).throwUnlessCan(+ action,+ machineIdentityId+ ? subject(ProjectPermissionSub.Identity, { identityId: machineIdentityId })+ : ProjectPermissionSub.Identity+ );+ };++ const notFound = (machineIdentityId: string) =>+ new NotFoundError({+ message: `Machine identity with ID '${machineIdentityId}' has no delegation, so it can't act on behalf of users`+ });++ // The same rule as granting an access bundle: a subject is named by its own Agent Vault membership. The memberships+ // are the rows the save holds locked, so no removal can land between this check and the write.+ const assertSubjectsInAgentVault = async (+ {+ projectId,+ userIds,+ groupIds,+ memberships+ }: {+ projectId: string;+ userIds: string[];+ groupIds: string[];+ memberships: Pick<TMemberships, "actorUserId" | "actorGroupId">[];+ },+ tx: Knex+ ) => {+ const memberGroups = new Set(memberships.map((row) => row.actorGroupId));+ const missingGroups = groupIds.filter((id) => !memberGroups.has(id));+ if (missingGroups.length) {+ throw new BadRequestError({+ message: `Group(s) ${quoted(missingGroups)} are not members of Agent Vault. Add them under Access Control first.`+ });+ }++ const memberUsers = new Set(memberships.map((row) => row.actorUserId));+ const missingUsers = userIds.filter((id) => !memberUsers.has(id));+ if (!missingUsers.length) return;++ const groupMemberships = await userGroupMembershipDAL.find({ $in: { userId: missingUsers } }, { tx });+ const groupsInAgentVault = groupMemberships.length+ ? await membershipDAL.find(+ {+ scope: AccessScope.Project,+ scopeProjectId: projectId,+ $in: { actorGroupId: [...new Set(groupMemberships.map((row) => row.groupId))] }+ },+ { tx }+ )+ : [];+ const memberGroupIds = new Set(groupsInAgentVault.map((row) => row.actorGroupId));+ const throughGroup = new Set(+ groupMemberships.filter((row) => memberGroupIds.has(row.groupId)).map((row) => row.userId)+ );++ // Both reasons in one message, so a batch that holds both is fixed in one round trip.+ const viaGroup = missingUsers.filter((id) => throughGroup.has(id));+ const strangers = missingUsers.filter((id) => !throughGroup.has(id));+ const reasons: string[] = [];+ if (viaGroup.length) {+ reasons.push(+ `User(s) ${quoted(viaGroup)} are in Agent Vault through a group. Name the group instead, or add them directly under Access Control first.`+ );+ }+ if (strangers.length) {+ reasons.push(`User(s) ${quoted(strangers)} are not members of Agent Vault. Add them under Access Control first.`);+ }+ throw new BadRequestError({ message: reasons.join(" ") });+ };++ // Users and the identity go through the same reachability as mint, so the view can't disagree with what mint allows.+ const reachOf = async ({+ projectId,+ orgId,+ actor+ }: {+ projectId: string;+ orgId: string;+ actor: { type: ActorType.USER | ActorType.IDENTITY; id: string };+ }) => {+ try {+ const { accessBundleIds } = await getAgentVaultReachability(+ { permissionService, membershipDAL },+ { projectId, ctx: { actor: actor.type, actorId: actor.id, actorOrgId: orgId, actorAuthMethod: null } }+ );+ return accessBundleIds;+ } catch (error) {+ if (error instanceof ForbiddenRequestError && error.name === "ProjectMembershipNotFound") return [];+ throw error;+ }+ };++ // A group reaches nothing without a live Agent Vault role, every bundle with the admin role, and otherwise the+ // bundles granted to it, which is what a group's grants add to its members' reach.+ const groupReachOf = async ({ projectId, groupIds }: { projectId: string; groupIds: string[] }) => {+ const reaches = new Map<string, string[] | null>();+ if (!groupIds.length) return reaches;++ const [memberships, grants] = await Promise.all([+ membershipDAL.find({ scope: AccessScope.Project, scopeProjectId: projectId, $in: { actorGroupId: groupIds } }),+ membershipDAL.find({+ scope: RESOURCE_SCOPE,+ scopeProjectId: projectId,+ scopeResourceType: ResourceType.AgentVaultAccessBundle,+ $in: { actorGroupId: groupIds }+ })+ ]);+ const roles = memberships.length+ ? await membershipRoleDAL.find({ $in: { membershipId: memberships.map((membership) => membership.id) } })+ : [];++ groupIds.forEach((groupId) => {+ const membershipIds = new Set(+ memberships.filter((m) => m.actorGroupId === groupId && m.isActive).map((membership) => membership.id)+ );+ const liveRoles = roles.filter((role) => membershipIds.has(role.membershipId) && isActiveRole(role));+ if (!liveRoles.length) {+ reaches.set(groupId, []);+ } else if (liveRoles.some((role) => role.role === ProjectMembershipRole.Admin)) {+ reaches.set(groupId, null);+ } else {+ reaches.set(+ groupId,+ grants+ .filter((grant) => grant.actorGroupId === groupId && grant.isActive)+ .map((grant) => grant.scopeResourceId!)+ );+ }+ });+ return reaches;+ };++ // A session on a user's behalf can use only the bundles both the user and the identity reach, so these are the+ // bundles the identity can't act on for each user and group it covers. All-members covers Agent Vault admins, who+ // reach every bundle, so there it is every bundle the identity can't reach.+ const withMissingAccessBundles = async ({+ projectId,+ ctx,+ delegation+ }: {+ projectId: string;+ ctx: TGenericPermission;+ delegation: TAgentVaultDelegationView;+ }) => {+ const identityReach = await reachOf({+ projectId,+ orgId: ctx.actorOrgId,+ actor: { type: ActorType.IDENTITY, id: delegation.machineIdentity.id }+ });+ const lacking: TMissingAccessBundle[] =+ identityReach === null+ ? []+ : (await agentVaultAccessBundleDAL.find({ projectId }, { sort: [["name", "asc"]] }))+ .filter((bundle) => !identityReach.includes(bundle.id))+ .map((bundle) => ({ id: bundle.id, name: bundle.name }));+ const missingFrom = (reach: string[] | null) =>+ reach === null ? lacking : lacking.filter((bundle) => reach.includes(bundle.id));++ const [userReaches, groupReaches] = lacking.length+ ? await Promise.all([+ Promise.all(+ delegation.users.map((user) =>+ reachOf({ projectId, orgId: ctx.actorOrgId, actor: { type: ActorType.USER, id: user.id } })+ )+ ),+ groupReachOf({ projectId, groupIds: delegation.groups.map((group) => group.id) })+ ])+ : [[], new Map<string, string[] | null>()];++ // Each reach ran getProjectPermission for someone else, and the audit log reads the caller's permission metadata+ // from the request context. Running the caller's check again, memoized so it costs no query, puts it back.+ await getAgentVaultPermission({ permissionService }, { projectId, ctx });++ const users = delegation.users.map((user, index) => ({+ ...user,+ missingAccessBundles: lacking.length ? missingFrom(userReaches[index]) : []+ }));+ const groups = delegation.groups.map((group) => {+ // A null reach is every bundle, so it can't fall back with ??.+ const reach = groupReaches.get(group.id);+ return { ...group, missingAccessBundles: reach === undefined ? [] : missingFrom(reach) };+ });+ const missingIds = new Set([...users, ...groups].flatMap((s) => s.missingAccessBundles.map((bundle) => bundle.id)));+ const missingAccessBundles =+ delegation.scope === AgentVaultDelegationScope.AllMembers+ ? lacking+ : lacking.filter((bundle) => missingIds.has(bundle.id));++ return { ...toDelegation(delegation), users, groups, missingAccessBundles };+ };++ const listDelegations = async ({ projectId, ctx, machineIdentityIds, limit, offset }: TListDelegationsDTO) => {+ await checkIdentityPermission({ projectId, ctx }, ProjectPermissionIdentityActions.Read);+ const { delegations, totalCount } = await agentVaultDelegationDAL.findViews({+ projectId,+ identityIds: machineIdentityIds,+ limit,+ offset+ });+ return { delegations: delegations.map(toDelegation), totalCount };+ };++ // An identity may read its own, so an orchestrator can check what it was allowed before it acts.+ const getDelegation = async ({ projectId, ctx, machineIdentityId }: TGetDelegationDTO) => {+ const { permission, isAdmin } = await getAgentVaultPermission({ permissionService }, { projectId, ctx });+ const isSelf = ctx.actor === ActorType.IDENTITY && ctx.actorId === machineIdentityId;+ if (!isSelf) {+ ForbiddenError.from(permission).throwUnlessCan(+ ProjectPermissionIdentityActions.Read,+ subject(ProjectPermissionSub.Identity, { identityId: machineIdentityId })+ );+ }++ const {+ delegations: [delegation]+ } = await agentVaultDelegationDAL.findViews({ projectId, identityIds: [machineIdentityId] });+ if (!delegation) throw notFound(machineIdentityId);+ // The missing bundles were never granted to the identity, so reading its own delegation can't reveal them.+ if (!isAdmin) return { delegation: withNoMissingAccessBundles(delegation) };+ return { delegation: await withMissingAccessBundles({ projectId, ctx, delegation }) };+ };++ const setDelegation = async ({ projectId, ctx, machineIdentityId, scope, userIds, groupIds }: TSetDelegationDTO) => {+ await checkIdentityPermission({ projectId, ctx, machineIdentityId }, ProjectPermissionIdentityActions.Edit);++ // A write replaces the whole list, so a subject left out is no longer covered.+ const wantedUserIds = scope === AgentVaultDelegationScope.Selected ? userIds : [];+ const wantedGroupIds = scope === AgentVaultDelegationScope.Selected ? groupIds : [];++ const delegation = await agentVaultDelegationDAL.transaction(async (tx) => {+ // Before the delegation row, the order a removal from Agent Vault takes them in, so a save and a removal can't+ // each hold a lock the other waits for.+ const memberships = await agentVaultDelegationDAL.lockMemberships(+ { projectId, identityId: machineIdentityId, userIds: wantedUserIds, groupIds: wantedGroupIds },+ tx+ );+ // Project-scoped, so an identity from another org is a 404 like one that doesn't exist.+ const identityMembership = memberships.find((row) => row.actorIdentityId === machineIdentityId);+ if (!identityMembership) {+ throw new NotFoundError({+ message: `Machine identity with ID '${machineIdentityId}' is not a member of Agent Vault. Add it under Access Control first.`+ });+ }+ await assertSubjectsInAgentVault(+ { projectId, userIds: wantedUserIds, groupIds: wantedGroupIds, memberships },+ tx+ );++ const row = await agentVaultDelegationDAL.upsertScope(+ { projectId, identityId: machineIdentityId, membershipId: identityMembership.id, scope },+ tx+ );++ const wantedMembershipIds = new Set(+ memberships+ .filter(+ (membership) =>+ (membership.actorUserId && wantedUserIds.includes(membership.actorUserId)) ||+ (membership.actorGroupId && wantedGroupIds.includes(membership.actorGroupId))+ )+ .map((membership) => membership.id)+ );+ // Rows that stay are kept rather than rewritten, so each one's addedAt still says when it was added.+ const existing = await agentVaultDelegationSubjectDAL.find({ delegationId: row.id }, { tx });+ const stale = existing.filter((named) => !wantedMembershipIds.has(named.membershipId));+ if (stale.length) {+ await agentVaultDelegationSubjectDAL.delete({ $in: { id: stale.map((named) => named.id) } }, tx);+ }+ const keptMembershipIds = new Set(existing.map((named) => named.membershipId));+ const added = [...wantedMembershipIds]+ .filter((membershipId) => !keptMembershipIds.has(membershipId))+ .map((membershipId) => ({ delegationId: row.id, membershipId }));+ if (added.length) await agentVaultDelegationSubjectDAL.insertMany(added, tx);++ const {+ delegations: [written]+ } = await agentVaultDelegationDAL.findViews({ projectId, identityIds: [machineIdentityId] }, tx);+ return written;+ });++ // After the commit: reading every covered user's reach is many queries, none of which belong in the transaction.+ return { delegation: await withMissingAccessBundles({ projectId, ctx, delegation }) };+ };++ const deleteDelegation = async ({ projectId, ctx, machineIdentityId }: TDeleteDelegationDTO) => {+ await checkIdentityPermission({ projectId, ctx, machineIdentityId }, ProjectPermissionIdentityActions.Edit);++ const deleted = await agentVaultDelegationDAL.transaction(async (tx) => {+ const {+ delegations: [delegation]+ } = await agentVaultDelegationDAL.findViews({ projectId, identityIds: [machineIdentityId] }, tx);+ if (!delegation) return undefined;++ // Two concurrent deletes both read it; only the one whose delete removed the row reports it, so the audit+ // trail holds a single deletion.+ const removed = await agentVaultDelegationDAL.delete({ id: delegation.id }, tx);+ return removed.length ? delegation : undefined;+ });+ if (!deleted) throw notFound(machineIdentityId);++ return { delegation: toDelegation(deleted) };+ };++ return { listDelegations, getDelegation, setDelegation, deleteDelegation };+};diff --cc backend/src/ee/services/agent-vault-delegation/agent-vault-on-behalf-of-fns.tsindex 14f1d41957,0000000000..d9409d54efmode 100644,000000..100644--- a/backend/src/ee/services/agent-vault-delegation/agent-vault-on-behalf-of-fns.ts+++ b/backend/src/ee/services/agent-vault-delegation/agent-vault-on-behalf-of-fns.ts@@@ -1,113 -1,0 +1,113 @@@+import { OrgMembershipStatus } from "@app/db/schemas";+import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";+import {+ ProjectPermissionAgentVaultSessionActions,+ ProjectPermissionSub+} from "@app/ee/services/permission/project-permission";+import { BadRequestError, ForbiddenRequestError } from "@app/lib/errors";+import { TGenericPermission } from "@app/lib/types";+import { ActorType } from "@app/services/auth/auth-type";+import { TMembershipDALFactory } from "@app/services/membership/membership-dal";+import { TOrgDALFactory } from "@app/services/org/org-dal";+import { TUserDALFactory } from "@app/services/user/user-dal";+- import { getAgentVaultReachability } from "../agent-vault/agent-vault-permission";+import { TOnBehalfOfUser } from "../agent-vault-session/agent-vault-session-types";++import { getAgentVaultReachability } from "../agent-vault/agent-vault-permission";+import { TAgentVaultDelegationDALFactory } from "./agent-vault-delegation-dal";++export type TOnBehalfOfDeps = {+ agentVaultDelegationDAL: Pick<TAgentVaultDelegationDALFactory, "findForIdentity" | "coversUser">;+ userDAL: Pick<TUserDALFactory, "findOne">;+ orgDAL: Pick<TOrgDALFactory, "findEffectiveOrgMembership">;+ permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;+ membershipDAL: Pick<TMembershipDALFactory, "findResourceMembershipsForActor">;+};++export const findCallerDelegation = async (+ { agentVaultDelegationDAL }: Pick<TOnBehalfOfDeps, "agentVaultDelegationDAL">,+ { projectId, ctx }: { projectId: string; ctx: TGenericPermission }+) => {+ if (ctx.actor !== ActorType.IDENTITY) {+ throw new BadRequestError({ message: "Only a machine identity can start a session on behalf of a user" });+ }++ const delegation = await agentVaultDelegationDAL.findForIdentity({ projectId, identityId: ctx.actorId });+ if (!delegation) {+ throw new ForbiddenRequestError({+ message:+ "This machine identity isn't allowed to start sessions on behalf of users. An Agent Vault admin can allow it by setting its delegation under Access Control."+ });+ }+ return delegation;+};++// A user who doesn't exist reads exactly like one the delegation doesn't cover.+export const resolveOnBehalfOfUser = async (+ { agentVaultDelegationDAL, userDAL, orgDAL, permissionService, membershipDAL }: TOnBehalfOfDeps,+ {+ projectId,+ ctx,+ onBehalfOf,+ delegation+ }: {+ projectId: string;+ ctx: TGenericPermission;+ onBehalfOf: TOnBehalfOfUser;+ delegation: Awaited<ReturnType<typeof findCallerDelegation>>;+ }+) => {+ const identifier = onBehalfOf.userId ?? onBehalfOf.userEmail ?? "";+ const notCovered = () =>+ new ForbiddenRequestError({+ message: `This machine identity can't start sessions on behalf of '${identifier}'. Check the user's ID or email, or ask an Agent Vault admin to add them to the identity's delegation.`+ });++ const user = await userDAL.findOne(+ onBehalfOf.userId ? { id: onBehalfOf.userId, isGhost: false } : { username: onBehalfOf.userEmail, isGhost: false }+ );+ if (!user) throw notCovered();++ // Resolve refuses a session whose actor isn't an active, accepted org member, so mint does too.+ const orgMembership = await orgDAL.findEffectiveOrgMembership({+ actorType: ActorType.USER,+ actorId: user.id,+ orgId: ctx.actorOrgId,+ status: OrgMembershipStatus.Accepted+ });+ if (!orgMembership?.isActive) throw notCovered();++ if (!(await agentVaultDelegationDAL.coversUser({ delegation, userId: user.id }))) throw notCovered();++ // The user's own role and grants decide what they reach. actorAuthMethod is null as in resolve: the session row+ // stores no auth method.+ const userCtx: TGenericPermission = {+ actor: ActorType.USER,+ actorId: user.id,+ actorOrgId: ctx.actorOrgId,+ actorAuthMethod: null+ };+ let reachability: Awaited<ReturnType<typeof getAgentVaultReachability>>;+ try {+ reachability = await getAgentVaultReachability({ permissionService, membershipDAL }, { projectId, ctx: userCtx });+ } catch (error) {+ if (error instanceof ForbiddenRequestError && error.name === "ProjectMembershipNotFound") {+ throw new BadRequestError({+ message: `'${identifier}' doesn't have access to Agent Vault, so no session can be started on their behalf. An Agent Vault admin can add them under Access Control.`+ });+ }+ throw error;+ }+ // Not thrown through CASL: the denial would be recorded against the identity making the request.+ if (+ !reachability.permission.can(+ ProjectPermissionAgentVaultSessionActions.Create,+ ProjectPermissionSub.AgentVaultSessions+ )+ ) {+ throw new ForbiddenRequestError({+ message: `'${identifier}' can't start Agent Vault sessions, so no session can be started on their behalf.`+ });+ }++ return { user, identifier, accessBundleIds: reachability.accessBundleIds };+};diff --cc backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.tsindex 1dfd1bb11f,26f9e084df..5ac1aed17b--- a/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts+++ b/backend/src/ee/services/agent-vault-proxy/agent-vault-proxy-service.ts@@@ -23,26 -23,8 +23,9 @@@ import { KmsDataKey } from "@app/servicimport { TMembershipDALFactory } from "@app/services/membership/membership-dal";import { TOrgDALFactory } from "@app/services/org/org-dal";- import { isUniqueViolation } from "../agent-vault/agent-vault-db-error-fns";- import {- AgentVaultCredentialType,- AgentVaultOauthStatus,- AgentVaultServiceType,- AgentVaultTrafficPolicy,- AgentVaultVariableReferenceField,- TAgentVaultMemberProvidedField- } from "../agent-vault/agent-vault-enums";- import { TAgentVaultOwner } from "../agent-vault/agent-vault-owner-fns";- import {- findReachableAccessBundleIds,- intersectAccessBundleIds,- liveGroupIdsFrom- } from "../agent-vault/agent-vault-permission";- import { getServiceServerUrl } from "../agent-vault/agent-vault-service-type-fns";- import { expandStoredVariableReferences, findStoredVariableIds } from "../agent-vault/agent-vault-variable-fns";import { TAgentVaultServiceCustomHeaderDALFactory } from "../agent-vault-access-bundle/agent-vault-service-custom-header-dal";import { TAgentVaultServiceSubstitutionDALFactory } from "../agent-vault-access-bundle/agent-vault-service-substitution-dal";+import { TAgentVaultDelegationDALFactory } from "../agent-vault-delegation/agent-vault-delegation-dal";import {AGENT_VAULT_SERVICE_MOVED_MESSAGE,TAgentVaultOauthServiceFactory@@@ -59,7 -39,22 +40,26 @@@ import} from "../agent-vault-session-log/agent-vault-session-log-license-fns";import { openSessionLogKey } from "../agent-vault-session-log/agent-vault-session-log-secrets";import { getEffectiveSessionLogConfig } from "../agent-vault-session-log/agent-vault-session-log-storage-fns";+ import { TAgentVaultSessionDALFactory } from "../agent-vault-session/agent-vault-session-dal";+ import { hashSessionToken } from "../agent-vault-session/agent-vault-session-fns";import { TAgentVaultVariableDALFactory } from "../agent-vault-variable/agent-vault-variable-dal";+ import { isUniqueViolation } from "../agent-vault/agent-vault-db-error-fns";+ import {+ AgentVaultCredentialType,+ AgentVaultOauthStatus,+ AgentVaultServiceType,+ AgentVaultTrafficPolicy,+ AgentVaultVariableReferenceField,+ TAgentVaultMemberProvidedField+ } from "../agent-vault/agent-vault-enums";+ import { TAgentVaultOwner } from "../agent-vault/agent-vault-owner-fns";-import { findReachableAccessBundleIds, liveGroupIdsFrom } from "../agent-vault/agent-vault-permission";++import {++ findReachableAccessBundleIds,++ intersectAccessBundleIds,++ liveGroupIdsFrom++} from "../agent-vault/agent-vault-permission";+ import { getServiceServerUrl } from "../agent-vault/agent-vault-service-type-fns";+ import { expandStoredVariableReferences, findStoredVariableIds } from "../agent-vault/agent-vault-variable-fns";import {mintAgentVaultProxyJwt,RESOURCE_TYPE_AGENT_VAULT_PROXYdiff --cc backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-service.tsindex faf9bae0ea,7290e2db1a..c8338ac4cd--- a/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-service.ts+++ b/backend/src/ee/services/agent-vault-session-log/agent-vault-session-log-service.ts@@@ -24,10 -24,10 +24,10 @@@ import { isS3DirectoryBucket } from "@aimport { TObjectStorageServiceFactory } from "@app/services/object-storage/object-storage-service";import { ObjectStorageType } from "@app/services/object-storage/object-storage-types";- import { getAgentVaultPermission } from "../agent-vault/agent-vault-permission";import { TAgentVaultProxyDALFactory } from "../agent-vault-proxy/agent-vault-proxy-dal";import { TAgentVaultSessionDALFactory } from "../agent-vault-session/agent-vault-session-dal";-import { isOwnerlessSession, isSessionOwnedBy } from "../agent-vault-session/agent-vault-session-fns";+import { isOrphanedSession, isSessionOwnedBy } from "../agent-vault-session/agent-vault-session-fns";+ import { getAgentVaultPermission } from "../agent-vault/agent-vault-permission";import { TAgentVaultSessionLogConfigDALFactory } from "./agent-vault-session-log-config-dal";import {AGENT_VAULT_SESSION_LOG_CHUNK_ID_TIME_TOLERANCE_MS,diff --cc backend/src/ee/services/agent-vault-session/agent-vault-session-service.tsindex 47adf864c5,5e9e59bb68..1c0c1f9d09--- a/backend/src/ee/services/agent-vault-session/agent-vault-session-service.ts+++ b/backend/src/ee/services/agent-vault-session/agent-vault-session-service.ts@@@ -11,15 -11,11 +11,15 @@@ import { ms } from "@app/lib/ms"import { ActorType } from "@app/services/auth/auth-type";import { TKmsServiceFactory } from "@app/services/kms/kms-service";import { TMembershipDALFactory } from "@app/services/membership/membership-dal";+import { TOrgDALFactory } from "@app/services/org/org-dal";+import { TUserDALFactory } from "@app/services/user/user-dal";- import { AgentVaultMemberType, AgentVaultSessionScope } from "../agent-vault/agent-vault-enums";- import { getAgentVaultPermission, getAgentVaultReachability } from "../agent-vault/agent-vault-permission";import { TAgentVaultAccessBundleDALFactory } from "../agent-vault-access-bundle/agent-vault-access-bundle-dal";+import { TAgentVaultDelegationDALFactory } from "../agent-vault-delegation/agent-vault-delegation-dal";+import { findCallerDelegation, resolveOnBehalfOfUser } from "../agent-vault-delegation/agent-vault-on-behalf-of-fns";import { generateSessionLogKey, wrapSessionLogKey } from "../agent-vault-session-log/agent-vault-session-log-secrets";+ import { AgentVaultMemberType, AgentVaultSessionScope } from "../agent-vault/agent-vault-enums";+ import { getAgentVaultPermission, getAgentVaultReachability } from "../agent-vault/agent-vault-permission";import { TAgentVaultSessionAccessBundleDALFactory } from "./agent-vault-session-access-bundle-dal";import { TAgentVaultSessionDALFactory, TAgentVaultSessionListRow } from "./agent-vault-session-dal";import { deriveSessionStatus, generateSessionToken } from "./agent-vault-session-fns";