mirror of
https://github.com/awatertrevi/infisical.git
synced 2026-10-18 02:56:57 +00:00
Merge branch 'main' into fix-approval-policy-org-check
This commit is contained in:
Vendored
+4
@@ -1,7 +1,9 @@
|
||||
import { FastifyInstance, RawReplyDefaultExpression, RawRequestDefaultExpression, RawServerDefault } from "fastify";
|
||||
|
||||
import { THsmServiceFactory } from "@app/ee/services/hsm/hsm-service";
|
||||
import { CustomLogger } from "@app/lib/logger/logger";
|
||||
import { ZodTypeProvider } from "@app/server/plugins/fastify-zod";
|
||||
import { TKmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";
|
||||
import { TSuperAdminDALFactory } from "@app/services/super-admin/super-admin-dal";
|
||||
|
||||
declare global {
|
||||
@@ -16,5 +18,7 @@ declare global {
|
||||
// used only for testing
|
||||
const testServer: FastifyZodProvider;
|
||||
const testSuperAdminDAL: TSuperAdminDALFactory;
|
||||
const testKmsRootConfigDAL: TKmsRootConfigDALFactory;
|
||||
const testHsmService: THsmServiceFactory;
|
||||
const jwtAuthToken: string;
|
||||
}
|
||||
|
||||
Vendored
+33
-10
@@ -20,18 +20,19 @@ import { TGatewayV2ServiceFactory } from "@app/ee/services/gateway-v2/gateway-v2
|
||||
import { TGithubOrgSyncServiceFactory } from "@app/ee/services/github-org-sync/github-org-sync-service";
|
||||
import { TGroupServiceFactory } from "@app/ee/services/group/group-service";
|
||||
import { TIdentityAuthTemplateServiceFactory } from "@app/ee/services/identity-auth-template";
|
||||
import { TIdentityProjectAdditionalPrivilegeServiceFactory } from "@app/ee/services/identity-project-additional-privilege/identity-project-additional-privilege-service";
|
||||
import { TIdentityProjectAdditionalPrivilegeV2ServiceFactory } from "@app/ee/services/identity-project-additional-privilege-v2/identity-project-additional-privilege-v2-service";
|
||||
import { TKmipClientDALFactory } from "@app/ee/services/kmip/kmip-client-dal";
|
||||
import { TKmipOperationServiceFactory } from "@app/ee/services/kmip/kmip-operation-service";
|
||||
import { TKmipServiceFactory } from "@app/ee/services/kmip/kmip-service";
|
||||
import { TLdapConfigServiceFactory } from "@app/ee/services/ldap-config/ldap-config-service";
|
||||
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
|
||||
import { TOidcConfigServiceFactory } from "@app/ee/services/oidc/oidc-config-service";
|
||||
import { TPamAccountServiceFactory } from "@app/ee/services/pam-account/pam-account-service";
|
||||
import { TPamFolderServiceFactory } from "@app/ee/services/pam-folder/pam-folder-service";
|
||||
import { TPamResourceServiceFactory } from "@app/ee/services/pam-resource/pam-resource-service";
|
||||
import { TPamSessionServiceFactory } from "@app/ee/services/pam-session/pam-session-service";
|
||||
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
|
||||
import { TPitServiceFactory } from "@app/ee/services/pit/pit-service";
|
||||
import { TProjectTemplateServiceFactory } from "@app/ee/services/project-template/project-template-types";
|
||||
import { TProjectUserAdditionalPrivilegeServiceFactory } from "@app/ee/services/project-user-additional-privilege/project-user-additional-privilege-types";
|
||||
import { RateLimitConfiguration, TRateLimitServiceFactory } from "@app/ee/services/rate-limit/rate-limit-types";
|
||||
import { TRelayServiceFactory } from "@app/ee/services/relay/relay-service";
|
||||
import { TSamlConfigServiceFactory } from "@app/ee/services/saml-config/saml-config-types";
|
||||
@@ -47,8 +48,10 @@ import { TSshCertificateAuthorityServiceFactory } from "@app/ee/services/ssh/ssh
|
||||
import { TSshCertificateTemplateServiceFactory } from "@app/ee/services/ssh-certificate-template/ssh-certificate-template-service";
|
||||
import { TSshHostServiceFactory } from "@app/ee/services/ssh-host/ssh-host-service";
|
||||
import { TSshHostGroupServiceFactory } from "@app/ee/services/ssh-host-group/ssh-host-group-service";
|
||||
import { TSubOrgServiceFactory } from "@app/ee/services/sub-org/sub-org-service";
|
||||
import { TTrustedIpServiceFactory } from "@app/ee/services/trusted-ip/trusted-ip-types";
|
||||
import { TAuthMode } from "@app/server/plugins/auth/inject-identity";
|
||||
import { TAdditionalPrivilegeServiceFactory } from "@app/services/additional-privilege/additional-privilege-service";
|
||||
import { TApiKeyServiceFactory } from "@app/services/api-key/api-key-service";
|
||||
import { TAppConnectionServiceFactory } from "@app/services/app-connection/app-connection-service";
|
||||
import { TAuthLoginFactory } from "@app/services/auth/auth-login-service";
|
||||
@@ -59,8 +62,13 @@ import { TAuthTokenServiceFactory } from "@app/services/auth-token/auth-token-se
|
||||
import { TCertificateServiceFactory } from "@app/services/certificate/certificate-service";
|
||||
import { TCertificateAuthorityServiceFactory } from "@app/services/certificate-authority/certificate-authority-service";
|
||||
import { TInternalCertificateAuthorityServiceFactory } from "@app/services/certificate-authority/internal/internal-certificate-authority-service";
|
||||
import { TCertificateEstV3ServiceFactory } from "@app/services/certificate-est-v3/certificate-est-v3-service";
|
||||
import { TCertificateProfileServiceFactory } from "@app/services/certificate-profile/certificate-profile-service";
|
||||
import { TCertificateTemplateServiceFactory } from "@app/services/certificate-template/certificate-template-service";
|
||||
import { TCertificateTemplateV2ServiceFactory } from "@app/services/certificate-template-v2/certificate-template-v2-service";
|
||||
import { TCertificateV3ServiceFactory } from "@app/services/certificate-v3/certificate-v3-service";
|
||||
import { TCmekServiceFactory } from "@app/services/cmek/cmek-service";
|
||||
import { TConvertorServiceFactory } from "@app/services/convertor/convertor-service";
|
||||
import { TExternalGroupOrgRoleMappingServiceFactory } from "@app/services/external-group-org-role-mapping/external-group-org-role-mapping-service";
|
||||
import { TExternalMigrationServiceFactory } from "@app/services/external-migration/external-migration-service";
|
||||
import { TFolderCommitServiceFactory } from "@app/services/folder-commit/folder-commit-service";
|
||||
@@ -84,10 +92,12 @@ import { TIdentityTokenAuthServiceFactory } from "@app/services/identity-token-a
|
||||
import { TIdentityUaServiceFactory } from "@app/services/identity-ua/identity-ua-service";
|
||||
import { TIntegrationServiceFactory } from "@app/services/integration/integration-service";
|
||||
import { TIntegrationAuthServiceFactory } from "@app/services/integration-auth/integration-auth-service";
|
||||
import { TMembershipGroupServiceFactory } from "@app/services/membership-group/membership-group-service";
|
||||
import { TMembershipIdentityServiceFactory } from "@app/services/membership-identity/membership-identity-service";
|
||||
import { TMembershipUserServiceFactory } from "@app/services/membership-user/membership-user-service";
|
||||
import { TMicrosoftTeamsServiceFactory } from "@app/services/microsoft-teams/microsoft-teams-service";
|
||||
import { TNotificationServiceFactory } from "@app/services/notification/notification-service";
|
||||
import { TOfflineUsageReportServiceFactory } from "@app/services/offline-usage-report/offline-usage-report-service";
|
||||
import { TOrgRoleServiceFactory } from "@app/services/org/org-role-service";
|
||||
import { TOrgServiceFactory } from "@app/services/org/org-service";
|
||||
import { TOrgAdminServiceFactory } from "@app/services/org-admin/org-admin-service";
|
||||
import { TPkiAlertServiceFactory } from "@app/services/pki-alert/pki-alert-service";
|
||||
@@ -100,8 +110,8 @@ import { TProjectBotServiceFactory } from "@app/services/project-bot/project-bot
|
||||
import { TProjectEnvServiceFactory } from "@app/services/project-env/project-env-service";
|
||||
import { TProjectKeyServiceFactory } from "@app/services/project-key/project-key-service";
|
||||
import { TProjectMembershipServiceFactory } from "@app/services/project-membership/project-membership-service";
|
||||
import { TProjectRoleServiceFactory } from "@app/services/project-role/project-role-service";
|
||||
import { TReminderServiceFactory } from "@app/services/reminder/reminder-types";
|
||||
import { TRoleServiceFactory } from "@app/services/role/role-service";
|
||||
import { TSecretServiceFactory } from "@app/services/secret/secret-service";
|
||||
import { TSecretBlindIndexServiceFactory } from "@app/services/secret-blind-index/secret-blind-index-service";
|
||||
import { TSecretFolderServiceFactory } from "@app/services/secret-folder/secret-folder-service";
|
||||
@@ -173,6 +183,8 @@ declare module "fastify" {
|
||||
type: ActorType;
|
||||
id: string;
|
||||
orgId: string;
|
||||
parentOrgId: string;
|
||||
rootOrgId: string;
|
||||
};
|
||||
rateLimits: RateLimitConfiguration;
|
||||
// passport data
|
||||
@@ -209,7 +221,6 @@ declare module "fastify" {
|
||||
authToken: TAuthTokenServiceFactory;
|
||||
permission: TPermissionServiceFactory;
|
||||
org: TOrgServiceFactory;
|
||||
orgRole: TOrgRoleServiceFactory;
|
||||
oidc: TOidcConfigServiceFactory;
|
||||
superAdmin: TSuperAdminServiceFactory;
|
||||
user: TUserServiceFactory;
|
||||
@@ -221,7 +232,6 @@ declare module "fastify" {
|
||||
projectMembership: TProjectMembershipServiceFactory;
|
||||
projectEnv: TProjectEnvServiceFactory;
|
||||
projectKey: TProjectKeyServiceFactory;
|
||||
projectRole: TProjectRoleServiceFactory;
|
||||
secret: TSecretServiceFactory;
|
||||
secretReplication: TSecretReplicationServiceFactory;
|
||||
secretTag: TSecretTagServiceFactory;
|
||||
@@ -259,7 +269,10 @@ declare module "fastify" {
|
||||
auditLog: TAuditLogServiceFactory;
|
||||
auditLogStream: TAuditLogStreamServiceFactory;
|
||||
certificate: TCertificateServiceFactory;
|
||||
certificateV3: TCertificateV3ServiceFactory;
|
||||
certificateTemplate: TCertificateTemplateServiceFactory;
|
||||
certificateTemplateV2: TCertificateTemplateV2ServiceFactory;
|
||||
certificateProfile: TCertificateProfileServiceFactory;
|
||||
sshCertificateAuthority: TSshCertificateAuthorityServiceFactory;
|
||||
sshCertificateTemplate: TSshCertificateTemplateServiceFactory;
|
||||
sshHost: TSshHostServiceFactory;
|
||||
@@ -267,6 +280,7 @@ declare module "fastify" {
|
||||
certificateAuthority: TCertificateAuthorityServiceFactory;
|
||||
certificateAuthorityCrl: TCertificateAuthorityCrlServiceFactory;
|
||||
certificateEst: TCertificateEstServiceFactory;
|
||||
certificateEstV3: TCertificateEstV3ServiceFactory;
|
||||
pkiCollection: TPkiCollectionServiceFactory;
|
||||
pkiSubscriber: TPkiSubscriberServiceFactory;
|
||||
pkiSync: TPkiSyncServiceFactory;
|
||||
@@ -277,9 +291,6 @@ declare module "fastify" {
|
||||
telemetry: TTelemetryServiceFactory;
|
||||
dynamicSecret: TDynamicSecretServiceFactory;
|
||||
dynamicSecretLease: TDynamicSecretLeaseServiceFactory;
|
||||
projectUserAdditionalPrivilege: TProjectUserAdditionalPrivilegeServiceFactory;
|
||||
identityProjectAdditionalPrivilege: TIdentityProjectAdditionalPrivilegeServiceFactory;
|
||||
identityProjectAdditionalPrivilegeV2: TIdentityProjectAdditionalPrivilegeV2ServiceFactory;
|
||||
secretSharing: TSecretSharingServiceFactory;
|
||||
rateLimit: TRateLimitServiceFactory;
|
||||
userEngagement: TUserEngagementServiceFactory;
|
||||
@@ -315,7 +326,19 @@ declare module "fastify" {
|
||||
identityAuthTemplate: TIdentityAuthTemplateServiceFactory;
|
||||
notification: TNotificationServiceFactory;
|
||||
offlineUsageReport: TOfflineUsageReportServiceFactory;
|
||||
pamFolder: TPamFolderServiceFactory;
|
||||
pamResource: TPamResourceServiceFactory;
|
||||
pamAccount: TPamAccountServiceFactory;
|
||||
pamSession: TPamSessionServiceFactory;
|
||||
upgradePath: TUpgradePathService;
|
||||
|
||||
membershipUser: TMembershipUserServiceFactory;
|
||||
membershipIdentity: TMembershipIdentityServiceFactory;
|
||||
membershipGroup: TMembershipGroupServiceFactory;
|
||||
additionalPrivilege: TAdditionalPrivilegeServiceFactory;
|
||||
role: TRoleServiceFactory;
|
||||
convertor: TConvertorServiceFactory;
|
||||
subOrganization: TSubOrgServiceFactory;
|
||||
};
|
||||
// this is exclusive use for middlewares in which we need to inject data
|
||||
// everywhere else access using service layer
|
||||
|
||||
Vendored
+77
@@ -17,6 +17,9 @@ import {
|
||||
TAccessApprovalRequestsReviewersInsert,
|
||||
TAccessApprovalRequestsReviewersUpdate,
|
||||
TAccessApprovalRequestsUpdate,
|
||||
TAdditionalPrivileges,
|
||||
TAdditionalPrivilegesInsert,
|
||||
TAdditionalPrivilegesUpdate,
|
||||
TApiKeys,
|
||||
TApiKeysInsert,
|
||||
TApiKeysUpdate,
|
||||
@@ -227,6 +230,15 @@ import {
|
||||
TLdapGroupMaps,
|
||||
TLdapGroupMapsInsert,
|
||||
TLdapGroupMapsUpdate,
|
||||
TMembershipRoles,
|
||||
TMembershipRolesInsert,
|
||||
TMembershipRolesUpdate,
|
||||
TMemberships,
|
||||
TMembershipsInsert,
|
||||
TMembershipsUpdate,
|
||||
TNamespaces,
|
||||
TNamespacesInsert,
|
||||
TNamespacesUpdate,
|
||||
TOidcConfigs,
|
||||
TOidcConfigsInsert,
|
||||
TOidcConfigsUpdate,
|
||||
@@ -254,12 +266,24 @@ import {
|
||||
TPkiAlerts,
|
||||
TPkiAlertsInsert,
|
||||
TPkiAlertsUpdate,
|
||||
TPkiApiEnrollmentConfigs,
|
||||
TPkiApiEnrollmentConfigsInsert,
|
||||
TPkiApiEnrollmentConfigsUpdate,
|
||||
TPkiCertificateProfiles,
|
||||
TPkiCertificateProfilesInsert,
|
||||
TPkiCertificateProfilesUpdate,
|
||||
TPkiCertificateTemplatesV2,
|
||||
TPkiCertificateTemplatesV2Insert,
|
||||
TPkiCertificateTemplatesV2Update,
|
||||
TPkiCollectionItems,
|
||||
TPkiCollectionItemsInsert,
|
||||
TPkiCollectionItemsUpdate,
|
||||
TPkiCollections,
|
||||
TPkiCollectionsInsert,
|
||||
TPkiCollectionsUpdate,
|
||||
TPkiEstEnrollmentConfigs,
|
||||
TPkiEstEnrollmentConfigsInsert,
|
||||
TPkiEstEnrollmentConfigsUpdate,
|
||||
TPkiSubscribers,
|
||||
TPkiSubscribersInsert,
|
||||
TPkiSubscribersUpdate,
|
||||
@@ -314,6 +338,9 @@ import {
|
||||
TResourceMetadata,
|
||||
TResourceMetadataInsert,
|
||||
TResourceMetadataUpdate,
|
||||
TRoles,
|
||||
TRolesInsert,
|
||||
TRolesUpdate,
|
||||
TSamlConfigs,
|
||||
TSamlConfigsInsert,
|
||||
TSamlConfigsUpdate,
|
||||
@@ -503,6 +530,9 @@ import {
|
||||
TUsers,
|
||||
TUsersInsert,
|
||||
TUsersUpdate,
|
||||
TVaultExternalMigrationConfigs,
|
||||
TVaultExternalMigrationConfigsInsert,
|
||||
TVaultExternalMigrationConfigsUpdate,
|
||||
TWebhooks,
|
||||
TWebhooksInsert,
|
||||
TWebhooksUpdate,
|
||||
@@ -530,6 +560,10 @@ import {
|
||||
TMicrosoftTeamsIntegrationsInsert,
|
||||
TMicrosoftTeamsIntegrationsUpdate
|
||||
} from "@app/db/schemas/microsoft-teams-integrations";
|
||||
import { TPamAccounts, TPamAccountsInsert, TPamAccountsUpdate } from "@app/db/schemas/pam-accounts";
|
||||
import { TPamFolders, TPamFoldersInsert, TPamFoldersUpdate } from "@app/db/schemas/pam-folders";
|
||||
import { TPamResources, TPamResourcesInsert, TPamResourcesUpdate } from "@app/db/schemas/pam-resources";
|
||||
import { TPamSessions, TPamSessionsInsert, TPamSessionsUpdate } from "@app/db/schemas/pam-sessions";
|
||||
import {
|
||||
TProjectMicrosoftTeamsConfigs,
|
||||
TProjectMicrosoftTeamsConfigsInsert,
|
||||
@@ -652,6 +686,26 @@ declare module "knex/types/tables" {
|
||||
TCertificateTemplatesInsert,
|
||||
TCertificateTemplatesUpdate
|
||||
>;
|
||||
[TableName.PkiCertificateTemplateV2]: KnexOriginal.CompositeTableType<
|
||||
TPkiCertificateTemplatesV2,
|
||||
TPkiCertificateTemplatesV2Insert,
|
||||
TPkiCertificateTemplatesV2Update
|
||||
>;
|
||||
[TableName.PkiCertificateProfile]: KnexOriginal.CompositeTableType<
|
||||
TPkiCertificateProfiles,
|
||||
TPkiCertificateProfilesInsert,
|
||||
TPkiCertificateProfilesUpdate
|
||||
>;
|
||||
[TableName.PkiEstEnrollmentConfig]: KnexOriginal.CompositeTableType<
|
||||
TPkiEstEnrollmentConfigs,
|
||||
TPkiEstEnrollmentConfigsInsert,
|
||||
TPkiEstEnrollmentConfigsUpdate
|
||||
>;
|
||||
[TableName.PkiApiEnrollmentConfig]: KnexOriginal.CompositeTableType<
|
||||
TPkiApiEnrollmentConfigs,
|
||||
TPkiApiEnrollmentConfigsInsert,
|
||||
TPkiApiEnrollmentConfigsUpdate
|
||||
>;
|
||||
[TableName.CertificateTemplateEstConfig]: KnexOriginal.CompositeTableType<
|
||||
TCertificateTemplateEstConfigs,
|
||||
TCertificateTemplateEstConfigsInsert,
|
||||
@@ -1308,5 +1362,28 @@ declare module "knex/types/tables" {
|
||||
TKeyValueStoreInsert,
|
||||
TKeyValueStoreUpdate
|
||||
>;
|
||||
[TableName.PamFolder]: KnexOriginal.CompositeTableType<TPamFolders, TPamFoldersInsert, TPamFoldersUpdate>;
|
||||
[TableName.PamResource]: KnexOriginal.CompositeTableType<TPamResources, TPamResourcesInsert, TPamResourcesUpdate>;
|
||||
[TableName.PamAccount]: KnexOriginal.CompositeTableType<TPamAccounts, TPamAccountsInsert, TPamAccountsUpdate>;
|
||||
[TableName.PamSession]: KnexOriginal.CompositeTableType<TPamSessions, TPamSessionsInsert, TPamSessionsUpdate>;
|
||||
|
||||
[TableName.Namespace]: KnexOriginal.CompositeTableType<TNamespaces, TNamespacesInsert, TNamespacesUpdate>;
|
||||
[TableName.Membership]: KnexOriginal.CompositeTableType<TMemberships, TMembershipsInsert, TMembershipsUpdate>;
|
||||
[TableName.MembershipRole]: KnexOriginal.CompositeTableType<
|
||||
TMembershipRoles,
|
||||
TMembershipRolesInsert,
|
||||
TMembershipRolesUpdate
|
||||
>;
|
||||
[TableName.Role]: KnexOriginal.CompositeTableType<TRoles, TRolesInsert, TRolesUpdate>;
|
||||
[TableName.AdditionalPrivilege]: KnexOriginal.CompositeTableType<
|
||||
TAdditionalPrivileges,
|
||||
TAdditionalPrivilegesInsert,
|
||||
TAdditionalPrivilegesUpdate
|
||||
>;
|
||||
[TableName.VaultExternalMigrationConfig]: KnexOriginal.CompositeTableType<
|
||||
TVaultExternalMigrationConfigs,
|
||||
TVaultExternalMigrationConfigsInsert,
|
||||
TVaultExternalMigrationConfigsUpdate
|
||||
>;
|
||||
}
|
||||
}
|
||||
|
||||
+41
-27
@@ -1,5 +1,29 @@
|
||||
import knex, { Knex } from "knex";
|
||||
|
||||
const parseSslConfig = (dbConnectionUri: string, dbRootCert?: string) => {
|
||||
let modifiedDbConnectionUri = dbConnectionUri;
|
||||
let sslConfig: { rejectUnauthorized: boolean; ca: string } | boolean = dbRootCert
|
||||
? { rejectUnauthorized: true, ca: Buffer.from(dbRootCert, "base64").toString("ascii") }
|
||||
: false;
|
||||
|
||||
if (dbRootCert) {
|
||||
const url = new URL(dbConnectionUri);
|
||||
const sslMode = url.searchParams.get("sslmode");
|
||||
|
||||
if (sslMode && sslMode !== "disable") {
|
||||
url.searchParams.delete("sslmode");
|
||||
modifiedDbConnectionUri = url.toString();
|
||||
|
||||
sslConfig = {
|
||||
rejectUnauthorized: ["verify-ca", "verify-full"].includes(sslMode),
|
||||
ca: Buffer.from(dbRootCert, "base64").toString("ascii")
|
||||
};
|
||||
}
|
||||
}
|
||||
|
||||
return { modifiedDbConnectionUri, sslConfig };
|
||||
};
|
||||
|
||||
export type TDbClient = Knex;
|
||||
export const initDbConnection = ({
|
||||
dbConnectionUri,
|
||||
@@ -32,23 +56,18 @@ export const initDbConnection = ({
|
||||
return selectedReplica;
|
||||
});
|
||||
|
||||
const { modifiedDbConnectionUri, sslConfig } = parseSslConfig(dbConnectionUri, dbRootCert);
|
||||
|
||||
db = knex({
|
||||
client: "pg",
|
||||
connection: {
|
||||
connectionString: dbConnectionUri,
|
||||
connectionString: modifiedDbConnectionUri,
|
||||
host: process.env.DB_HOST,
|
||||
// @ts-expect-error I have no clue why only for the port there is a type error
|
||||
// eslint-disable-next-line
|
||||
port: process.env.DB_PORT,
|
||||
port: process.env.DB_PORT ? parseInt(process.env.DB_PORT, 10) : undefined,
|
||||
user: process.env.DB_USER,
|
||||
database: process.env.DB_NAME,
|
||||
password: process.env.DB_PASSWORD,
|
||||
ssl: dbRootCert
|
||||
? {
|
||||
rejectUnauthorized: true,
|
||||
ca: Buffer.from(dbRootCert, "base64").toString("ascii")
|
||||
}
|
||||
: false
|
||||
ssl: sslConfig
|
||||
},
|
||||
// https://knexjs.org/guide/#pool
|
||||
pool: { min: 0, max: 10 },
|
||||
@@ -59,16 +78,16 @@ export const initDbConnection = ({
|
||||
|
||||
readReplicaDbs = readReplicas.map((el) => {
|
||||
const replicaDbCertificate = el.dbRootCert || dbRootCert;
|
||||
const { modifiedDbConnectionUri: replicaUri, sslConfig: replicaSslConfig } = parseSslConfig(
|
||||
el.dbConnectionUri,
|
||||
replicaDbCertificate
|
||||
);
|
||||
|
||||
return knex({
|
||||
client: "pg",
|
||||
connection: {
|
||||
connectionString: el.dbConnectionUri,
|
||||
ssl: replicaDbCertificate
|
||||
? {
|
||||
rejectUnauthorized: true,
|
||||
ca: Buffer.from(replicaDbCertificate, "base64").toString("ascii")
|
||||
}
|
||||
: false
|
||||
connectionString: replicaUri,
|
||||
ssl: replicaSslConfig
|
||||
},
|
||||
migrations: {
|
||||
tableName: "infisical_migrations"
|
||||
@@ -87,26 +106,21 @@ export const initAuditLogDbConnection = ({
|
||||
dbConnectionUri: string;
|
||||
dbRootCert?: string;
|
||||
}) => {
|
||||
const { modifiedDbConnectionUri, sslConfig } = parseSslConfig(dbConnectionUri, dbRootCert);
|
||||
|
||||
// akhilmhdh: the default Knex is knex.Knex<any, any[]>. but when assigned with knex({<config>}) the value is knex.Knex<any, unknown[]>
|
||||
// this was causing issue with files like `snapshot-dal` `findRecursivelySnapshots` this i am explicitly putting the any and unknown[]
|
||||
// eslint-disable-next-line
|
||||
const db: Knex<any, unknown[]> = knex({
|
||||
client: "pg",
|
||||
connection: {
|
||||
connectionString: dbConnectionUri,
|
||||
connectionString: modifiedDbConnectionUri,
|
||||
host: process.env.AUDIT_LOGS_DB_HOST,
|
||||
// @ts-expect-error I have no clue why only for the port there is a type error
|
||||
// eslint-disable-next-line
|
||||
port: process.env.AUDIT_LOGS_DB_PORT,
|
||||
port: process.env.AUDIT_LOGS_DB_PORT ? parseInt(process.env.AUDIT_LOGS_DB_PORT, 10) : undefined,
|
||||
user: process.env.AUDIT_LOGS_DB_USER,
|
||||
database: process.env.AUDIT_LOGS_DB_NAME,
|
||||
password: process.env.AUDIT_LOGS_DB_PASSWORD,
|
||||
ssl: dbRootCert
|
||||
? {
|
||||
rejectUnauthorized: true,
|
||||
ca: Buffer.from(dbRootCert, "base64").toString("ascii")
|
||||
}
|
||||
: false
|
||||
ssl: sslConfig
|
||||
},
|
||||
migrations: {
|
||||
tableName: "infisical_migrations"
|
||||
|
||||
@@ -127,7 +127,8 @@ export async function down(knex: Knex): Promise<void> {
|
||||
});
|
||||
await knex.schema.alterTable(TableName.SecretApprovalPolicyApprover, (tb) => {
|
||||
tb.dropColumn("approverUserId");
|
||||
tb.uuid("approverId").notNullable().alter();
|
||||
// akhilmhdh: i had to comment this out and is not possible as membership is now changed in structure
|
||||
// tb.uuid("approverId").notNullable().alter();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
@@ -3,13 +3,14 @@ import { Knex } from "knex";
|
||||
import { inMemoryKeyStore } from "@app/keystore/memory";
|
||||
import { crypto } from "@app/lib/crypto/cryptography";
|
||||
import { initLogger } from "@app/lib/logger";
|
||||
import { kmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";
|
||||
import { KmsDataKey } from "@app/services/kms/kms-types";
|
||||
import { superAdminDALFactory } from "@app/services/super-admin/super-admin-dal";
|
||||
|
||||
import { SecretKeyEncoding, TableName } from "../schemas";
|
||||
import { getMigrationEnvConfig } from "./utils/env-config";
|
||||
import { getMigrationEnvConfig, getMigrationHsmConfig } from "./utils/env-config";
|
||||
import { createCircularCache } from "./utils/ring-buffer";
|
||||
import { getMigrationEncryptionServices } from "./utils/services";
|
||||
import { getMigrationEncryptionServices, getMigrationHsmService } from "./utils/services";
|
||||
|
||||
const BATCH_SIZE = 500;
|
||||
export async function up(knex: Knex): Promise<void> {
|
||||
@@ -25,10 +26,12 @@ export async function up(knex: Knex): Promise<void> {
|
||||
if (hasUrl) t.string("url").nullable().alter();
|
||||
});
|
||||
}
|
||||
|
||||
initLogger();
|
||||
|
||||
const { hsmService } = await getMigrationHsmService({ envConfig: getMigrationHsmConfig() });
|
||||
const superAdminDAL = superAdminDALFactory(knex);
|
||||
const envConfig = await getMigrationEnvConfig(superAdminDAL);
|
||||
const kmsRootConfigDAL = kmsRootConfigDALFactory(knex);
|
||||
const envConfig = await getMigrationEnvConfig(superAdminDAL, hsmService, kmsRootConfigDAL);
|
||||
|
||||
const keyStore = inMemoryKeyStore();
|
||||
const { kmsService } = await getMigrationEncryptionServices({ envConfig, keyStore, db: knex });
|
||||
|
||||
@@ -4,13 +4,14 @@ import { inMemoryKeyStore } from "@app/keystore/memory";
|
||||
import { crypto } from "@app/lib/crypto/cryptography";
|
||||
import { selectAllTableCols } from "@app/lib/knex";
|
||||
import { initLogger } from "@app/lib/logger";
|
||||
import { kmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";
|
||||
import { KmsDataKey } from "@app/services/kms/kms-types";
|
||||
import { superAdminDALFactory } from "@app/services/super-admin/super-admin-dal";
|
||||
|
||||
import { SecretKeyEncoding, TableName } from "../schemas";
|
||||
import { getMigrationEnvConfig } from "./utils/env-config";
|
||||
import { getMigrationEnvConfig, getMigrationHsmConfig } from "./utils/env-config";
|
||||
import { createCircularCache } from "./utils/ring-buffer";
|
||||
import { getMigrationEncryptionServices } from "./utils/services";
|
||||
import { getMigrationEncryptionServices, getMigrationHsmService } from "./utils/services";
|
||||
|
||||
const BATCH_SIZE = 500;
|
||||
export async function up(knex: Knex): Promise<void> {
|
||||
@@ -30,8 +31,12 @@ export async function up(knex: Knex): Promise<void> {
|
||||
}
|
||||
|
||||
initLogger();
|
||||
|
||||
const { hsmService } = await getMigrationHsmService({ envConfig: getMigrationHsmConfig() });
|
||||
|
||||
const superAdminDAL = superAdminDALFactory(knex);
|
||||
const envConfig = await getMigrationEnvConfig(superAdminDAL);
|
||||
const kmsRootConfigDAL = kmsRootConfigDALFactory(knex);
|
||||
const envConfig = await getMigrationEnvConfig(superAdminDAL, hsmService, kmsRootConfigDAL);
|
||||
|
||||
const keyStore = inMemoryKeyStore();
|
||||
const { kmsService } = await getMigrationEncryptionServices({ envConfig, keyStore, db: knex });
|
||||
|
||||
@@ -4,13 +4,14 @@ import { inMemoryKeyStore } from "@app/keystore/memory";
|
||||
import { crypto } from "@app/lib/crypto/cryptography";
|
||||
import { selectAllTableCols } from "@app/lib/knex";
|
||||
import { initLogger } from "@app/lib/logger";
|
||||
import { kmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";
|
||||
import { KmsDataKey } from "@app/services/kms/kms-types";
|
||||
import { superAdminDALFactory } from "@app/services/super-admin/super-admin-dal";
|
||||
|
||||
import { SecretKeyEncoding, TableName } from "../schemas";
|
||||
import { getMigrationEnvConfig } from "./utils/env-config";
|
||||
import { getMigrationEnvConfig, getMigrationHsmConfig } from "./utils/env-config";
|
||||
import { createCircularCache } from "./utils/ring-buffer";
|
||||
import { getMigrationEncryptionServices } from "./utils/services";
|
||||
import { getMigrationEncryptionServices, getMigrationHsmService } from "./utils/services";
|
||||
|
||||
const BATCH_SIZE = 500;
|
||||
export async function up(knex: Knex): Promise<void> {
|
||||
@@ -24,8 +25,11 @@ export async function up(knex: Knex): Promise<void> {
|
||||
}
|
||||
|
||||
initLogger();
|
||||
const { hsmService } = await getMigrationHsmService({ envConfig: getMigrationHsmConfig() });
|
||||
|
||||
const superAdminDAL = superAdminDALFactory(knex);
|
||||
const envConfig = await getMigrationEnvConfig(superAdminDAL);
|
||||
const kmsRootConfigDAL = kmsRootConfigDALFactory(knex);
|
||||
const envConfig = await getMigrationEnvConfig(superAdminDAL, hsmService, kmsRootConfigDAL);
|
||||
|
||||
const keyStore = inMemoryKeyStore();
|
||||
const { kmsService } = await getMigrationEncryptionServices({ envConfig, keyStore, db: knex });
|
||||
|
||||
@@ -4,13 +4,14 @@ import { inMemoryKeyStore } from "@app/keystore/memory";
|
||||
import { crypto, SymmetricKeySize } from "@app/lib/crypto/cryptography";
|
||||
import { selectAllTableCols } from "@app/lib/knex";
|
||||
import { initLogger } from "@app/lib/logger";
|
||||
import { kmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";
|
||||
import { KmsDataKey } from "@app/services/kms/kms-types";
|
||||
import { superAdminDALFactory } from "@app/services/super-admin/super-admin-dal";
|
||||
|
||||
import { SecretKeyEncoding, TableName, TOrgBots } from "../schemas";
|
||||
import { getMigrationEnvConfig } from "./utils/env-config";
|
||||
import { getMigrationEnvConfig, getMigrationHsmConfig } from "./utils/env-config";
|
||||
import { createCircularCache } from "./utils/ring-buffer";
|
||||
import { getMigrationEncryptionServices } from "./utils/services";
|
||||
import { getMigrationEncryptionServices, getMigrationHsmService } from "./utils/services";
|
||||
|
||||
const BATCH_SIZE = 500;
|
||||
const reencryptIdentityK8sAuth = async (knex: Knex) => {
|
||||
@@ -55,9 +56,11 @@ const reencryptIdentityK8sAuth = async (knex: Knex) => {
|
||||
}
|
||||
|
||||
initLogger();
|
||||
const superAdminDAL = superAdminDALFactory(knex);
|
||||
const envConfig = await getMigrationEnvConfig(superAdminDAL);
|
||||
const { hsmService } = await getMigrationHsmService({ envConfig: getMigrationHsmConfig() });
|
||||
|
||||
const superAdminDAL = superAdminDALFactory(knex);
|
||||
const kmsRootConfigDAL = kmsRootConfigDALFactory(knex);
|
||||
const envConfig = await getMigrationEnvConfig(superAdminDAL, hsmService, kmsRootConfigDAL);
|
||||
const keyStore = inMemoryKeyStore();
|
||||
const { kmsService } = await getMigrationEncryptionServices({ envConfig, keyStore, db: knex });
|
||||
const orgEncryptionRingBuffer =
|
||||
|
||||
@@ -4,13 +4,14 @@ import { inMemoryKeyStore } from "@app/keystore/memory";
|
||||
import { crypto, SymmetricKeySize } from "@app/lib/crypto/cryptography";
|
||||
import { selectAllTableCols } from "@app/lib/knex";
|
||||
import { initLogger } from "@app/lib/logger";
|
||||
import { kmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";
|
||||
import { KmsDataKey } from "@app/services/kms/kms-types";
|
||||
import { superAdminDALFactory } from "@app/services/super-admin/super-admin-dal";
|
||||
|
||||
import { SecretKeyEncoding, TableName, TOrgBots } from "../schemas";
|
||||
import { getMigrationEnvConfig } from "./utils/env-config";
|
||||
import { getMigrationEnvConfig, getMigrationHsmConfig } from "./utils/env-config";
|
||||
import { createCircularCache } from "./utils/ring-buffer";
|
||||
import { getMigrationEncryptionServices } from "./utils/services";
|
||||
import { getMigrationEncryptionServices, getMigrationHsmService } from "./utils/services";
|
||||
|
||||
const BATCH_SIZE = 500;
|
||||
const reencryptIdentityOidcAuth = async (knex: Knex) => {
|
||||
@@ -35,8 +36,11 @@ const reencryptIdentityOidcAuth = async (knex: Knex) => {
|
||||
}
|
||||
|
||||
initLogger();
|
||||
const { hsmService } = await getMigrationHsmService({ envConfig: getMigrationHsmConfig() });
|
||||
|
||||
const superAdminDAL = superAdminDALFactory(knex);
|
||||
const envConfig = await getMigrationEnvConfig(superAdminDAL);
|
||||
const kmsRootConfigDAL = kmsRootConfigDALFactory(knex);
|
||||
const envConfig = await getMigrationEnvConfig(superAdminDAL, hsmService, kmsRootConfigDAL);
|
||||
|
||||
const keyStore = inMemoryKeyStore();
|
||||
const { kmsService } = await getMigrationEncryptionServices({ envConfig, keyStore, db: knex });
|
||||
|
||||
@@ -4,16 +4,18 @@ import { inMemoryKeyStore } from "@app/keystore/memory";
|
||||
import { crypto, SymmetricKeySize } from "@app/lib/crypto/cryptography";
|
||||
import { selectAllTableCols } from "@app/lib/knex";
|
||||
import { initLogger } from "@app/lib/logger";
|
||||
import { kmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";
|
||||
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
|
||||
import { KmsDataKey } from "@app/services/kms/kms-types";
|
||||
import { superAdminDALFactory } from "@app/services/super-admin/super-admin-dal";
|
||||
|
||||
import { SecretKeyEncoding, TableName } from "../schemas";
|
||||
import { getMigrationEnvConfig } from "./utils/env-config";
|
||||
import { getMigrationEnvConfig, getMigrationHsmConfig } from "./utils/env-config";
|
||||
import { createCircularCache } from "./utils/ring-buffer";
|
||||
import { getMigrationEncryptionServices } from "./utils/services";
|
||||
import { getMigrationEncryptionServices, getMigrationHsmService } from "./utils/services";
|
||||
|
||||
const BATCH_SIZE = 500;
|
||||
const reencryptSamlConfig = async (knex: Knex) => {
|
||||
const reencryptSamlConfig = async (knex: Knex, kmsService: TKmsServiceFactory) => {
|
||||
const hasEncryptedEntrypointColumn = await knex.schema.hasColumn(TableName.SamlConfig, "encryptedSamlEntryPoint");
|
||||
const hasEncryptedIssuerColumn = await knex.schema.hasColumn(TableName.SamlConfig, "encryptedSamlIssuer");
|
||||
const hasEncryptedCertificateColumn = await knex.schema.hasColumn(TableName.SamlConfig, "encryptedSamlCertificate");
|
||||
@@ -28,10 +30,6 @@ const reencryptSamlConfig = async (knex: Knex) => {
|
||||
}
|
||||
|
||||
initLogger();
|
||||
const superAdminDAL = superAdminDALFactory(knex);
|
||||
const envConfig = await getMigrationEnvConfig(superAdminDAL);
|
||||
const keyStore = inMemoryKeyStore();
|
||||
const { kmsService } = await getMigrationEncryptionServices({ envConfig, keyStore, db: knex });
|
||||
const orgEncryptionRingBuffer =
|
||||
createCircularCache<Awaited<ReturnType<(typeof kmsService)["createCipherPairWithDataKey"]>>>(25);
|
||||
|
||||
@@ -159,7 +157,7 @@ const reencryptSamlConfig = async (knex: Knex) => {
|
||||
}
|
||||
};
|
||||
|
||||
const reencryptLdapConfig = async (knex: Knex) => {
|
||||
const reencryptLdapConfig = async (knex: Knex, kmsService: TKmsServiceFactory) => {
|
||||
const hasEncryptedLdapBindDNColum = await knex.schema.hasColumn(TableName.LdapConfig, "encryptedLdapBindDN");
|
||||
const hasEncryptedLdapBindPassColumn = await knex.schema.hasColumn(TableName.LdapConfig, "encryptedLdapBindPass");
|
||||
const hasEncryptedCertificateColumn = await knex.schema.hasColumn(TableName.LdapConfig, "encryptedLdapCaCertificate");
|
||||
@@ -194,10 +192,6 @@ const reencryptLdapConfig = async (knex: Knex) => {
|
||||
}
|
||||
|
||||
initLogger();
|
||||
const superAdminDAL = superAdminDALFactory(knex);
|
||||
const envConfig = await getMigrationEnvConfig(superAdminDAL);
|
||||
const keyStore = inMemoryKeyStore();
|
||||
const { kmsService } = await getMigrationEncryptionServices({ envConfig, keyStore, db: knex });
|
||||
const orgEncryptionRingBuffer =
|
||||
createCircularCache<Awaited<ReturnType<(typeof kmsService)["createCipherPairWithDataKey"]>>>(25);
|
||||
|
||||
@@ -323,7 +317,7 @@ const reencryptLdapConfig = async (knex: Knex) => {
|
||||
}
|
||||
};
|
||||
|
||||
const reencryptOidcConfig = async (knex: Knex) => {
|
||||
const reencryptOidcConfig = async (knex: Knex, kmsService: TKmsServiceFactory) => {
|
||||
const hasEncryptedOidcClientIdColumn = await knex.schema.hasColumn(TableName.OidcConfig, "encryptedOidcClientId");
|
||||
const hasEncryptedOidcClientSecretColumn = await knex.schema.hasColumn(
|
||||
TableName.OidcConfig,
|
||||
@@ -354,10 +348,6 @@ const reencryptOidcConfig = async (knex: Knex) => {
|
||||
}
|
||||
|
||||
initLogger();
|
||||
const superAdminDAL = superAdminDALFactory(knex);
|
||||
const envConfig = await getMigrationEnvConfig(superAdminDAL);
|
||||
const keyStore = inMemoryKeyStore();
|
||||
const { kmsService } = await getMigrationEncryptionServices({ envConfig, keyStore, db: knex });
|
||||
const orgEncryptionRingBuffer =
|
||||
createCircularCache<Awaited<ReturnType<(typeof kmsService)["createCipherPairWithDataKey"]>>>(25);
|
||||
|
||||
@@ -462,9 +452,18 @@ const reencryptOidcConfig = async (knex: Knex) => {
|
||||
};
|
||||
|
||||
export async function up(knex: Knex): Promise<void> {
|
||||
await reencryptSamlConfig(knex);
|
||||
await reencryptLdapConfig(knex);
|
||||
await reencryptOidcConfig(knex);
|
||||
initLogger();
|
||||
|
||||
const { hsmService } = await getMigrationHsmService({ envConfig: getMigrationHsmConfig() });
|
||||
const superAdminDAL = superAdminDALFactory(knex);
|
||||
const kmsRootConfigDAL = kmsRootConfigDALFactory(knex);
|
||||
const envConfig = await getMigrationEnvConfig(superAdminDAL, hsmService, kmsRootConfigDAL);
|
||||
const keyStore = inMemoryKeyStore();
|
||||
const { kmsService } = await getMigrationEncryptionServices({ envConfig, keyStore, db: knex });
|
||||
|
||||
await reencryptSamlConfig(knex, kmsService);
|
||||
await reencryptLdapConfig(knex, kmsService);
|
||||
await reencryptOidcConfig(knex, kmsService);
|
||||
}
|
||||
|
||||
const dropSamlConfigColumns = async (knex: Knex) => {
|
||||
|
||||
@@ -3,12 +3,13 @@ import { Knex } from "knex";
|
||||
import { inMemoryKeyStore } from "@app/keystore/memory";
|
||||
import { selectAllTableCols } from "@app/lib/knex";
|
||||
import { initLogger } from "@app/lib/logger";
|
||||
import { kmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";
|
||||
import { KmsDataKey } from "@app/services/kms/kms-types";
|
||||
import { superAdminDALFactory } from "@app/services/super-admin/super-admin-dal";
|
||||
|
||||
import { TableName } from "../schemas";
|
||||
import { getMigrationEnvConfig } from "./utils/env-config";
|
||||
import { getMigrationEncryptionServices } from "./utils/services";
|
||||
import { getMigrationEnvConfig, getMigrationHsmConfig } from "./utils/env-config";
|
||||
import { getMigrationEncryptionServices, getMigrationHsmService } from "./utils/services";
|
||||
|
||||
// Note(daniel): We aren't dropping tables or columns in this migrations so we can easily rollback if needed.
|
||||
// In the future we need to drop the projectGatewayId on the dynamic secrets table, and drop the project_gateways table entirely.
|
||||
@@ -40,8 +41,10 @@ export async function up(knex: Knex): Promise<void> {
|
||||
);
|
||||
|
||||
initLogger();
|
||||
const { hsmService } = await getMigrationHsmService({ envConfig: getMigrationHsmConfig() });
|
||||
const superAdminDAL = superAdminDALFactory(knex);
|
||||
const envConfig = await getMigrationEnvConfig(superAdminDAL);
|
||||
const kmsRootConfigDAL = kmsRootConfigDALFactory(knex);
|
||||
const envConfig = await getMigrationEnvConfig(superAdminDAL, hsmService, kmsRootConfigDAL);
|
||||
const keyStore = inMemoryKeyStore();
|
||||
const { kmsService } = await getMigrationEncryptionServices({ envConfig, keyStore, db: knex });
|
||||
|
||||
|
||||
@@ -2,19 +2,23 @@ import { Knex } from "knex";
|
||||
|
||||
import { inMemoryKeyStore } from "@app/keystore/memory";
|
||||
import { selectAllTableCols } from "@app/lib/knex";
|
||||
import { kmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";
|
||||
import { superAdminDALFactory } from "@app/services/super-admin/super-admin-dal";
|
||||
|
||||
import { TableName } from "../schemas";
|
||||
import { getMigrationEnvConfig } from "./utils/env-config";
|
||||
import { getMigrationEncryptionServices } from "./utils/services";
|
||||
import { getMigrationEnvConfig, getMigrationHsmConfig } from "./utils/env-config";
|
||||
import { getMigrationEncryptionServices, getMigrationHsmService } from "./utils/services";
|
||||
|
||||
export async function up(knex: Knex) {
|
||||
const existingSuperAdminsWithGithubConnection = await knex(TableName.SuperAdmin)
|
||||
.select(selectAllTableCols(TableName.SuperAdmin))
|
||||
.whereNotNull(`${TableName.SuperAdmin}.encryptedGitHubAppConnectionClientId`);
|
||||
|
||||
const { hsmService } = await getMigrationHsmService({ envConfig: getMigrationHsmConfig() });
|
||||
|
||||
const superAdminDAL = superAdminDALFactory(knex);
|
||||
const envConfig = await getMigrationEnvConfig(superAdminDAL);
|
||||
const kmsRootConfigDAL = kmsRootConfigDALFactory(knex);
|
||||
const envConfig = await getMigrationEnvConfig(superAdminDAL, hsmService, kmsRootConfigDAL);
|
||||
const keyStore = inMemoryKeyStore();
|
||||
const { kmsService } = await getMigrationEncryptionServices({ envConfig, keyStore, db: knex });
|
||||
|
||||
|
||||
@@ -2,13 +2,14 @@ import { Knex } from "knex";
|
||||
|
||||
import { inMemoryKeyStore } from "@app/keystore/memory";
|
||||
import { crypto } from "@app/lib/crypto/cryptography";
|
||||
import { kmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";
|
||||
import { KmsDataKey } from "@app/services/kms/kms-types";
|
||||
import { superAdminDALFactory } from "@app/services/super-admin/super-admin-dal";
|
||||
|
||||
import { SecretKeyEncoding, TableName } from "../schemas";
|
||||
import { getMigrationEnvConfig } from "./utils/env-config";
|
||||
import { getMigrationEnvConfig, getMigrationHsmConfig } from "./utils/env-config";
|
||||
import { createCircularCache } from "./utils/ring-buffer";
|
||||
import { getMigrationEncryptionServices } from "./utils/services";
|
||||
import { getMigrationEncryptionServices, getMigrationHsmService } from "./utils/services";
|
||||
|
||||
const BATCH_SIZE = 500;
|
||||
export async function up(knex: Knex): Promise<void> {
|
||||
@@ -25,8 +26,10 @@ export async function up(knex: Knex): Promise<void> {
|
||||
});
|
||||
|
||||
if (!hasEncryptedCredentials) {
|
||||
const { hsmService } = await getMigrationHsmService({ envConfig: getMigrationHsmConfig() });
|
||||
const superAdminDAL = superAdminDALFactory(knex);
|
||||
const envConfig = await getMigrationEnvConfig(superAdminDAL);
|
||||
const kmsRootConfigDAL = kmsRootConfigDALFactory(knex);
|
||||
const envConfig = await getMigrationEnvConfig(superAdminDAL, hsmService, kmsRootConfigDAL);
|
||||
const keyStore = inMemoryKeyStore();
|
||||
|
||||
const { kmsService } = await getMigrationEncryptionServices({ envConfig, keyStore, db: knex });
|
||||
@@ -131,8 +134,11 @@ export async function down(knex: Knex): Promise<void> {
|
||||
const hasEncryptedCredentials = await knex.schema.hasColumn(TableName.AuditLogStream, "encryptedCredentials");
|
||||
|
||||
if (hasEncryptedCredentials) {
|
||||
const { hsmService } = await getMigrationHsmService({ envConfig: getMigrationHsmConfig() });
|
||||
|
||||
const superAdminDAL = superAdminDALFactory(knex);
|
||||
const envConfig = await getMigrationEnvConfig(superAdminDAL);
|
||||
const kmsRootConfigDAL = kmsRootConfigDALFactory(knex);
|
||||
const envConfig = await getMigrationEnvConfig(superAdminDAL, hsmService, kmsRootConfigDAL);
|
||||
const keyStore = inMemoryKeyStore();
|
||||
|
||||
const { kmsService } = await getMigrationEncryptionServices({ envConfig, keyStore, db: knex });
|
||||
|
||||
@@ -0,0 +1,165 @@
|
||||
import { Knex } from "knex";
|
||||
|
||||
import { TableName } from "../schemas";
|
||||
import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";
|
||||
|
||||
export async function up(knex: Knex): Promise<void> {
|
||||
// PAM Folders
|
||||
if (!(await knex.schema.hasTable(TableName.PamFolder))) {
|
||||
await knex.schema.createTable(TableName.PamFolder, (t) => {
|
||||
t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
|
||||
|
||||
t.string("projectId").notNullable();
|
||||
t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");
|
||||
t.index("projectId");
|
||||
|
||||
t.uuid("parentId").nullable();
|
||||
t.foreign("parentId").references("id").inTable(TableName.PamFolder).onDelete("CASCADE");
|
||||
t.index("parentId");
|
||||
|
||||
t.string("name").notNullable();
|
||||
t.index("name");
|
||||
|
||||
// Enforce uniqueness for sub-folders
|
||||
t.unique(["projectId", "parentId", "name"], {
|
||||
indexName: "uidx_pam_folder_children_name",
|
||||
predicate: knex.whereNotNull("parentId")
|
||||
});
|
||||
|
||||
// Enforce uniqueness for root-level folders
|
||||
t.unique(["projectId", "name"], {
|
||||
indexName: "uidx_pam_folder_root_name",
|
||||
predicate: knex.whereNull("parentId")
|
||||
});
|
||||
|
||||
t.text("description").nullable();
|
||||
|
||||
t.timestamps(true, true, true);
|
||||
});
|
||||
}
|
||||
|
||||
// PAM Resources
|
||||
if (!(await knex.schema.hasTable(TableName.PamResource))) {
|
||||
await knex.schema.createTable(TableName.PamResource, (t) => {
|
||||
t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
|
||||
|
||||
t.string("projectId").notNullable();
|
||||
t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");
|
||||
t.index("projectId");
|
||||
|
||||
t.string("name").notNullable();
|
||||
t.index("name");
|
||||
|
||||
t.uuid("gatewayId").notNullable();
|
||||
t.foreign("gatewayId").references("id").inTable(TableName.GatewayV2);
|
||||
t.index("gatewayId");
|
||||
|
||||
t.string("resourceType").notNullable();
|
||||
t.index("resourceType");
|
||||
|
||||
t.binary("encryptedConnectionDetails").notNullable();
|
||||
|
||||
t.timestamps(true, true, true);
|
||||
});
|
||||
}
|
||||
|
||||
// PAM Accounts
|
||||
if (!(await knex.schema.hasTable(TableName.PamAccount))) {
|
||||
await knex.schema.createTable(TableName.PamAccount, (t) => {
|
||||
t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
|
||||
|
||||
t.string("projectId").notNullable();
|
||||
t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");
|
||||
t.index("projectId");
|
||||
|
||||
t.uuid("folderId").nullable();
|
||||
t.foreign("folderId").references("id").inTable(TableName.PamFolder).onDelete("CASCADE");
|
||||
t.index("folderId");
|
||||
|
||||
t.uuid("resourceId").notNullable();
|
||||
t.foreign("resourceId").references("id").inTable(TableName.PamResource);
|
||||
t.index("resourceId");
|
||||
|
||||
t.string("name").notNullable();
|
||||
t.index("name");
|
||||
|
||||
// Enforce uniqueness for folders
|
||||
t.unique(["projectId", "folderId", "name"], {
|
||||
indexName: "uidx_pam_account_children_name",
|
||||
predicate: knex.whereNotNull("folderId")
|
||||
});
|
||||
|
||||
// Enforce uniqueness for root-level
|
||||
t.unique(["projectId", "name"], {
|
||||
indexName: "uidx_pam_account_root_name",
|
||||
predicate: knex.whereNull("folderId")
|
||||
});
|
||||
|
||||
t.text("description").nullable();
|
||||
t.binary("encryptedCredentials").notNullable();
|
||||
|
||||
t.timestamps(true, true, true);
|
||||
});
|
||||
}
|
||||
|
||||
// PAM Sessions
|
||||
if (!(await knex.schema.hasTable(TableName.PamSession))) {
|
||||
await knex.schema.createTable(TableName.PamSession, (t) => {
|
||||
t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
|
||||
|
||||
t.string("projectId").notNullable();
|
||||
t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");
|
||||
t.index("projectId");
|
||||
|
||||
t.uuid("accountId").nullable();
|
||||
t.foreign("accountId").references("id").inTable(TableName.PamAccount).onDelete("SET NULL");
|
||||
t.index("accountId");
|
||||
|
||||
// To be used in the event of an account deletion
|
||||
t.string("resourceType").notNullable();
|
||||
t.string("resourceName").notNullable();
|
||||
t.string("accountName").notNullable();
|
||||
|
||||
t.uuid("userId").nullable();
|
||||
t.foreign("userId").references("id").inTable(TableName.Users).onDelete("SET NULL");
|
||||
t.index("userId");
|
||||
|
||||
// To be used in the event of user deletion
|
||||
t.string("actorName").notNullable();
|
||||
t.string("actorEmail").notNullable();
|
||||
|
||||
t.string("actorIp").notNullable();
|
||||
t.string("actorUserAgent").notNullable();
|
||||
|
||||
t.string("status").notNullable();
|
||||
t.index("status");
|
||||
|
||||
t.binary("encryptedLogsBlob").nullable();
|
||||
|
||||
t.datetime("expiresAt").notNullable();
|
||||
|
||||
t.datetime("startedAt").nullable(); // Not when the row is created, but when the end-to-end connection between user and resource is established
|
||||
t.datetime("endedAt").nullable();
|
||||
t.index(["startedAt", "endedAt"]);
|
||||
|
||||
t.timestamps(true, true, true);
|
||||
});
|
||||
}
|
||||
|
||||
await createOnUpdateTrigger(knex, TableName.PamFolder);
|
||||
await createOnUpdateTrigger(knex, TableName.PamResource);
|
||||
await createOnUpdateTrigger(knex, TableName.PamAccount);
|
||||
await createOnUpdateTrigger(knex, TableName.PamSession);
|
||||
}
|
||||
|
||||
export async function down(knex: Knex): Promise<void> {
|
||||
await knex.schema.dropTableIfExists(TableName.PamSession);
|
||||
await knex.schema.dropTableIfExists(TableName.PamAccount);
|
||||
await knex.schema.dropTableIfExists(TableName.PamResource);
|
||||
await knex.schema.dropTableIfExists(TableName.PamFolder);
|
||||
|
||||
await dropOnUpdateTrigger(knex, TableName.PamSession);
|
||||
await dropOnUpdateTrigger(knex, TableName.PamAccount);
|
||||
await dropOnUpdateTrigger(knex, TableName.PamResource);
|
||||
await dropOnUpdateTrigger(knex, TableName.PamFolder);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Knex } from "knex";
|
||||
|
||||
import { TableName } from "../schemas";
|
||||
|
||||
export async function up(knex: Knex): Promise<void> {
|
||||
if (!(await knex.schema.hasColumn(TableName.GatewayV2, "encryptedPamSessionKey"))) {
|
||||
await knex.schema.alterTable(TableName.GatewayV2, (t) => {
|
||||
t.binary("encryptedPamSessionKey");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function down(knex: Knex): Promise<void> {
|
||||
if (await knex.schema.hasColumn(TableName.GatewayV2, "encryptedPamSessionKey")) {
|
||||
await knex.schema.alterTable(TableName.GatewayV2, (t) => {
|
||||
t.dropColumn("encryptedPamSessionKey");
|
||||
});
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,117 @@
|
||||
import { Knex } from "knex";
|
||||
|
||||
import { TableName } from "../schemas";
|
||||
import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";
|
||||
|
||||
export async function up(knex: Knex): Promise<void> {
|
||||
if (!(await knex.schema.hasTable(TableName.PkiCertificateTemplateV2))) {
|
||||
await knex.schema.createTable(TableName.PkiCertificateTemplateV2, (t) => {
|
||||
t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
|
||||
t.string("projectId").notNullable();
|
||||
t.foreign("projectId").references("id").inTable(TableName.Project);
|
||||
|
||||
t.string("name").notNullable();
|
||||
t.string("description");
|
||||
|
||||
t.jsonb("subject");
|
||||
t.jsonb("sans");
|
||||
t.jsonb("keyUsages");
|
||||
t.jsonb("extendedKeyUsages");
|
||||
t.jsonb("algorithms");
|
||||
t.jsonb("validity");
|
||||
|
||||
t.timestamps(true, true, true);
|
||||
|
||||
t.unique(["name", "projectId"]);
|
||||
});
|
||||
|
||||
await createOnUpdateTrigger(knex, TableName.PkiCertificateTemplateV2);
|
||||
}
|
||||
|
||||
if (!(await knex.schema.hasTable(TableName.PkiEstEnrollmentConfig))) {
|
||||
await knex.schema.createTable(TableName.PkiEstEnrollmentConfig, (t) => {
|
||||
t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
|
||||
|
||||
t.boolean("disableBootstrapCaValidation").defaultTo(false);
|
||||
t.text("hashedPassphrase").notNullable();
|
||||
t.binary("encryptedCaChain");
|
||||
|
||||
t.timestamps(true, true, true);
|
||||
});
|
||||
|
||||
await createOnUpdateTrigger(knex, TableName.PkiEstEnrollmentConfig);
|
||||
}
|
||||
|
||||
if (!(await knex.schema.hasTable(TableName.PkiApiEnrollmentConfig))) {
|
||||
await knex.schema.createTable(TableName.PkiApiEnrollmentConfig, (t) => {
|
||||
t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
|
||||
|
||||
t.boolean("autoRenew").defaultTo(false);
|
||||
t.integer("autoRenewDays");
|
||||
|
||||
t.timestamps(true, true, true);
|
||||
});
|
||||
|
||||
await createOnUpdateTrigger(knex, TableName.PkiApiEnrollmentConfig);
|
||||
}
|
||||
|
||||
if (!(await knex.schema.hasTable(TableName.PkiCertificateProfile))) {
|
||||
await knex.schema.createTable(TableName.PkiCertificateProfile, (t) => {
|
||||
t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
|
||||
t.string("projectId").notNullable();
|
||||
t.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");
|
||||
|
||||
t.uuid("caId").notNullable();
|
||||
t.foreign("caId").references("id").inTable(TableName.CertificateAuthority);
|
||||
|
||||
t.uuid("certificateTemplateId").notNullable();
|
||||
t.foreign("certificateTemplateId").references("id").inTable(TableName.PkiCertificateTemplateV2);
|
||||
|
||||
t.string("slug").notNullable();
|
||||
t.string("description");
|
||||
t.string("enrollmentType").notNullable().checkIn(["api", "est"]);
|
||||
|
||||
t.uuid("estConfigId");
|
||||
t.foreign("estConfigId").references("id").inTable(TableName.PkiEstEnrollmentConfig).onDelete("SET NULL");
|
||||
|
||||
t.uuid("apiConfigId");
|
||||
t.foreign("apiConfigId").references("id").inTable(TableName.PkiApiEnrollmentConfig).onDelete("SET NULL");
|
||||
|
||||
t.timestamps(true, true, true);
|
||||
|
||||
t.unique(["slug", "projectId"]);
|
||||
});
|
||||
|
||||
await createOnUpdateTrigger(knex, TableName.PkiCertificateProfile);
|
||||
}
|
||||
|
||||
if (!(await knex.schema.hasColumn(TableName.Certificate, "profileId"))) {
|
||||
await knex.schema.alterTable(TableName.Certificate, (t) => {
|
||||
t.uuid("profileId");
|
||||
t.foreign("profileId").references("id").inTable(TableName.PkiCertificateProfile).onDelete("SET NULL");
|
||||
t.index("profileId");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function down(knex: Knex): Promise<void> {
|
||||
if (await knex.schema.hasColumn(TableName.Certificate, "profileId")) {
|
||||
await knex.schema.alterTable(TableName.Certificate, (t) => {
|
||||
t.dropForeign(["profileId"]);
|
||||
t.dropIndex("profileId");
|
||||
t.dropColumn("profileId");
|
||||
});
|
||||
}
|
||||
|
||||
await knex.schema.dropTableIfExists(TableName.PkiCertificateProfile);
|
||||
await dropOnUpdateTrigger(knex, TableName.PkiCertificateProfile);
|
||||
|
||||
await knex.schema.dropTableIfExists(TableName.PkiApiEnrollmentConfig);
|
||||
await dropOnUpdateTrigger(knex, TableName.PkiApiEnrollmentConfig);
|
||||
|
||||
await knex.schema.dropTableIfExists(TableName.PkiEstEnrollmentConfig);
|
||||
await dropOnUpdateTrigger(knex, TableName.PkiEstEnrollmentConfig);
|
||||
|
||||
await knex.schema.dropTableIfExists(TableName.PkiCertificateTemplateV2);
|
||||
await dropOnUpdateTrigger(knex, TableName.PkiCertificateTemplateV2);
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Knex } from "knex";
|
||||
|
||||
import { TableName } from "../schemas";
|
||||
|
||||
export async function up(knex: Knex): Promise<void> {
|
||||
if (!(await knex.schema.hasColumn(TableName.Relay, "heartbeat"))) {
|
||||
await knex.schema.alterTable(TableName.Relay, (t) => {
|
||||
t.datetime("heartbeat");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function down(knex: Knex): Promise<void> {
|
||||
if (await knex.schema.hasColumn(TableName.Relay, "heartbeat")) {
|
||||
await knex.schema.alterTable(TableName.Relay, (t) => {
|
||||
t.dropColumn("heartbeat");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Knex } from "knex";
|
||||
|
||||
import { TableName } from "../schemas";
|
||||
|
||||
export async function up(knex: Knex): Promise<void> {
|
||||
if (!(await knex.schema.hasColumn(TableName.Relay, "healthAlertedAt"))) {
|
||||
await knex.schema.alterTable(TableName.Relay, (t) => {
|
||||
t.datetime("healthAlertedAt");
|
||||
});
|
||||
}
|
||||
if (!(await knex.schema.hasColumn(TableName.GatewayV2, "healthAlertedAt"))) {
|
||||
await knex.schema.alterTable(TableName.GatewayV2, (t) => {
|
||||
t.datetime("healthAlertedAt");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function down(knex: Knex): Promise<void> {
|
||||
if (await knex.schema.hasColumn(TableName.GatewayV2, "healthAlertedAt")) {
|
||||
await knex.schema.alterTable(TableName.GatewayV2, (t) => {
|
||||
t.dropColumn("healthAlertedAt");
|
||||
});
|
||||
}
|
||||
if (await knex.schema.hasColumn(TableName.Relay, "healthAlertedAt")) {
|
||||
await knex.schema.alterTable(TableName.Relay, (t) => {
|
||||
t.dropColumn("healthAlertedAt");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,19 @@
|
||||
import { Knex } from "knex";
|
||||
|
||||
import { TableName } from "../schemas";
|
||||
|
||||
export async function up(knex: Knex): Promise<void> {
|
||||
if (!(await knex.schema.hasColumn(TableName.KmsKey, "kmipMetadata"))) {
|
||||
await knex.schema.alterTable(TableName.KmsKey, (t) => {
|
||||
t.jsonb("kmipMetadata");
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function down(knex: Knex): Promise<void> {
|
||||
if (await knex.schema.hasColumn(TableName.KmsKey, "kmipMetadata")) {
|
||||
await knex.schema.alterTable(TableName.KmsKey, (t) => {
|
||||
t.dropColumn("kmipMetadata");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,23 @@
|
||||
import { Knex } from "knex";
|
||||
|
||||
import { TableName } from "../schemas";
|
||||
|
||||
export async function up(knex: Knex): Promise<void> {
|
||||
const hasScopeColumn = await knex.schema.hasColumn(TableName.Membership, "scope");
|
||||
const hasActorIdentityColumn = await knex.schema.hasColumn(TableName.Membership, "actorIdentityId");
|
||||
if (hasScopeColumn && hasActorIdentityColumn) {
|
||||
await knex.schema.alterTable(TableName.Membership, (t) => {
|
||||
t.index(["scope", "actorIdentityId"]);
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function down(knex: Knex): Promise<void> {
|
||||
const hasScopeColumn = await knex.schema.hasColumn(TableName.Membership, "scope");
|
||||
const hasActorIdentityColumn = await knex.schema.hasColumn(TableName.Membership, "actorIdentityId");
|
||||
if (hasScopeColumn && hasActorIdentityColumn) {
|
||||
await knex.schema.alterTable(TableName.Membership, (t) => {
|
||||
t.dropIndex(["scope", "actorIdentityId"]);
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
import { Knex } from "knex";
|
||||
|
||||
import { TableName } from "../schemas";
|
||||
import { createOnUpdateTrigger, dropOnUpdateTrigger } from "../utils";
|
||||
|
||||
export async function up(knex: Knex): Promise<void> {
|
||||
if (!(await knex.schema.hasTable(TableName.VaultExternalMigrationConfig))) {
|
||||
await knex.schema.createTable(TableName.VaultExternalMigrationConfig, (t) => {
|
||||
t.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
|
||||
t.uuid("orgId").notNullable();
|
||||
t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE");
|
||||
|
||||
t.string("namespace").notNullable();
|
||||
|
||||
t.uuid("connectionId");
|
||||
t.foreign("connectionId").references("id").inTable(TableName.AppConnection);
|
||||
|
||||
t.timestamps(true, true, true);
|
||||
t.unique(["orgId", "namespace"]);
|
||||
});
|
||||
|
||||
await createOnUpdateTrigger(knex, TableName.VaultExternalMigrationConfig);
|
||||
}
|
||||
}
|
||||
|
||||
export async function down(knex: Knex): Promise<void> {
|
||||
await knex.schema.dropTableIfExists(TableName.VaultExternalMigrationConfig);
|
||||
await dropOnUpdateTrigger(knex, TableName.VaultExternalMigrationConfig);
|
||||
}
|
||||
@@ -0,0 +1,49 @@
|
||||
import { Knex } from "knex";
|
||||
|
||||
import { TableName } from "../schemas";
|
||||
|
||||
export async function up(knex: Knex): Promise<void> {
|
||||
if (!(await knex.schema.hasColumn(TableName.PamAccount, "rotationEnabled"))) {
|
||||
await knex.schema.alterTable(TableName.PamAccount, (t) => {
|
||||
t.boolean("rotationEnabled").notNullable().defaultTo(false);
|
||||
});
|
||||
}
|
||||
if (!(await knex.schema.hasColumn(TableName.PamAccount, "rotationIntervalSeconds"))) {
|
||||
await knex.schema.alterTable(TableName.PamAccount, (t) => {
|
||||
t.integer("rotationIntervalSeconds").nullable();
|
||||
});
|
||||
}
|
||||
if (!(await knex.schema.hasColumn(TableName.PamAccount, "lastRotatedAt"))) {
|
||||
await knex.schema.alterTable(TableName.PamAccount, (t) => {
|
||||
t.timestamp("lastRotatedAt").nullable();
|
||||
});
|
||||
}
|
||||
if (!(await knex.schema.hasColumn(TableName.PamResource, "encryptedRotationAccountCredentials"))) {
|
||||
await knex.schema.alterTable(TableName.PamResource, (t) => {
|
||||
t.binary("encryptedRotationAccountCredentials").nullable();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function down(knex: Knex): Promise<void> {
|
||||
if (await knex.schema.hasColumn(TableName.PamResource, "encryptedRotationAccountCredentials")) {
|
||||
await knex.schema.alterTable(TableName.PamResource, (t) => {
|
||||
t.dropColumn("encryptedRotationAccountCredentials");
|
||||
});
|
||||
}
|
||||
if (await knex.schema.hasColumn(TableName.PamAccount, "rotationEnabled")) {
|
||||
await knex.schema.alterTable(TableName.PamAccount, (t) => {
|
||||
t.dropColumn("rotationEnabled");
|
||||
});
|
||||
}
|
||||
if (await knex.schema.hasColumn(TableName.PamAccount, "rotationIntervalSeconds")) {
|
||||
await knex.schema.alterTable(TableName.PamAccount, (t) => {
|
||||
t.dropColumn("rotationIntervalSeconds");
|
||||
});
|
||||
}
|
||||
if (await knex.schema.hasColumn(TableName.PamAccount, "lastRotatedAt")) {
|
||||
await knex.schema.alterTable(TableName.PamAccount, (t) => {
|
||||
t.dropColumn("lastRotatedAt");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,68 @@
|
||||
import { Knex } from "knex";
|
||||
|
||||
import { dropConstraintIfExists } from "@app/db/migrations/utils/dropConstraintIfExists";
|
||||
|
||||
import { AccessScope, TableName } from "../schemas";
|
||||
|
||||
export async function up(knex: Knex): Promise<void> {
|
||||
const hasParentOrgId = await knex.schema.hasColumn(TableName.Organization, "parentOrgId");
|
||||
if (!hasParentOrgId) {
|
||||
await knex.schema.alterTable(TableName.Organization, async (t) => {
|
||||
// the one just above the chain
|
||||
t.uuid("parentOrgId");
|
||||
t.foreign("parentOrgId").references("id").inTable(TableName.Organization).onDelete("CASCADE");
|
||||
// this would root organization containing various informations like billing etc
|
||||
t.uuid("rootOrgId");
|
||||
t.foreign("rootOrgId").references("id").inTable(TableName.Organization).onDelete("CASCADE");
|
||||
|
||||
await dropConstraintIfExists(TableName.Organization, "organizations_slug_unique", knex);
|
||||
t.unique(["rootOrgId", "parentOrgId", "slug"]);
|
||||
});
|
||||
|
||||
// had to switch to raw for null not distinct
|
||||
}
|
||||
|
||||
const hasIdentityOrgCol = await knex.schema.hasColumn(TableName.Identity, "orgId");
|
||||
if (!hasIdentityOrgCol) {
|
||||
await knex.schema.alterTable(TableName.Identity, (t) => {
|
||||
t.uuid("orgId");
|
||||
t.foreign("orgId").references("id").inTable(TableName.Organization).onDelete("CASCADE");
|
||||
});
|
||||
|
||||
await knex.raw(
|
||||
`
|
||||
UPDATE ?? AS identity
|
||||
SET "orgId" = membership."scopeOrgId"
|
||||
FROM ?? AS membership
|
||||
WHERE
|
||||
membership."actorIdentityId" = identity."id"
|
||||
AND membership."scope" = ?
|
||||
`,
|
||||
[TableName.Identity, TableName.Membership, AccessScope.Organization]
|
||||
);
|
||||
|
||||
await knex.raw(`DELETE FROM ?? WHERE "orgId" IS NULL`, [TableName.Identity]);
|
||||
|
||||
await knex.schema.alterTable(TableName.Identity, (t) => {
|
||||
t.uuid("orgId").notNullable().alter();
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
export async function down(knex: Knex): Promise<void> {
|
||||
const hasParentOrgId = await knex.schema.hasColumn(TableName.Organization, "parentOrgId");
|
||||
const hasRootOrgId = await knex.schema.hasColumn(TableName.Organization, "rootOrgId");
|
||||
if (hasParentOrgId || hasRootOrgId) {
|
||||
await knex.schema.alterTable(TableName.Organization, (t) => {
|
||||
if (hasParentOrgId) t.dropColumn("parentOrgId");
|
||||
if (hasRootOrgId) t.dropColumn("rootOrgId");
|
||||
});
|
||||
}
|
||||
|
||||
const hasIdentityOrgCol = await knex.schema.hasColumn(TableName.Identity, "orgId");
|
||||
if (hasIdentityOrgCol) {
|
||||
await knex.schema.alterTable(TableName.Identity, (t) => {
|
||||
t.dropColumn("orgId");
|
||||
});
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,60 @@
|
||||
import { Knex } from "knex";
|
||||
|
||||
import { AccessScope, TableName } from "../schemas";
|
||||
|
||||
export async function up(knex: Knex): Promise<void> {
|
||||
const hasGroupsTable = await knex.schema.hasTable(TableName.Groups);
|
||||
const hasMembershipTable = await knex.schema.hasTable(TableName.Membership);
|
||||
const hasMembershipRoleTable = await knex.schema.hasTable(TableName.MembershipRole);
|
||||
|
||||
if (!hasGroupsTable || !hasMembershipTable || !hasMembershipRoleTable) {
|
||||
return;
|
||||
}
|
||||
|
||||
const groupsWithoutMembership = await knex
|
||||
.select(
|
||||
`${TableName.Groups}.id`,
|
||||
`${TableName.Groups}.orgId`,
|
||||
`${TableName.Groups}.role`,
|
||||
`${TableName.Groups}.roleId`
|
||||
)
|
||||
.from(TableName.Groups)
|
||||
.leftJoin(TableName.Membership, `${TableName.Groups}.id`, `${TableName.Membership}.actorGroupId`)
|
||||
.whereNull(`${TableName.Membership}.actorGroupId`);
|
||||
|
||||
if (groupsWithoutMembership.length > 0) {
|
||||
const membershipInserts = groupsWithoutMembership.map((group) => ({
|
||||
actorGroupId: group.id,
|
||||
scope: AccessScope.Organization,
|
||||
scopeOrgId: group.orgId,
|
||||
isActive: true
|
||||
}));
|
||||
|
||||
const insertedMemberships = await knex(TableName.Membership).insert(membershipInserts).returning("*");
|
||||
|
||||
const membershipRoleInserts = insertedMemberships.map((membership, index) => {
|
||||
const group = groupsWithoutMembership[index];
|
||||
return {
|
||||
membershipId: membership.id,
|
||||
role: group.role,
|
||||
customRoleId: group.roleId
|
||||
};
|
||||
});
|
||||
|
||||
await knex(TableName.MembershipRole).insert(membershipRoleInserts);
|
||||
}
|
||||
|
||||
await knex.schema.alterTable(TableName.Membership, (t) => {
|
||||
t.check(
|
||||
`("actorUserId" IS NOT NULL OR "actorIdentityId" IS NOT NULL OR "actorGroupId" IS NOT NULL)`,
|
||||
undefined,
|
||||
"at_least_one_actor"
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
export async function down(knex: Knex): Promise<void> {
|
||||
await knex.schema.alterTable(TableName.Membership, (t) => {
|
||||
t.dropChecks("at_least_one_actor");
|
||||
});
|
||||
}
|
||||
@@ -1,7 +1,10 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { THsmServiceFactory } from "@app/ee/services/hsm/hsm-service";
|
||||
import { crypto } from "@app/lib/crypto/cryptography";
|
||||
import { removeTrailingSlash } from "@app/lib/fn";
|
||||
import { zpStr } from "@app/lib/zod";
|
||||
import { TKmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";
|
||||
import { TSuperAdminDALFactory } from "@app/services/super-admin/super-admin-dal";
|
||||
|
||||
const envSchema = z
|
||||
@@ -22,13 +25,17 @@ const envSchema = z
|
||||
HSM_LIB_PATH: zpStr(z.string().optional()),
|
||||
HSM_PIN: zpStr(z.string().optional()),
|
||||
HSM_KEY_LABEL: zpStr(z.string().optional()),
|
||||
HSM_SLOT: z.coerce.number().optional().default(0)
|
||||
HSM_SLOT: z.coerce.number().optional().default(0),
|
||||
|
||||
LICENSE_SERVER_URL: zpStr(z.string().optional().default("https://portal.infisical.com")),
|
||||
LICENSE_SERVER_KEY: zpStr(z.string().optional()),
|
||||
LICENSE_KEY: zpStr(z.string().optional()),
|
||||
LICENSE_KEY_OFFLINE: zpStr(z.string().optional()),
|
||||
INTERNAL_REGION: zpStr(z.enum(["us", "eu"]).optional()),
|
||||
|
||||
SITE_URL: zpStr(z.string().transform((val) => (val ? removeTrailingSlash(val) : val))).optional()
|
||||
})
|
||||
// To ensure that basic encryption is always possible.
|
||||
.refine(
|
||||
(data) => Boolean(data.ENCRYPTION_KEY) || Boolean(data.ROOT_ENCRYPTION_KEY),
|
||||
"Either ENCRYPTION_KEY or ROOT_ENCRYPTION_KEY must be defined."
|
||||
)
|
||||
.transform((data) => ({
|
||||
...data,
|
||||
isHsmConfigured:
|
||||
@@ -37,7 +44,27 @@ const envSchema = z
|
||||
|
||||
export type TMigrationEnvConfig = z.infer<typeof envSchema>;
|
||||
|
||||
export const getMigrationEnvConfig = async (superAdminDAL: TSuperAdminDALFactory) => {
|
||||
export const getMigrationHsmConfig = () => {
|
||||
const parsedEnv = envSchema.safeParse(process.env);
|
||||
if (!parsedEnv.success) {
|
||||
console.error("Invalid environment variables. Check the error below");
|
||||
console.error(parsedEnv.error.issues);
|
||||
process.exit(-1);
|
||||
}
|
||||
return {
|
||||
isHsmConfigured: parsedEnv.data.isHsmConfigured,
|
||||
HSM_PIN: parsedEnv.data.HSM_PIN,
|
||||
HSM_SLOT: parsedEnv.data.HSM_SLOT,
|
||||
HSM_LIB_PATH: parsedEnv.data.HSM_LIB_PATH,
|
||||
HSM_KEY_LABEL: parsedEnv.data.HSM_KEY_LABEL
|
||||
};
|
||||
};
|
||||
|
||||
export const getMigrationEnvConfig = async (
|
||||
superAdminDAL: TSuperAdminDALFactory,
|
||||
hsmService: THsmServiceFactory,
|
||||
kmsRootConfigDAL: TKmsRootConfigDALFactory
|
||||
) => {
|
||||
const parsedEnv = envSchema.safeParse(process.env);
|
||||
if (!parsedEnv.success) {
|
||||
// eslint-disable-next-line no-console
|
||||
@@ -53,7 +80,7 @@ export const getMigrationEnvConfig = async (superAdminDAL: TSuperAdminDALFactory
|
||||
|
||||
let envCfg = Object.freeze(parsedEnv.data);
|
||||
|
||||
const fipsEnabled = await crypto.initialize(superAdminDAL, envCfg);
|
||||
const fipsEnabled = await crypto.initialize(superAdminDAL, hsmService, kmsRootConfigDAL, envCfg);
|
||||
|
||||
// Fix for 128-bit entropy encryption key expansion issue:
|
||||
// In FIPS it is not ideal to expand a 128-bit key into 256-bit. We solved this issue in the past by creating the ROOT_ENCRYPTION_KEY.
|
||||
|
||||
@@ -1,28 +1,23 @@
|
||||
import { Knex } from "knex";
|
||||
|
||||
import { initializeHsmModule } from "@app/ee/services/hsm/hsm-fns";
|
||||
import { initializeHsmModule, isHsmActiveAndEnabled } from "@app/ee/services/hsm/hsm-fns";
|
||||
import { hsmServiceFactory } from "@app/ee/services/hsm/hsm-service";
|
||||
import { licenseDALFactory } from "@app/ee/services/license/license-dal";
|
||||
import { licenseServiceFactory } from "@app/ee/services/license/license-service";
|
||||
import { permissionDALFactory } from "@app/ee/services/permission/permission-dal";
|
||||
import { permissionServiceFactory } from "@app/ee/services/permission/permission-service";
|
||||
import { TKeyStoreFactory } from "@app/keystore/keystore";
|
||||
import { folderCheckpointDALFactory } from "@app/services/folder-checkpoint/folder-checkpoint-dal";
|
||||
import { folderCheckpointResourcesDALFactory } from "@app/services/folder-checkpoint-resources/folder-checkpoint-resources-dal";
|
||||
import { folderCommitDALFactory } from "@app/services/folder-commit/folder-commit-dal";
|
||||
import { folderCommitServiceFactory } from "@app/services/folder-commit/folder-commit-service";
|
||||
import { folderCommitChangesDALFactory } from "@app/services/folder-commit-changes/folder-commit-changes-dal";
|
||||
import { folderTreeCheckpointDALFactory } from "@app/services/folder-tree-checkpoint/folder-tree-checkpoint-dal";
|
||||
import { folderTreeCheckpointResourcesDALFactory } from "@app/services/folder-tree-checkpoint-resources/folder-tree-checkpoint-resources-dal";
|
||||
import { BadRequestError } from "@app/lib/errors";
|
||||
import { identityDALFactory } from "@app/services/identity/identity-dal";
|
||||
import { internalKmsDALFactory } from "@app/services/kms/internal-kms-dal";
|
||||
import { kmskeyDALFactory } from "@app/services/kms/kms-key-dal";
|
||||
import { kmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";
|
||||
import { kmsServiceFactory } from "@app/services/kms/kms-service";
|
||||
import { RootKeyEncryptionStrategy } from "@app/services/kms/kms-types";
|
||||
import { orgDALFactory } from "@app/services/org/org-dal";
|
||||
import { projectDALFactory } from "@app/services/project/project-dal";
|
||||
import { resourceMetadataDALFactory } from "@app/services/resource-metadata/resource-metadata-dal";
|
||||
import { secretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";
|
||||
import { secretFolderVersionDALFactory } from "@app/services/secret-folder/secret-folder-version-dal";
|
||||
import { secretTagDALFactory } from "@app/services/secret-tag/secret-tag-dal";
|
||||
import { secretV2BridgeDALFactory } from "@app/services/secret-v2-bridge/secret-v2-bridge-dal";
|
||||
import { secretVersionV2BridgeDALFactory } from "@app/services/secret-v2-bridge/secret-version-dal";
|
||||
import { roleDALFactory } from "@app/services/role/role-dal";
|
||||
import { serviceTokenDALFactory } from "@app/services/service-token/service-token-dal";
|
||||
import { userDALFactory } from "@app/services/user/user-dal";
|
||||
|
||||
import { TMigrationEnvConfig } from "./env-config";
|
||||
@@ -33,8 +28,11 @@ type TDependencies = {
|
||||
keyStore: TKeyStoreFactory;
|
||||
};
|
||||
|
||||
export const getMigrationEncryptionServices = async ({ envConfig, db, keyStore }: TDependencies) => {
|
||||
// eslint-disable-next-line no-param-reassign
|
||||
type THsmServiceDependencies = {
|
||||
envConfig: Pick<TMigrationEnvConfig, "HSM_PIN" | "HSM_SLOT" | "HSM_LIB_PATH" | "HSM_KEY_LABEL" | "isHsmConfigured">;
|
||||
};
|
||||
|
||||
export const getMigrationHsmService = async ({ envConfig }: THsmServiceDependencies) => {
|
||||
const hsmModule = initializeHsmModule(envConfig);
|
||||
hsmModule.initialize();
|
||||
|
||||
@@ -43,67 +41,72 @@ export const getMigrationEncryptionServices = async ({ envConfig, db, keyStore }
|
||||
envConfig
|
||||
});
|
||||
|
||||
const orgDAL = orgDALFactory(db);
|
||||
const kmsRootConfigDAL = kmsRootConfigDALFactory(db);
|
||||
const kmsDAL = kmskeyDALFactory(db);
|
||||
const internalKmsDAL = internalKmsDALFactory(db);
|
||||
const projectDAL = projectDALFactory(db);
|
||||
|
||||
const kmsService = kmsServiceFactory({
|
||||
kmsRootConfigDAL,
|
||||
keyStore,
|
||||
kmsDAL,
|
||||
internalKmsDAL,
|
||||
orgDAL,
|
||||
projectDAL,
|
||||
hsmService,
|
||||
envConfig
|
||||
});
|
||||
|
||||
await hsmService.startService();
|
||||
await kmsService.startService();
|
||||
|
||||
return { kmsService };
|
||||
return { hsmService };
|
||||
};
|
||||
|
||||
export const getMigrationPITServices = async ({
|
||||
db,
|
||||
keyStore,
|
||||
envConfig
|
||||
}: {
|
||||
db: Knex;
|
||||
keyStore: TKeyStoreFactory;
|
||||
envConfig: TMigrationEnvConfig;
|
||||
}) => {
|
||||
export const getMigrationEncryptionServices = async ({ envConfig, db, keyStore }: TDependencies) => {
|
||||
// ----- DAL dependencies -----
|
||||
const orgDAL = orgDALFactory(db);
|
||||
const licenseDAL = licenseDALFactory(db);
|
||||
const permissionDAL = permissionDALFactory(db);
|
||||
const projectDAL = projectDALFactory(db);
|
||||
const folderCommitDAL = folderCommitDALFactory(db);
|
||||
const folderCommitChangesDAL = folderCommitChangesDALFactory(db);
|
||||
const folderCheckpointDAL = folderCheckpointDALFactory(db);
|
||||
const folderTreeCheckpointDAL = folderTreeCheckpointDALFactory(db);
|
||||
const roleDAL = roleDALFactory(db);
|
||||
const userDAL = userDALFactory(db);
|
||||
const identityDAL = identityDALFactory(db);
|
||||
const folderDAL = secretFolderDALFactory(db);
|
||||
const folderVersionDAL = secretFolderVersionDALFactory(db);
|
||||
const secretVersionV2BridgeDAL = secretVersionV2BridgeDALFactory(db);
|
||||
const folderCheckpointResourcesDAL = folderCheckpointResourcesDALFactory(db);
|
||||
const secretV2BridgeDAL = secretV2BridgeDALFactory({ db, keyStore });
|
||||
const folderTreeCheckpointResourcesDAL = folderTreeCheckpointResourcesDALFactory(db);
|
||||
const secretTagDAL = secretTagDALFactory(db);
|
||||
|
||||
const orgDAL = orgDALFactory(db);
|
||||
const serviceTokenDAL = serviceTokenDALFactory(db);
|
||||
const kmsRootConfigDAL = kmsRootConfigDALFactory(db);
|
||||
const kmsDAL = kmskeyDALFactory(db);
|
||||
const internalKmsDAL = internalKmsDALFactory(db);
|
||||
const resourceMetadataDAL = resourceMetadataDALFactory(db);
|
||||
|
||||
const hsmModule = initializeHsmModule(envConfig);
|
||||
hsmModule.initialize();
|
||||
// ----- Service dependencies -----
|
||||
const permissionService = permissionServiceFactory({
|
||||
permissionDAL,
|
||||
serviceTokenDAL,
|
||||
projectDAL,
|
||||
keyStore,
|
||||
roleDAL,
|
||||
userDAL,
|
||||
identityDAL
|
||||
});
|
||||
|
||||
const hsmService = hsmServiceFactory({
|
||||
hsmModule: hsmModule.getModule(),
|
||||
const licenseService = licenseServiceFactory({
|
||||
permissionService,
|
||||
orgDAL,
|
||||
licenseDAL,
|
||||
keyStore,
|
||||
projectDAL,
|
||||
envConfig
|
||||
});
|
||||
|
||||
// ----- HSM startup -----
|
||||
|
||||
const { hsmService } = await getMigrationHsmService({ envConfig });
|
||||
|
||||
const hsmStatus = await isHsmActiveAndEnabled({
|
||||
hsmService,
|
||||
kmsRootConfigDAL,
|
||||
licenseService
|
||||
});
|
||||
|
||||
// if the encryption strategy is software - user needs to provide an encryption key
|
||||
// if the encryption strategy is null AND the hsm is not configured - user needs to provide an encryption key
|
||||
const needsEncryptionKey =
|
||||
hsmStatus.rootKmsConfigEncryptionStrategy === RootKeyEncryptionStrategy.Software ||
|
||||
(hsmStatus.rootKmsConfigEncryptionStrategy === null && !hsmStatus.isHsmConfigured);
|
||||
|
||||
if (needsEncryptionKey) {
|
||||
if (!envConfig.ROOT_ENCRYPTION_KEY && !envConfig.ENCRYPTION_KEY) {
|
||||
throw new BadRequestError({
|
||||
message:
|
||||
"Root KMS encryption strategy is set to software. Please set the ENCRYPTION_KEY environment variable and restart your deployment.\nYou can enable HSM encryption in the Server Console."
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
// ----- KMS startup -----
|
||||
|
||||
const kmsService = kmsServiceFactory({
|
||||
kmsRootConfigDAL,
|
||||
keyStore,
|
||||
@@ -115,27 +118,7 @@ export const getMigrationPITServices = async ({
|
||||
envConfig
|
||||
});
|
||||
|
||||
await hsmService.startService();
|
||||
await kmsService.startService();
|
||||
await kmsService.startService(hsmStatus);
|
||||
|
||||
const folderCommitService = folderCommitServiceFactory({
|
||||
folderCommitDAL,
|
||||
folderCommitChangesDAL,
|
||||
folderCheckpointDAL,
|
||||
folderTreeCheckpointDAL,
|
||||
userDAL,
|
||||
identityDAL,
|
||||
folderDAL,
|
||||
folderVersionDAL,
|
||||
secretVersionV2BridgeDAL,
|
||||
projectDAL,
|
||||
folderCheckpointResourcesDAL,
|
||||
secretV2BridgeDAL,
|
||||
folderTreeCheckpointResourcesDAL,
|
||||
kmsService,
|
||||
secretTagDAL,
|
||||
resourceMetadataDAL
|
||||
});
|
||||
|
||||
return { folderCommitService };
|
||||
return { kmsService, hsmService };
|
||||
};
|
||||
|
||||
@@ -0,0 +1,30 @@
|
||||
// Code generated by automation script, DO NOT EDIT.
|
||||
// Automated by pulling database and generating zod schema
|
||||
// To update. Just run npm run generate:schema
|
||||
// Written by akhilmhdh.
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import { TImmutableDBKeys } from "./models";
|
||||
|
||||
export const AdditionalPrivilegesSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
name: z.string(),
|
||||
isTemporary: z.boolean().default(false),
|
||||
temporaryMode: z.string().nullable().optional(),
|
||||
temporaryRange: z.string().nullable().optional(),
|
||||
temporaryAccessStartTime: z.date().nullable().optional(),
|
||||
temporaryAccessEndTime: z.date().nullable().optional(),
|
||||
permissions: z.unknown(),
|
||||
actorUserId: z.string().uuid().nullable().optional(),
|
||||
actorIdentityId: z.string().uuid().nullable().optional(),
|
||||
orgId: z.string().uuid().nullable().optional(),
|
||||
projectId: z.string().nullable().optional(),
|
||||
namespaceId: z.string().uuid().nullable().optional(),
|
||||
createdAt: z.date(),
|
||||
updatedAt: z.date()
|
||||
});
|
||||
|
||||
export type TAdditionalPrivileges = z.infer<typeof AdditionalPrivilegesSchema>;
|
||||
export type TAdditionalPrivilegesInsert = Omit<z.input<typeof AdditionalPrivilegesSchema>, TImmutableDBKeys>;
|
||||
export type TAdditionalPrivilegesUpdate = Partial<Omit<z.input<typeof AdditionalPrivilegesSchema>, TImmutableDBKeys>>;
|
||||
@@ -26,7 +26,8 @@ export const CertificatesSchema = z.object({
|
||||
keyUsages: z.string().array().nullable().optional(),
|
||||
extendedKeyUsages: z.string().array().nullable().optional(),
|
||||
projectId: z.string(),
|
||||
pkiSubscriberId: z.string().uuid().nullable().optional()
|
||||
pkiSubscriberId: z.string().uuid().nullable().optional(),
|
||||
profileId: z.string().uuid().nullable().optional()
|
||||
});
|
||||
|
||||
export type TCertificates = z.infer<typeof CertificatesSchema>;
|
||||
|
||||
@@ -5,6 +5,8 @@
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import { zodBuffer } from "@app/lib/zod";
|
||||
|
||||
import { TImmutableDBKeys } from "./models";
|
||||
|
||||
export const GatewaysV2Schema = z.object({
|
||||
@@ -15,7 +17,9 @@ export const GatewaysV2Schema = z.object({
|
||||
identityId: z.string().uuid(),
|
||||
relayId: z.string().uuid().nullable().optional(),
|
||||
name: z.string(),
|
||||
heartbeat: z.date().nullable().optional()
|
||||
heartbeat: z.date().nullable().optional(),
|
||||
encryptedPamSessionKey: zodBuffer.nullable().optional(),
|
||||
healthAlertedAt: z.date().nullable().optional()
|
||||
});
|
||||
|
||||
export type TGatewaysV2 = z.infer<typeof GatewaysV2Schema>;
|
||||
|
||||
@@ -13,7 +13,8 @@ export const IdentitiesSchema = z.object({
|
||||
authMethod: z.string().nullable().optional(),
|
||||
createdAt: z.date(),
|
||||
updatedAt: z.date(),
|
||||
hasDeleteProtection: z.boolean().default(false)
|
||||
hasDeleteProtection: z.boolean().default(false),
|
||||
orgId: z.string().uuid()
|
||||
});
|
||||
|
||||
export type TIdentities = z.infer<typeof IdentitiesSchema>;
|
||||
|
||||
@@ -3,6 +3,7 @@ export * from "./access-approval-policies-approvers";
|
||||
export * from "./access-approval-policies-bypassers";
|
||||
export * from "./access-approval-requests";
|
||||
export * from "./access-approval-requests-reviewers";
|
||||
export * from "./additional-privileges";
|
||||
export * from "./api-keys";
|
||||
export * from "./app-connections";
|
||||
export * from "./audit-log-streams";
|
||||
@@ -73,8 +74,11 @@ export * from "./kms-keys";
|
||||
export * from "./kms-root-config";
|
||||
export * from "./ldap-configs";
|
||||
export * from "./ldap-group-maps";
|
||||
export * from "./membership-roles";
|
||||
export * from "./memberships";
|
||||
export * from "./microsoft-teams-integrations";
|
||||
export * from "./models";
|
||||
export * from "./namespaces";
|
||||
export * from "./oidc-configs";
|
||||
export * from "./org-bots";
|
||||
export * from "./org-gateway-config";
|
||||
@@ -83,9 +87,17 @@ export * from "./org-memberships";
|
||||
export * from "./org-relay-config";
|
||||
export * from "./org-roles";
|
||||
export * from "./organizations";
|
||||
export * from "./pam-accounts";
|
||||
export * from "./pam-folders";
|
||||
export * from "./pam-resources";
|
||||
export * from "./pam-sessions";
|
||||
export * from "./pki-alerts";
|
||||
export * from "./pki-api-enrollment-configs";
|
||||
export * from "./pki-certificate-profiles";
|
||||
export * from "./pki-certificate-templates-v2";
|
||||
export * from "./pki-collection-items";
|
||||
export * from "./pki-collections";
|
||||
export * from "./pki-est-enrollment-configs";
|
||||
export * from "./pki-subscribers";
|
||||
export * from "./pki-syncs";
|
||||
export * from "./project-bots";
|
||||
@@ -104,6 +116,7 @@ export * from "./projects";
|
||||
export * from "./rate-limit";
|
||||
export * from "./relays";
|
||||
export * from "./resource-metadata";
|
||||
export * from "./roles";
|
||||
export * from "./saml-configs";
|
||||
export * from "./scim-tokens";
|
||||
export * from "./secret-approval-policies";
|
||||
@@ -167,5 +180,6 @@ export * from "./user-aliases";
|
||||
export * from "./user-encryption-keys";
|
||||
export * from "./user-group-membership";
|
||||
export * from "./users";
|
||||
export * from "./vault-external-migration-configs";
|
||||
export * from "./webhooks";
|
||||
export * from "./workflow-integrations";
|
||||
|
||||
@@ -17,7 +17,8 @@ export const KmsKeysSchema = z.object({
|
||||
createdAt: z.date(),
|
||||
updatedAt: z.date(),
|
||||
projectId: z.string().nullable().optional(),
|
||||
keyUsage: z.string().default("encrypt-decrypt")
|
||||
keyUsage: z.string().default("encrypt-decrypt"),
|
||||
kmipMetadata: z.unknown().nullable().optional()
|
||||
});
|
||||
|
||||
export type TKmsKeys = z.infer<typeof KmsKeysSchema>;
|
||||
|
||||
@@ -0,0 +1,26 @@
|
||||
// Code generated by automation script, DO NOT EDIT.
|
||||
// Automated by pulling database and generating zod schema
|
||||
// To update. Just run npm run generate:schema
|
||||
// Written by akhilmhdh.
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import { TImmutableDBKeys } from "./models";
|
||||
|
||||
export const MembershipRolesSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
role: z.string(),
|
||||
isTemporary: z.boolean().default(false),
|
||||
temporaryMode: z.string().nullable().optional(),
|
||||
temporaryRange: z.string().nullable().optional(),
|
||||
temporaryAccessStartTime: z.date().nullable().optional(),
|
||||
temporaryAccessEndTime: z.date().nullable().optional(),
|
||||
customRoleId: z.string().uuid().nullable().optional(),
|
||||
membershipId: z.string().uuid(),
|
||||
createdAt: z.date(),
|
||||
updatedAt: z.date()
|
||||
});
|
||||
|
||||
export type TMembershipRoles = z.infer<typeof MembershipRolesSchema>;
|
||||
export type TMembershipRolesInsert = Omit<z.input<typeof MembershipRolesSchema>, TImmutableDBKeys>;
|
||||
export type TMembershipRolesUpdate = Partial<Omit<z.input<typeof MembershipRolesSchema>, TImmutableDBKeys>>;
|
||||
@@ -0,0 +1,32 @@
|
||||
// Code generated by automation script, DO NOT EDIT.
|
||||
// Automated by pulling database and generating zod schema
|
||||
// To update. Just run npm run generate:schema
|
||||
// Written by akhilmhdh.
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import { TImmutableDBKeys } from "./models";
|
||||
|
||||
export const MembershipsSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
scope: z.string(),
|
||||
actorUserId: z.string().uuid().nullable().optional(),
|
||||
actorIdentityId: z.string().uuid().nullable().optional(),
|
||||
actorGroupId: z.string().uuid().nullable().optional(),
|
||||
scopeOrgId: z.string().uuid(),
|
||||
scopeProjectId: z.string().nullable().optional(),
|
||||
scopeNamespaceId: z.string().uuid().nullable().optional(),
|
||||
isActive: z.boolean().default(true),
|
||||
status: z.string().nullable().optional(),
|
||||
inviteEmail: z.string().nullable().optional(),
|
||||
lastInvitedAt: z.date().nullable().optional(),
|
||||
lastLoginAuthMethod: z.string().nullable().optional(),
|
||||
lastLoginTime: z.date().nullable().optional(),
|
||||
projectFavorites: z.string().array().nullable().optional(),
|
||||
createdAt: z.date(),
|
||||
updatedAt: z.date()
|
||||
});
|
||||
|
||||
export type TMemberships = z.infer<typeof MembershipsSchema>;
|
||||
export type TMembershipsInsert = Omit<z.input<typeof MembershipsSchema>, TImmutableDBKeys>;
|
||||
export type TMembershipsUpdate = Partial<Omit<z.input<typeof MembershipsSchema>, TImmutableDBKeys>>;
|
||||
@@ -23,6 +23,10 @@ export enum TableName {
|
||||
CertificateBody = "certificate_bodies",
|
||||
CertificateSecret = "certificate_secrets",
|
||||
CertificateTemplate = "certificate_templates",
|
||||
PkiCertificateTemplateV2 = "pki_certificate_templates_v2",
|
||||
PkiCertificateProfile = "pki_certificate_profiles",
|
||||
PkiEstEnrollmentConfig = "pki_est_enrollment_configs",
|
||||
PkiApiEnrollmentConfig = "pki_api_enrollment_configs",
|
||||
PkiSubscriber = "pki_subscribers",
|
||||
PkiAlert = "pki_alerts",
|
||||
PkiCollection = "pki_collections",
|
||||
@@ -178,6 +182,14 @@ export enum TableName {
|
||||
SecretScanningScan = "secret_scanning_scans",
|
||||
SecretScanningFinding = "secret_scanning_findings",
|
||||
SecretScanningConfig = "secret_scanning_configs",
|
||||
|
||||
Membership = "memberships",
|
||||
MembershipRole = "membership_roles",
|
||||
Role = "roles",
|
||||
AdditionalPrivilege = "additional_privileges",
|
||||
|
||||
Namespace = "namespaces",
|
||||
|
||||
// reminders
|
||||
Reminder = "reminders",
|
||||
ReminderRecipient = "reminders_recipients",
|
||||
@@ -189,7 +201,15 @@ export enum TableName {
|
||||
Relay = "relays",
|
||||
GatewayV2 = "gateways_v2",
|
||||
|
||||
KeyValueStore = "key_value_store"
|
||||
KeyValueStore = "key_value_store",
|
||||
|
||||
// PAM
|
||||
PamFolder = "pam_folders",
|
||||
PamResource = "pam_resources",
|
||||
PamAccount = "pam_accounts",
|
||||
PamSession = "pam_sessions",
|
||||
|
||||
VaultExternalMigrationConfig = "vault_external_migration_configs"
|
||||
}
|
||||
|
||||
export type TImmutableDBKeys = "id" | "createdAt" | "updatedAt" | "commitId";
|
||||
@@ -281,7 +301,8 @@ export enum ProjectType {
|
||||
CertificateManager = "cert-manager",
|
||||
KMS = "kms",
|
||||
SSH = "ssh",
|
||||
SecretScanning = "secret-scanning"
|
||||
SecretScanning = "secret-scanning",
|
||||
PAM = "pam"
|
||||
}
|
||||
|
||||
export enum ActionProjectType {
|
||||
@@ -290,11 +311,50 @@ export enum ActionProjectType {
|
||||
KMS = ProjectType.KMS,
|
||||
SSH = ProjectType.SSH,
|
||||
SecretScanning = ProjectType.SecretScanning,
|
||||
PAM = ProjectType.PAM,
|
||||
// project operations that happen on all types
|
||||
Any = "any"
|
||||
}
|
||||
|
||||
export enum OrganizationActionScope {
|
||||
ChildOrganization = "child-organization-only",
|
||||
ParentOrganization = "parent-organization-only",
|
||||
Any = "any"
|
||||
}
|
||||
|
||||
export enum TemporaryPermissionMode {
|
||||
Relative = "relative"
|
||||
}
|
||||
|
||||
export enum MembershipActors {
|
||||
Group = "group",
|
||||
User = "user",
|
||||
Identity = "identity"
|
||||
}
|
||||
|
||||
export enum SortDirection {
|
||||
ASC = "asc",
|
||||
DESC = "desc"
|
||||
}
|
||||
|
||||
export enum AccessScope {
|
||||
Organization = "organization",
|
||||
Namespace = "namespace",
|
||||
Project = "project"
|
||||
}
|
||||
|
||||
export type AccessScopeData =
|
||||
| {
|
||||
scope: AccessScope.Organization;
|
||||
orgId: string;
|
||||
}
|
||||
| {
|
||||
scope: AccessScope.Namespace;
|
||||
orgId: string;
|
||||
namespaceId: string;
|
||||
}
|
||||
| {
|
||||
scope: AccessScope.Project;
|
||||
orgId: string;
|
||||
projectId: string;
|
||||
};
|
||||
|
||||
@@ -0,0 +1,21 @@
|
||||
// Code generated by automation script, DO NOT EDIT.
|
||||
// Automated by pulling database and generating zod schema
|
||||
// To update. Just run npm run generate:schema
|
||||
// Written by akhilmhdh.
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import { TImmutableDBKeys } from "./models";
|
||||
|
||||
export const NamespacesSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
name: z.string(),
|
||||
description: z.string().nullable().optional(),
|
||||
orgId: z.string().uuid(),
|
||||
createdAt: z.date(),
|
||||
updatedAt: z.date()
|
||||
});
|
||||
|
||||
export type TNamespaces = z.infer<typeof NamespacesSchema>;
|
||||
export type TNamespacesInsert = Omit<z.input<typeof NamespacesSchema>, TImmutableDBKeys>;
|
||||
export type TNamespacesUpdate = Partial<Omit<z.input<typeof NamespacesSchema>, TImmutableDBKeys>>;
|
||||
@@ -38,7 +38,9 @@ export const OrganizationsSchema = z.object({
|
||||
maxSharedSecretLifetime: z.number().default(2592000).nullable().optional(),
|
||||
maxSharedSecretViewLimit: z.number().nullable().optional(),
|
||||
googleSsoAuthEnforced: z.boolean().default(false),
|
||||
googleSsoAuthLastUsed: z.date().nullable().optional()
|
||||
googleSsoAuthLastUsed: z.date().nullable().optional(),
|
||||
parentOrgId: z.string().uuid().nullable().optional(),
|
||||
rootOrgId: z.string().uuid().nullable().optional()
|
||||
});
|
||||
|
||||
export type TOrganizations = z.infer<typeof OrganizationsSchema>;
|
||||
|
||||
@@ -0,0 +1,29 @@
|
||||
// Code generated by automation script, DO NOT EDIT.
|
||||
// Automated by pulling database and generating zod schema
|
||||
// To update. Just run npm run generate:schema
|
||||
// Written by akhilmhdh.
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import { zodBuffer } from "@app/lib/zod";
|
||||
|
||||
import { TImmutableDBKeys } from "./models";
|
||||
|
||||
export const PamAccountsSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
projectId: z.string(),
|
||||
folderId: z.string().uuid().nullable().optional(),
|
||||
resourceId: z.string().uuid(),
|
||||
name: z.string(),
|
||||
description: z.string().nullable().optional(),
|
||||
encryptedCredentials: zodBuffer,
|
||||
createdAt: z.date(),
|
||||
updatedAt: z.date(),
|
||||
rotationEnabled: z.boolean().default(false),
|
||||
rotationIntervalSeconds: z.number().nullable().optional(),
|
||||
lastRotatedAt: z.date().nullable().optional()
|
||||
});
|
||||
|
||||
export type TPamAccounts = z.infer<typeof PamAccountsSchema>;
|
||||
export type TPamAccountsInsert = Omit<z.input<typeof PamAccountsSchema>, TImmutableDBKeys>;
|
||||
export type TPamAccountsUpdate = Partial<Omit<z.input<typeof PamAccountsSchema>, TImmutableDBKeys>>;
|
||||
@@ -0,0 +1,22 @@
|
||||
// Code generated by automation script, DO NOT EDIT.
|
||||
// Automated by pulling database and generating zod schema
|
||||
// To update. Just run npm run generate:schema
|
||||
// Written by akhilmhdh.
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import { TImmutableDBKeys } from "./models";
|
||||
|
||||
export const PamFoldersSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
projectId: z.string(),
|
||||
parentId: z.string().uuid().nullable().optional(),
|
||||
name: z.string(),
|
||||
description: z.string().nullable().optional(),
|
||||
createdAt: z.date(),
|
||||
updatedAt: z.date()
|
||||
});
|
||||
|
||||
export type TPamFolders = z.infer<typeof PamFoldersSchema>;
|
||||
export type TPamFoldersInsert = Omit<z.input<typeof PamFoldersSchema>, TImmutableDBKeys>;
|
||||
export type TPamFoldersUpdate = Partial<Omit<z.input<typeof PamFoldersSchema>, TImmutableDBKeys>>;
|
||||
@@ -0,0 +1,26 @@
|
||||
// Code generated by automation script, DO NOT EDIT.
|
||||
// Automated by pulling database and generating zod schema
|
||||
// To update. Just run npm run generate:schema
|
||||
// Written by akhilmhdh.
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import { zodBuffer } from "@app/lib/zod";
|
||||
|
||||
import { TImmutableDBKeys } from "./models";
|
||||
|
||||
export const PamResourcesSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
projectId: z.string(),
|
||||
name: z.string(),
|
||||
gatewayId: z.string().uuid(),
|
||||
resourceType: z.string(),
|
||||
encryptedConnectionDetails: zodBuffer,
|
||||
createdAt: z.date(),
|
||||
updatedAt: z.date(),
|
||||
encryptedRotationAccountCredentials: zodBuffer.nullable().optional()
|
||||
});
|
||||
|
||||
export type TPamResources = z.infer<typeof PamResourcesSchema>;
|
||||
export type TPamResourcesInsert = Omit<z.input<typeof PamResourcesSchema>, TImmutableDBKeys>;
|
||||
export type TPamResourcesUpdate = Partial<Omit<z.input<typeof PamResourcesSchema>, TImmutableDBKeys>>;
|
||||
@@ -0,0 +1,35 @@
|
||||
// Code generated by automation script, DO NOT EDIT.
|
||||
// Automated by pulling database and generating zod schema
|
||||
// To update. Just run npm run generate:schema
|
||||
// Written by akhilmhdh.
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import { zodBuffer } from "@app/lib/zod";
|
||||
|
||||
import { TImmutableDBKeys } from "./models";
|
||||
|
||||
export const PamSessionsSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
projectId: z.string(),
|
||||
accountId: z.string().uuid().nullable().optional(),
|
||||
resourceType: z.string(),
|
||||
resourceName: z.string(),
|
||||
accountName: z.string(),
|
||||
userId: z.string().uuid().nullable().optional(),
|
||||
actorName: z.string(),
|
||||
actorEmail: z.string(),
|
||||
actorIp: z.string(),
|
||||
actorUserAgent: z.string(),
|
||||
status: z.string(),
|
||||
encryptedLogsBlob: zodBuffer.nullable().optional(),
|
||||
expiresAt: z.date(),
|
||||
startedAt: z.date().nullable().optional(),
|
||||
endedAt: z.date().nullable().optional(),
|
||||
createdAt: z.date(),
|
||||
updatedAt: z.date()
|
||||
});
|
||||
|
||||
export type TPamSessions = z.infer<typeof PamSessionsSchema>;
|
||||
export type TPamSessionsInsert = Omit<z.input<typeof PamSessionsSchema>, TImmutableDBKeys>;
|
||||
export type TPamSessionsUpdate = Partial<Omit<z.input<typeof PamSessionsSchema>, TImmutableDBKeys>>;
|
||||
@@ -0,0 +1,22 @@
|
||||
// Code generated by automation script, DO NOT EDIT.
|
||||
// Automated by pulling database and generating zod schema
|
||||
// To update. Just run npm run generate:schema
|
||||
// Written by akhilmhdh.
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import { TImmutableDBKeys } from "./models";
|
||||
|
||||
export const PkiApiEnrollmentConfigsSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
autoRenew: z.boolean().default(false).nullable().optional(),
|
||||
autoRenewDays: z.number().nullable().optional(),
|
||||
createdAt: z.date(),
|
||||
updatedAt: z.date()
|
||||
});
|
||||
|
||||
export type TPkiApiEnrollmentConfigs = z.infer<typeof PkiApiEnrollmentConfigsSchema>;
|
||||
export type TPkiApiEnrollmentConfigsInsert = Omit<z.input<typeof PkiApiEnrollmentConfigsSchema>, TImmutableDBKeys>;
|
||||
export type TPkiApiEnrollmentConfigsUpdate = Partial<
|
||||
Omit<z.input<typeof PkiApiEnrollmentConfigsSchema>, TImmutableDBKeys>
|
||||
>;
|
||||
@@ -0,0 +1,28 @@
|
||||
// Code generated by automation script, DO NOT EDIT.
|
||||
// Automated by pulling database and generating zod schema
|
||||
// To update. Just run npm run generate:schema
|
||||
// Written by akhilmhdh.
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import { TImmutableDBKeys } from "./models";
|
||||
|
||||
export const PkiCertificateProfilesSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
projectId: z.string(),
|
||||
caId: z.string().uuid(),
|
||||
certificateTemplateId: z.string().uuid(),
|
||||
slug: z.string(),
|
||||
description: z.string().nullable().optional(),
|
||||
enrollmentType: z.string(),
|
||||
estConfigId: z.string().uuid().nullable().optional(),
|
||||
apiConfigId: z.string().uuid().nullable().optional(),
|
||||
createdAt: z.date(),
|
||||
updatedAt: z.date()
|
||||
});
|
||||
|
||||
export type TPkiCertificateProfiles = z.infer<typeof PkiCertificateProfilesSchema>;
|
||||
export type TPkiCertificateProfilesInsert = Omit<z.input<typeof PkiCertificateProfilesSchema>, TImmutableDBKeys>;
|
||||
export type TPkiCertificateProfilesUpdate = Partial<
|
||||
Omit<z.input<typeof PkiCertificateProfilesSchema>, TImmutableDBKeys>
|
||||
>;
|
||||
@@ -0,0 +1,29 @@
|
||||
// Code generated by automation script, DO NOT EDIT.
|
||||
// Automated by pulling database and generating zod schema
|
||||
// To update. Just run npm run generate:schema
|
||||
// Written by akhilmhdh.
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import { TImmutableDBKeys } from "./models";
|
||||
|
||||
export const PkiCertificateTemplatesV2Schema = z.object({
|
||||
id: z.string().uuid(),
|
||||
projectId: z.string(),
|
||||
name: z.string(),
|
||||
description: z.string().nullable().optional(),
|
||||
subject: z.unknown().nullable().optional(),
|
||||
sans: z.unknown().nullable().optional(),
|
||||
keyUsages: z.unknown().nullable().optional(),
|
||||
extendedKeyUsages: z.unknown().nullable().optional(),
|
||||
algorithms: z.unknown().nullable().optional(),
|
||||
validity: z.unknown().nullable().optional(),
|
||||
createdAt: z.date(),
|
||||
updatedAt: z.date()
|
||||
});
|
||||
|
||||
export type TPkiCertificateTemplatesV2 = z.infer<typeof PkiCertificateTemplatesV2Schema>;
|
||||
export type TPkiCertificateTemplatesV2Insert = Omit<z.input<typeof PkiCertificateTemplatesV2Schema>, TImmutableDBKeys>;
|
||||
export type TPkiCertificateTemplatesV2Update = Partial<
|
||||
Omit<z.input<typeof PkiCertificateTemplatesV2Schema>, TImmutableDBKeys>
|
||||
>;
|
||||
@@ -0,0 +1,25 @@
|
||||
// Code generated by automation script, DO NOT EDIT.
|
||||
// Automated by pulling database and generating zod schema
|
||||
// To update. Just run npm run generate:schema
|
||||
// Written by akhilmhdh.
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import { zodBuffer } from "@app/lib/zod";
|
||||
|
||||
import { TImmutableDBKeys } from "./models";
|
||||
|
||||
export const PkiEstEnrollmentConfigsSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
disableBootstrapCaValidation: z.boolean().default(false).nullable().optional(),
|
||||
hashedPassphrase: z.string(),
|
||||
encryptedCaChain: zodBuffer.nullable().optional(),
|
||||
createdAt: z.date(),
|
||||
updatedAt: z.date()
|
||||
});
|
||||
|
||||
export type TPkiEstEnrollmentConfigs = z.infer<typeof PkiEstEnrollmentConfigsSchema>;
|
||||
export type TPkiEstEnrollmentConfigsInsert = Omit<z.input<typeof PkiEstEnrollmentConfigsSchema>, TImmutableDBKeys>;
|
||||
export type TPkiEstEnrollmentConfigsUpdate = Partial<
|
||||
Omit<z.input<typeof PkiEstEnrollmentConfigsSchema>, TImmutableDBKeys>
|
||||
>;
|
||||
@@ -14,7 +14,9 @@ export const RelaysSchema = z.object({
|
||||
orgId: z.string().uuid().nullable().optional(),
|
||||
identityId: z.string().uuid().nullable().optional(),
|
||||
name: z.string(),
|
||||
host: z.string()
|
||||
host: z.string(),
|
||||
heartbeat: z.date().nullable().optional(),
|
||||
healthAlertedAt: z.date().nullable().optional()
|
||||
});
|
||||
|
||||
export type TRelays = z.infer<typeof RelaysSchema>;
|
||||
|
||||
@@ -0,0 +1,25 @@
|
||||
// Code generated by automation script, DO NOT EDIT.
|
||||
// Automated by pulling database and generating zod schema
|
||||
// To update. Just run npm run generate:schema
|
||||
// Written by akhilmhdh.
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import { TImmutableDBKeys } from "./models";
|
||||
|
||||
export const RolesSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
name: z.string(),
|
||||
description: z.string().nullable().optional(),
|
||||
slug: z.string(),
|
||||
permissions: z.unknown(),
|
||||
orgId: z.string().uuid().nullable().optional(),
|
||||
projectId: z.string().nullable().optional(),
|
||||
namespaceId: z.string().uuid().nullable().optional(),
|
||||
createdAt: z.date(),
|
||||
updatedAt: z.date()
|
||||
});
|
||||
|
||||
export type TRoles = z.infer<typeof RolesSchema>;
|
||||
export type TRolesInsert = Omit<z.input<typeof RolesSchema>, TImmutableDBKeys>;
|
||||
export type TRolesUpdate = Partial<Omit<z.input<typeof RolesSchema>, TImmutableDBKeys>>;
|
||||
@@ -0,0 +1,27 @@
|
||||
// Code generated by automation script, DO NOT EDIT.
|
||||
// Automated by pulling database and generating zod schema
|
||||
// To update. Just run npm run generate:schema
|
||||
// Written by akhilmhdh.
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import { TImmutableDBKeys } from "./models";
|
||||
|
||||
export const UserNotificationsDefaultSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
userId: z.string().uuid(),
|
||||
orgId: z.string().uuid().nullable().optional(),
|
||||
type: z.string(),
|
||||
title: z.string(),
|
||||
body: z.string().nullable().optional(),
|
||||
link: z.string().nullable().optional(),
|
||||
isRead: z.boolean().default(false),
|
||||
createdAt: z.date(),
|
||||
updatedAt: z.date()
|
||||
});
|
||||
|
||||
export type TUserNotificationsDefault = z.infer<typeof UserNotificationsDefaultSchema>;
|
||||
export type TUserNotificationsDefaultInsert = Omit<z.input<typeof UserNotificationsDefaultSchema>, TImmutableDBKeys>;
|
||||
export type TUserNotificationsDefaultUpdate = Partial<
|
||||
Omit<z.input<typeof UserNotificationsDefaultSchema>, TImmutableDBKeys>
|
||||
>;
|
||||
@@ -0,0 +1,26 @@
|
||||
// Code generated by automation script, DO NOT EDIT.
|
||||
// Automated by pulling database and generating zod schema
|
||||
// To update. Just run npm run generate:schema
|
||||
// Written by akhilmhdh.
|
||||
|
||||
import { z } from "zod";
|
||||
|
||||
import { TImmutableDBKeys } from "./models";
|
||||
|
||||
export const VaultExternalMigrationConfigsSchema = z.object({
|
||||
id: z.string().uuid(),
|
||||
orgId: z.string().uuid(),
|
||||
namespace: z.string(),
|
||||
connectionId: z.string().uuid().nullable().optional(),
|
||||
createdAt: z.date(),
|
||||
updatedAt: z.date()
|
||||
});
|
||||
|
||||
export type TVaultExternalMigrationConfigs = z.infer<typeof VaultExternalMigrationConfigsSchema>;
|
||||
export type TVaultExternalMigrationConfigsInsert = Omit<
|
||||
z.input<typeof VaultExternalMigrationConfigsSchema>,
|
||||
TImmutableDBKeys
|
||||
>;
|
||||
export type TVaultExternalMigrationConfigsUpdate = Partial<
|
||||
Omit<z.input<typeof VaultExternalMigrationConfigsSchema>, TImmutableDBKeys>
|
||||
>;
|
||||
@@ -1,7 +1,10 @@
|
||||
import { Knex } from "knex";
|
||||
|
||||
import { initEnvConfig } from "@app/lib/config/env";
|
||||
import { initializeHsmModule } from "@app/ee/services/hsm/hsm-fns";
|
||||
import { hsmServiceFactory } from "@app/ee/services/hsm/hsm-service";
|
||||
import { getHsmConfig, initEnvConfig } from "@app/lib/config/env";
|
||||
import { initLogger, logger } from "@app/lib/logger";
|
||||
import { kmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";
|
||||
import { superAdminDALFactory } from "@app/services/super-admin/super-admin-dal";
|
||||
|
||||
import { AuthMethod } from "../../services/auth/auth-type";
|
||||
@@ -17,7 +20,21 @@ export async function seed(knex: Knex): Promise<void> {
|
||||
initLogger();
|
||||
|
||||
const superAdminDAL = superAdminDALFactory(knex);
|
||||
await initEnvConfig(superAdminDAL, logger);
|
||||
const kmsRootConfigDAL = kmsRootConfigDALFactory(knex);
|
||||
|
||||
const hsmConfig = getHsmConfig(logger);
|
||||
|
||||
const hsmModule = initializeHsmModule(hsmConfig);
|
||||
hsmModule.initialize();
|
||||
|
||||
const hsmService = hsmServiceFactory({
|
||||
hsmModule: hsmModule.getModule(),
|
||||
envConfig: hsmConfig
|
||||
});
|
||||
|
||||
await hsmService.startService();
|
||||
|
||||
await initEnvConfig(hsmService, kmsRootConfigDAL, superAdminDAL, logger);
|
||||
|
||||
await knex(TableName.SuperAdmin).insert([
|
||||
// eslint-disable-next-line
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Knex } from "knex";
|
||||
|
||||
import { OrgMembershipRole, OrgMembershipStatus, TableName } from "../schemas";
|
||||
import { AccessScope, OrgMembershipRole, OrgMembershipStatus, TableName } from "../schemas";
|
||||
import { seedData1 } from "../seed-data";
|
||||
|
||||
export async function seed(knex: Knex): Promise<void> {
|
||||
@@ -24,13 +24,22 @@ export async function seed(knex: Knex): Promise<void> {
|
||||
])
|
||||
.returning("*");
|
||||
|
||||
await knex(TableName.OrgMembership).insert([
|
||||
const [membership] = await knex(TableName.Membership)
|
||||
.insert([
|
||||
{
|
||||
scope: AccessScope.Organization,
|
||||
scopeOrgId: org.id,
|
||||
actorUserId: user.id,
|
||||
isActive: true,
|
||||
status: OrgMembershipStatus.Accepted
|
||||
}
|
||||
])
|
||||
.returning("*");
|
||||
|
||||
await knex(TableName.MembershipRole).insert([
|
||||
{
|
||||
role: OrgMembershipRole.Admin,
|
||||
orgId: org.id,
|
||||
status: OrgMembershipStatus.Accepted,
|
||||
userId: user.id,
|
||||
isActive: true
|
||||
membershipId: membership.id,
|
||||
role: OrgMembershipRole.Admin
|
||||
}
|
||||
]);
|
||||
}
|
||||
|
||||
@@ -1,19 +1,23 @@
|
||||
import { Knex } from "knex";
|
||||
|
||||
import { initEnvConfig } from "@app/lib/config/env";
|
||||
import { initializeHsmModule } from "@app/ee/services/hsm/hsm-fns";
|
||||
import { hsmServiceFactory } from "@app/ee/services/hsm/hsm-service";
|
||||
import { getHsmConfig, initEnvConfig } from "@app/lib/config/env";
|
||||
import { crypto, SymmetricKeySize } from "@app/lib/crypto/cryptography";
|
||||
import { generateUserSrpKeys } from "@app/lib/crypto/srp";
|
||||
import { initLogger, logger } from "@app/lib/logger";
|
||||
import { alphaNumericNanoId } from "@app/lib/nanoid";
|
||||
import { AuthMethod } from "@app/services/auth/auth-type";
|
||||
import { kmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";
|
||||
import { membershipRoleDALFactory } from "@app/services/membership/membership-role-dal";
|
||||
import { membershipUserDALFactory } from "@app/services/membership-user/membership-user-dal";
|
||||
import { assignWorkspaceKeysToMembers, createProjectKey } from "@app/services/project/project-fns";
|
||||
import { projectKeyDALFactory } from "@app/services/project-key/project-key-dal";
|
||||
import { projectMembershipDALFactory } from "@app/services/project-membership/project-membership-dal";
|
||||
import { projectUserMembershipRoleDALFactory } from "@app/services/project-membership/project-user-membership-role-dal";
|
||||
import { superAdminDALFactory } from "@app/services/super-admin/super-admin-dal";
|
||||
import { userDALFactory } from "@app/services/user/user-dal";
|
||||
|
||||
import {
|
||||
AccessScope,
|
||||
OrgMembershipRole,
|
||||
OrgMembershipStatus,
|
||||
ProjectMembershipRole,
|
||||
@@ -39,8 +43,8 @@ const createUserWithGhostUser = async (
|
||||
) => {
|
||||
const projectKeyDAL = projectKeyDALFactory(knex);
|
||||
const userDAL = userDALFactory(knex);
|
||||
const projectMembershipDAL = projectMembershipDALFactory(knex);
|
||||
const projectUserMembershipRoleDAL = projectUserMembershipRoleDALFactory(knex);
|
||||
const membershipDAL = membershipUserDALFactory(knex);
|
||||
const membershipRoleDAL = membershipRoleDALFactory(knex);
|
||||
|
||||
const email = `sudo-${alphaNumericNanoId(16)}-${orgId}@infisical.com`; // We add a nanoid because the email is unique. And we have to create a new ghost user each time, so we can have access to the private key.
|
||||
|
||||
@@ -63,25 +67,36 @@ const createUserWithGhostUser = async (
|
||||
.onConflict("userId")
|
||||
.merge();
|
||||
|
||||
await knex(TableName.OrgMembership)
|
||||
const [orgMembership] = await knex(TableName.Membership)
|
||||
.insert({
|
||||
orgId,
|
||||
userId: ghostUser.id,
|
||||
role: OrgMembershipRole.Admin,
|
||||
scope: AccessScope.Organization,
|
||||
scopeOrgId: orgId,
|
||||
actorUserId: ghostUser.id,
|
||||
status: OrgMembershipStatus.Accepted,
|
||||
isActive: true
|
||||
})
|
||||
.returning("*");
|
||||
|
||||
const [projectMembership] = await knex(TableName.ProjectMembership)
|
||||
await knex(TableName.MembershipRole).insert([
|
||||
{
|
||||
membershipId: orgMembership.id,
|
||||
role: OrgMembershipRole.Admin
|
||||
}
|
||||
]);
|
||||
|
||||
const [projectMembership] = await knex(TableName.Membership)
|
||||
.insert({
|
||||
userId: ghostUser.id,
|
||||
projectId
|
||||
actorUserId: ghostUser.id,
|
||||
scopeProjectId: projectId,
|
||||
scope: AccessScope.Project,
|
||||
scopeOrgId: orgId,
|
||||
status: OrgMembershipStatus.Accepted,
|
||||
isActive: true
|
||||
})
|
||||
.returning("*");
|
||||
|
||||
await knex(TableName.ProjectUserMembershipRole).insert({
|
||||
projectMembershipId: projectMembership.id,
|
||||
await knex(TableName.MembershipRole).insert({
|
||||
membershipId: projectMembership.id,
|
||||
role: ProjectMembershipRole.Admin
|
||||
});
|
||||
|
||||
@@ -142,17 +157,16 @@ const createUserWithGhostUser = async (
|
||||
});
|
||||
|
||||
// Create a membership for the user
|
||||
const userProjectMembership = await projectMembershipDAL.create(
|
||||
const userProjectMembership = await membershipDAL.create(
|
||||
{
|
||||
projectId,
|
||||
userId: user.id
|
||||
scopeProjectId: projectId,
|
||||
scope: AccessScope.Project,
|
||||
actorUserId: user.id,
|
||||
scopeOrgId: orgId
|
||||
},
|
||||
knex
|
||||
);
|
||||
await projectUserMembershipRoleDAL.create(
|
||||
{ projectMembershipId: userProjectMembership.id, role: ProjectMembershipRole.Admin },
|
||||
knex
|
||||
);
|
||||
await membershipRoleDAL.create({ membershipId: userProjectMembership.id, role: ProjectMembershipRole.Admin }, knex);
|
||||
|
||||
// Create a project key for the user
|
||||
await projectKeyDAL.create(
|
||||
@@ -181,7 +195,21 @@ export async function seed(knex: Knex): Promise<void> {
|
||||
initLogger();
|
||||
|
||||
const superAdminDAL = superAdminDALFactory(knex);
|
||||
await initEnvConfig(superAdminDAL, logger);
|
||||
const kmsRootConfigDAL = kmsRootConfigDALFactory(knex);
|
||||
|
||||
const hsmConfig = getHsmConfig(logger);
|
||||
|
||||
const hsmModule = initializeHsmModule(hsmConfig);
|
||||
hsmModule.initialize();
|
||||
|
||||
const hsmService = hsmServiceFactory({
|
||||
hsmModule: hsmModule.getModule(),
|
||||
envConfig: hsmConfig
|
||||
});
|
||||
|
||||
await hsmService.startService();
|
||||
|
||||
await initEnvConfig(hsmService, kmsRootConfigDAL, superAdminDAL, logger);
|
||||
|
||||
const [project] = await knex(TableName.Project)
|
||||
.insert({
|
||||
@@ -195,10 +223,11 @@ export async function seed(knex: Knex): Promise<void> {
|
||||
})
|
||||
.returning("*");
|
||||
|
||||
const userOrgMembership = await knex(TableName.OrgMembership)
|
||||
const userOrgMembership = await knex(TableName.Membership)
|
||||
.where({
|
||||
orgId: seedData1.organization.id,
|
||||
userId: seedData1.id
|
||||
scopeOrgId: seedData1.organization.id,
|
||||
actorUserId: seedData1.id,
|
||||
scope: AccessScope.Organization
|
||||
})
|
||||
.first();
|
||||
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Knex } from "knex";
|
||||
|
||||
import { ProjectMembershipRole, ProjectType, ProjectVersion, TableName } from "../schemas";
|
||||
import { AccessScope, ProjectMembershipRole, ProjectType, ProjectVersion, TableName } from "../schemas";
|
||||
import { seedData1 } from "../seed-data";
|
||||
|
||||
export const DEFAULT_PROJECT_ENVS = [
|
||||
@@ -23,15 +23,17 @@ export async function seed(knex: Knex): Promise<void> {
|
||||
})
|
||||
.returning("*");
|
||||
|
||||
const projectMembershipV3 = await knex(TableName.ProjectMembership)
|
||||
const projectMembershipV3 = await knex(TableName.Membership)
|
||||
.insert({
|
||||
projectId: projectV2.id,
|
||||
userId: seedData1.id
|
||||
scopeProjectId: projectV2.id,
|
||||
actorUserId: seedData1.id,
|
||||
scope: AccessScope.Project,
|
||||
scopeOrgId: seedData1.organization.id
|
||||
})
|
||||
.returning("*");
|
||||
await knex(TableName.ProjectUserMembershipRole).insert({
|
||||
await knex(TableName.MembershipRole).insert({
|
||||
role: ProjectMembershipRole.Admin,
|
||||
projectMembershipId: projectMembershipV3[0].id
|
||||
membershipId: projectMembershipV3[0].id
|
||||
});
|
||||
|
||||
// create default environments and default folders
|
||||
|
||||
@@ -1,22 +1,37 @@
|
||||
import { Knex } from "knex";
|
||||
|
||||
import { initEnvConfig } from "@app/lib/config/env";
|
||||
import { initializeHsmModule } from "@app/ee/services/hsm/hsm-fns";
|
||||
import { hsmServiceFactory } from "@app/ee/services/hsm/hsm-service";
|
||||
import { getHsmConfig, initEnvConfig } from "@app/lib/config/env";
|
||||
import { crypto } from "@app/lib/crypto/cryptography";
|
||||
import { initLogger, logger } from "@app/lib/logger";
|
||||
import { kmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";
|
||||
import { superAdminDALFactory } from "@app/services/super-admin/super-admin-dal";
|
||||
|
||||
import { IdentityAuthMethod, OrgMembershipRole, ProjectMembershipRole, TableName } from "../schemas";
|
||||
import { AccessScope, IdentityAuthMethod, OrgMembershipRole, ProjectMembershipRole, TableName } from "../schemas";
|
||||
import { seedData1 } from "../seed-data";
|
||||
|
||||
export async function seed(knex: Knex): Promise<void> {
|
||||
// Deletes ALL existing entries
|
||||
await knex(TableName.Identity).del();
|
||||
await knex(TableName.IdentityOrgMembership).del();
|
||||
|
||||
initLogger();
|
||||
|
||||
const superAdminDAL = superAdminDALFactory(knex);
|
||||
await initEnvConfig(superAdminDAL, logger);
|
||||
const kmsRootConfigDAL = kmsRootConfigDALFactory(knex);
|
||||
const hsmConfig = getHsmConfig(logger);
|
||||
|
||||
const hsmModule = initializeHsmModule(hsmConfig);
|
||||
hsmModule.initialize();
|
||||
|
||||
const hsmService = hsmServiceFactory({
|
||||
hsmModule: hsmModule.getModule(),
|
||||
envConfig: hsmConfig
|
||||
});
|
||||
|
||||
await hsmService.startService();
|
||||
|
||||
await initEnvConfig(hsmService, kmsRootConfigDAL, superAdminDAL, logger);
|
||||
|
||||
// Inserts seed entries
|
||||
await knex(TableName.Identity).insert([
|
||||
@@ -25,7 +40,8 @@ export async function seed(knex: Knex): Promise<void> {
|
||||
// @ts-ignore
|
||||
id: seedData1.machineIdentity.id,
|
||||
name: seedData1.machineIdentity.name,
|
||||
authMethod: IdentityAuthMethod.UNIVERSAL_AUTH
|
||||
authMethod: IdentityAuthMethod.UNIVERSAL_AUTH,
|
||||
orgId: seedData1.organization.id
|
||||
}
|
||||
]);
|
||||
const identityUa = await knex(TableName.IdentityUniversalAuth)
|
||||
@@ -78,34 +94,47 @@ export async function seed(knex: Knex): Promise<void> {
|
||||
isClientSecretRevoked: false
|
||||
}
|
||||
]);
|
||||
await knex(TableName.IdentityOrgMembership).insert([
|
||||
const [orgMembership] = await knex(TableName.Membership)
|
||||
.insert([
|
||||
{
|
||||
actorIdentityId: seedData1.machineIdentity.id,
|
||||
scopeOrgId: seedData1.organization.id,
|
||||
scope: AccessScope.Organization
|
||||
}
|
||||
])
|
||||
.returning("*");
|
||||
await knex(TableName.MembershipRole).insert([
|
||||
{
|
||||
identityId: seedData1.machineIdentity.id,
|
||||
orgId: seedData1.organization.id,
|
||||
membershipId: orgMembership.id,
|
||||
role: OrgMembershipRole.Admin
|
||||
}
|
||||
]);
|
||||
|
||||
const identityProjectMembership = await knex(TableName.IdentityProjectMembership)
|
||||
const identityProjectMembership = await knex(TableName.Membership)
|
||||
.insert({
|
||||
identityId: seedData1.machineIdentity.id,
|
||||
projectId: seedData1.project.id
|
||||
actorIdentityId: seedData1.machineIdentity.id,
|
||||
scopeOrgId: seedData1.organization.id,
|
||||
scope: AccessScope.Project,
|
||||
scopeProjectId: seedData1.project.id
|
||||
})
|
||||
.returning("*");
|
||||
|
||||
await knex(TableName.IdentityProjectMembershipRole).insert({
|
||||
await knex(TableName.MembershipRole).insert({
|
||||
role: ProjectMembershipRole.Admin,
|
||||
projectMembershipId: identityProjectMembership[0].id
|
||||
membershipId: identityProjectMembership[0].id
|
||||
});
|
||||
const identityProjectMembershipV3 = await knex(TableName.IdentityProjectMembership)
|
||||
|
||||
const identityProjectMembershipV3 = await knex(TableName.Membership)
|
||||
.insert({
|
||||
identityId: seedData1.machineIdentity.id,
|
||||
projectId: seedData1.projectV3.id
|
||||
actorIdentityId: seedData1.machineIdentity.id,
|
||||
scopeOrgId: seedData1.organization.id,
|
||||
scope: AccessScope.Project,
|
||||
scopeProjectId: seedData1.projectV3.id
|
||||
})
|
||||
.returning("*");
|
||||
|
||||
await knex(TableName.IdentityProjectMembershipRole).insert({
|
||||
await knex(TableName.MembershipRole).insert({
|
||||
role: ProjectMembershipRole.Admin,
|
||||
projectMembershipId: identityProjectMembershipV3[0].id
|
||||
membershipId: identityProjectMembershipV3[0].id
|
||||
});
|
||||
}
|
||||
|
||||
@@ -8,6 +8,35 @@ import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
|
||||
export const registerCertificateEstRouter = async (server: FastifyZodProvider) => {
|
||||
const appCfg = getConfig();
|
||||
|
||||
const getIdentifierType = async (identifier: string): Promise<"template" | "profile" | null> => {
|
||||
try {
|
||||
// Try to find as profile first using internal access
|
||||
await server.services.certificateProfile.getEstConfigurationByProfile({
|
||||
profileId: identifier,
|
||||
isInternal: true
|
||||
});
|
||||
return "profile";
|
||||
} catch (profileError) {
|
||||
try {
|
||||
await server.services.certificateTemplate.getEstConfiguration({
|
||||
isInternal: true,
|
||||
certificateTemplateId: identifier
|
||||
});
|
||||
return "template";
|
||||
} catch (templateError) {
|
||||
server.log.debug(
|
||||
{
|
||||
identifier,
|
||||
profileError: profileError instanceof Error ? profileError.message : "Unknown error",
|
||||
templateError: templateError instanceof Error ? templateError.message : "Unknown error"
|
||||
},
|
||||
"EST identifier not found as profile or template"
|
||||
);
|
||||
return null;
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
// add support for CSR bodies
|
||||
server.addContentTypeParser("application/pkcs10", { parseAs: "string" }, (_, body, done) => {
|
||||
try {
|
||||
@@ -59,11 +88,29 @@ export const registerCertificateEstRouter = async (server: FastifyZodProvider) =
|
||||
return;
|
||||
}
|
||||
|
||||
const certificateTemplateId = urlFragments.slice(-2)[0];
|
||||
const estConfig = await server.services.certificateTemplate.getEstConfiguration({
|
||||
isInternal: true,
|
||||
certificateTemplateId
|
||||
});
|
||||
const identifier = urlFragments.slice(-2)[0];
|
||||
|
||||
const identifierType = await getIdentifierType(identifier);
|
||||
if (!identifierType) {
|
||||
res.raw.statusCode = 404;
|
||||
res.raw.setHeader("Content-Type", "text/plain");
|
||||
res.raw.write("Certificate template or profile not found");
|
||||
res.raw.flushHeaders();
|
||||
return;
|
||||
}
|
||||
|
||||
let estConfig;
|
||||
if (identifierType === "profile") {
|
||||
estConfig = await server.services.certificateProfile.getEstConfigurationByProfile({
|
||||
profileId: identifier,
|
||||
isInternal: true
|
||||
});
|
||||
} else {
|
||||
estConfig = await server.services.certificateTemplate.getEstConfiguration({
|
||||
isInternal: true,
|
||||
certificateTemplateId: identifier
|
||||
});
|
||||
}
|
||||
|
||||
if (!estConfig.isEnabled) {
|
||||
throw new BadRequestError({
|
||||
@@ -95,14 +142,14 @@ export const registerCertificateEstRouter = async (server: FastifyZodProvider) =
|
||||
|
||||
server.route({
|
||||
method: "POST",
|
||||
url: "/:certificateTemplateId/simpleenroll",
|
||||
url: "/:identifier/simpleenroll",
|
||||
config: {
|
||||
rateLimit: writeLimit
|
||||
},
|
||||
schema: {
|
||||
body: z.string().min(1),
|
||||
params: z.object({
|
||||
certificateTemplateId: z.string().min(1)
|
||||
identifier: z.string().min(1)
|
||||
}),
|
||||
response: {
|
||||
200: z.string()
|
||||
@@ -112,9 +159,23 @@ export const registerCertificateEstRouter = async (server: FastifyZodProvider) =
|
||||
void res.header("Content-Type", "application/pkcs7-mime; smime-type=certs-only");
|
||||
void res.header("Content-Transfer-Encoding", "base64");
|
||||
|
||||
const { identifier } = req.params;
|
||||
const identifierType = await getIdentifierType(identifier);
|
||||
|
||||
if (!identifierType) {
|
||||
throw new BadRequestError({ message: "Certificate template or profile not found" });
|
||||
}
|
||||
|
||||
if (identifierType === "profile") {
|
||||
return server.services.certificateEstV3.simpleEnrollByProfile({
|
||||
csr: req.body,
|
||||
profileId: identifier,
|
||||
sslClientCert: req.headers[appCfg.SSL_CLIENT_CERTIFICATE_HEADER_KEY] as string
|
||||
});
|
||||
}
|
||||
return server.services.certificateEst.simpleEnroll({
|
||||
csr: req.body,
|
||||
certificateTemplateId: req.params.certificateTemplateId,
|
||||
certificateTemplateId: identifier,
|
||||
sslClientCert: req.headers[appCfg.SSL_CLIENT_CERTIFICATE_HEADER_KEY] as string
|
||||
});
|
||||
}
|
||||
@@ -122,14 +183,14 @@ export const registerCertificateEstRouter = async (server: FastifyZodProvider) =
|
||||
|
||||
server.route({
|
||||
method: "POST",
|
||||
url: "/:certificateTemplateId/simplereenroll",
|
||||
url: "/:identifier/simplereenroll",
|
||||
config: {
|
||||
rateLimit: writeLimit
|
||||
},
|
||||
schema: {
|
||||
body: z.string().min(1),
|
||||
params: z.object({
|
||||
certificateTemplateId: z.string().min(1)
|
||||
identifier: z.string().min(1)
|
||||
}),
|
||||
response: {
|
||||
200: z.string()
|
||||
@@ -139,9 +200,23 @@ export const registerCertificateEstRouter = async (server: FastifyZodProvider) =
|
||||
void res.header("Content-Type", "application/pkcs7-mime; smime-type=certs-only");
|
||||
void res.header("Content-Transfer-Encoding", "base64");
|
||||
|
||||
const { identifier } = req.params;
|
||||
const identifierType = await getIdentifierType(identifier);
|
||||
|
||||
if (!identifierType) {
|
||||
throw new BadRequestError({ message: "Certificate template or profile not found" });
|
||||
}
|
||||
|
||||
if (identifierType === "profile") {
|
||||
return server.services.certificateEstV3.simpleReenrollByProfile({
|
||||
csr: req.body,
|
||||
profileId: identifier,
|
||||
sslClientCert: req.headers[appCfg.SSL_CLIENT_CERTIFICATE_HEADER_KEY] as string
|
||||
});
|
||||
}
|
||||
return server.services.certificateEst.simpleReenroll({
|
||||
csr: req.body,
|
||||
certificateTemplateId: req.params.certificateTemplateId,
|
||||
certificateTemplateId: identifier,
|
||||
sslClientCert: req.headers[appCfg.SSL_CLIENT_CERTIFICATE_HEADER_KEY] as string
|
||||
});
|
||||
}
|
||||
@@ -149,13 +224,13 @@ export const registerCertificateEstRouter = async (server: FastifyZodProvider) =
|
||||
|
||||
server.route({
|
||||
method: "GET",
|
||||
url: "/:certificateTemplateId/cacerts",
|
||||
url: "/:identifier/cacerts",
|
||||
config: {
|
||||
rateLimit: readLimit
|
||||
},
|
||||
schema: {
|
||||
params: z.object({
|
||||
certificateTemplateId: z.string().min(1)
|
||||
identifier: z.string().min(1)
|
||||
}),
|
||||
response: {
|
||||
200: z.string()
|
||||
@@ -165,8 +240,20 @@ export const registerCertificateEstRouter = async (server: FastifyZodProvider) =
|
||||
void res.header("Content-Type", "application/pkcs7-mime; smime-type=certs-only");
|
||||
void res.header("Content-Transfer-Encoding", "base64");
|
||||
|
||||
const { identifier } = req.params;
|
||||
const identifierType = await getIdentifierType(identifier);
|
||||
|
||||
if (!identifierType) {
|
||||
throw new BadRequestError({ message: "Certificate template or profile not found" });
|
||||
}
|
||||
|
||||
if (identifierType === "profile") {
|
||||
return server.services.certificateEstV3.getCaCertsByProfile({
|
||||
profileId: identifier
|
||||
});
|
||||
}
|
||||
return server.services.certificateEst.getCaCerts({
|
||||
certificateTemplateId: req.params.certificateTemplateId
|
||||
certificateTemplateId: identifier
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { packRules } from "@casl/ability/extra";
|
||||
import { z } from "zod";
|
||||
|
||||
import { ProjectMembershipRole, ProjectRolesSchema } from "@app/db/schemas";
|
||||
import { AccessScope, ProjectMembershipRole, ProjectRolesSchema } from "@app/db/schemas";
|
||||
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
|
||||
import {
|
||||
backfillPermissionV1SchemaToV2Schema,
|
||||
@@ -13,7 +13,6 @@ import { slugSchema } from "@app/server/lib/schemas";
|
||||
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
||||
import { SanitizedRoleSchemaV1 } from "@app/server/routes/sanitizedSchemas";
|
||||
import { AuthMode } from "@app/services/auth/auth-type";
|
||||
import { ProjectRoleServiceIdentifierType } from "@app/services/project-role/project-role-types";
|
||||
|
||||
export const registerDeprecatedProjectRoleRouter = async (server: FastifyZodProvider) => {
|
||||
server.route({
|
||||
@@ -55,14 +54,16 @@ export const registerDeprecatedProjectRoleRouter = async (server: FastifyZodProv
|
||||
packRules(backfillPermissionV1SchemaToV2Schema(req.body.permissions, true))
|
||||
);
|
||||
|
||||
const role = await server.services.projectRole.createRole({
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
actorId: req.permission.id,
|
||||
actorOrgId: req.permission.orgId,
|
||||
actor: req.permission.type,
|
||||
filter: {
|
||||
type: ProjectRoleServiceIdentifierType.SLUG,
|
||||
projectSlug: req.params.projectSlug
|
||||
const { id: projectId } = await server.services.convertor.projectSlugToId({
|
||||
slug: req.params.projectSlug,
|
||||
orgId: req.permission.orgId
|
||||
});
|
||||
const role = await server.services.role.createRole({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
orgId: req.permission.orgId,
|
||||
projectId
|
||||
},
|
||||
data: {
|
||||
...req.body,
|
||||
@@ -73,7 +74,7 @@ export const registerDeprecatedProjectRoleRouter = async (server: FastifyZodProv
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: role.projectId,
|
||||
projectId,
|
||||
event: {
|
||||
type: EventType.CREATE_PROJECT_ROLE,
|
||||
metadata: {
|
||||
@@ -86,7 +87,7 @@ export const registerDeprecatedProjectRoleRouter = async (server: FastifyZodProv
|
||||
}
|
||||
});
|
||||
|
||||
return { role };
|
||||
return { role: { ...role, projectId: role.projectId as string } };
|
||||
}
|
||||
});
|
||||
|
||||
@@ -131,12 +132,21 @@ export const registerDeprecatedProjectRoleRouter = async (server: FastifyZodProv
|
||||
? JSON.stringify(packRules(backfillPermissionV1SchemaToV2Schema(req.body.permissions, true)))
|
||||
: undefined;
|
||||
|
||||
const role = await server.services.projectRole.updateRole({
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
actorId: req.permission.id,
|
||||
actorOrgId: req.permission.orgId,
|
||||
actor: req.permission.type,
|
||||
roleId: req.params.roleId,
|
||||
const { id: projectId } = await server.services.convertor.projectSlugToId({
|
||||
slug: req.params.projectSlug,
|
||||
orgId: req.permission.orgId
|
||||
});
|
||||
|
||||
const role = await server.services.role.updateRole({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
orgId: req.permission.orgId,
|
||||
projectId
|
||||
},
|
||||
selector: {
|
||||
id: req.params.roleId
|
||||
},
|
||||
data: {
|
||||
...req.body,
|
||||
permissions: stringifiedPermissions
|
||||
@@ -146,7 +156,7 @@ export const registerDeprecatedProjectRoleRouter = async (server: FastifyZodProv
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: role.projectId,
|
||||
projectId: role.projectId as string,
|
||||
event: {
|
||||
type: EventType.UPDATE_PROJECT_ROLE,
|
||||
metadata: {
|
||||
@@ -159,7 +169,7 @@ export const registerDeprecatedProjectRoleRouter = async (server: FastifyZodProv
|
||||
}
|
||||
});
|
||||
|
||||
return { role };
|
||||
return { role: { ...role, projectId: role.projectId as string } };
|
||||
}
|
||||
});
|
||||
|
||||
@@ -188,18 +198,27 @@ export const registerDeprecatedProjectRoleRouter = async (server: FastifyZodProv
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
handler: async (req) => {
|
||||
const role = await server.services.projectRole.deleteRole({
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
actorId: req.permission.id,
|
||||
actorOrgId: req.permission.orgId,
|
||||
actor: req.permission.type,
|
||||
roleId: req.params.roleId
|
||||
const { id: projectId } = await server.services.convertor.projectSlugToId({
|
||||
slug: req.params.projectSlug,
|
||||
orgId: req.permission.orgId
|
||||
});
|
||||
|
||||
const role = await server.services.role.deleteRole({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
orgId: req.permission.orgId,
|
||||
projectId
|
||||
},
|
||||
selector: {
|
||||
id: req.params.roleId
|
||||
}
|
||||
});
|
||||
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: role.projectId,
|
||||
projectId: role.projectId as string,
|
||||
event: {
|
||||
type: EventType.DELETE_PROJECT_ROLE,
|
||||
metadata: {
|
||||
@@ -210,7 +229,7 @@ export const registerDeprecatedProjectRoleRouter = async (server: FastifyZodProv
|
||||
}
|
||||
});
|
||||
|
||||
return { role };
|
||||
return { role: { ...role, projectId: role.projectId as string } };
|
||||
}
|
||||
});
|
||||
|
||||
@@ -238,17 +257,21 @@ export const registerDeprecatedProjectRoleRouter = async (server: FastifyZodProv
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
handler: async (req) => {
|
||||
const roles = await server.services.projectRole.listRoles({
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
actorId: req.permission.id,
|
||||
actorOrgId: req.permission.orgId,
|
||||
actor: req.permission.type,
|
||||
filter: {
|
||||
type: ProjectRoleServiceIdentifierType.SLUG,
|
||||
projectSlug: req.params.projectSlug
|
||||
}
|
||||
const { id: projectId } = await server.services.convertor.projectSlugToId({
|
||||
slug: req.params.projectSlug,
|
||||
orgId: req.permission.orgId
|
||||
});
|
||||
return { roles };
|
||||
|
||||
const { roles } = await server.services.role.listRoles({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
orgId: req.permission.orgId,
|
||||
projectId
|
||||
},
|
||||
data: {}
|
||||
});
|
||||
return { roles: roles.map((el) => ({ ...el, projectId: el.projectId as string })) };
|
||||
}
|
||||
});
|
||||
|
||||
@@ -265,78 +288,30 @@ export const registerDeprecatedProjectRoleRouter = async (server: FastifyZodProv
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
role: SanitizedRoleSchemaV1.omit({ version: true })
|
||||
role: SanitizedRoleSchemaV1
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
handler: async (req) => {
|
||||
const role = await server.services.projectRole.getRoleBySlug({
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
actorId: req.permission.id,
|
||||
actorOrgId: req.permission.orgId,
|
||||
actor: req.permission.type,
|
||||
filter: {
|
||||
type: ProjectRoleServiceIdentifierType.SLUG,
|
||||
projectSlug: req.params.projectSlug
|
||||
},
|
||||
roleSlug: req.params.slug
|
||||
const { id: projectId } = await server.services.convertor.projectSlugToId({
|
||||
slug: req.params.projectSlug,
|
||||
orgId: req.permission.orgId
|
||||
});
|
||||
|
||||
return { role };
|
||||
}
|
||||
});
|
||||
|
||||
server.route({
|
||||
method: "GET",
|
||||
url: "/:projectId/permissions",
|
||||
config: {
|
||||
rateLimit: readLimit
|
||||
},
|
||||
schema: {
|
||||
params: z.object({
|
||||
projectId: z.string().trim()
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
data: z.object({
|
||||
membership: z.object({
|
||||
id: z.string(),
|
||||
roles: z
|
||||
.object({
|
||||
role: z.string()
|
||||
})
|
||||
.array()
|
||||
}),
|
||||
assumedPrivilegeDetails: z
|
||||
.object({
|
||||
actorId: z.string(),
|
||||
actorType: z.string(),
|
||||
actorName: z.string(),
|
||||
actorEmail: z.string().optional()
|
||||
})
|
||||
.optional(),
|
||||
permissions: z.any().array()
|
||||
})
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const { permissions, membership, assumedPrivilegeDetails } = await server.services.projectRole.getUserPermission(
|
||||
req.permission.id,
|
||||
req.params.projectId,
|
||||
req.permission.authMethod,
|
||||
req.permission.orgId
|
||||
);
|
||||
|
||||
return {
|
||||
data: {
|
||||
permissions,
|
||||
membership,
|
||||
assumedPrivilegeDetails
|
||||
const role = await server.services.role.getRoleBySlug({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
orgId: req.permission.orgId,
|
||||
projectId
|
||||
},
|
||||
selector: {
|
||||
slug: req.params.slug
|
||||
}
|
||||
};
|
||||
});
|
||||
|
||||
return { role: { ...role, projectId: role.projectId as string } };
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import slugify from "@sindresorhus/slugify";
|
||||
import { z } from "zod";
|
||||
|
||||
import { IdentityProjectAdditionalPrivilegeTemporaryMode } from "@app/ee/services/identity-project-additional-privilege/identity-project-additional-privilege-types";
|
||||
import { AccessScope, TemporaryPermissionMode } from "@app/db/schemas";
|
||||
import { backfillPermissionV1SchemaToV2Schema } from "@app/ee/services/permission/project-permission";
|
||||
import { ApiDocsTags, IDENTITY_ADDITIONAL_PRIVILEGE } from "@app/lib/api-docs";
|
||||
import { UnauthorizedError } from "@app/lib/errors";
|
||||
@@ -15,7 +15,7 @@ import {
|
||||
ProjectSpecificPrivilegePermissionSchema,
|
||||
SanitizedIdentityPrivilegeSchema
|
||||
} from "@app/server/routes/sanitizedSchemas";
|
||||
import { AuthMode } from "@app/services/auth/auth-type";
|
||||
import { ActorType, AuthMode } from "@app/services/auth/auth-type";
|
||||
|
||||
export const registerIdentityProjectAdditionalPrivilegeRouter = async (server: FastifyZodProvider) => {
|
||||
server.route({
|
||||
@@ -56,6 +56,10 @@ export const registerIdentityProjectAdditionalPrivilegeRouter = async (server: F
|
||||
if (!permissions && !privilegePermission) {
|
||||
throw new UnauthorizedError({ message: "Permission or privilegePermission must be provided" });
|
||||
}
|
||||
const { id: projectId } = await server.services.convertor.projectSlugToId({
|
||||
orgId: req.permission.orgId,
|
||||
slug: req.body.projectSlug
|
||||
});
|
||||
|
||||
const permission = privilegePermission
|
||||
? privilegePermission.actions.map((action) => ({
|
||||
@@ -64,19 +68,35 @@ export const registerIdentityProjectAdditionalPrivilegeRouter = async (server: F
|
||||
conditions: privilegePermission.conditions
|
||||
}))
|
||||
: permissions!;
|
||||
const privilege = await server.services.identityProjectAdditionalPrivilege.create({
|
||||
actorId: req.permission.id,
|
||||
actor: req.permission.type,
|
||||
actorOrgId: req.permission.orgId,
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
...req.body,
|
||||
slug: req.body.slug ?? slugify(alphaNumericNanoId(12)),
|
||||
isTemporary: false,
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore-error this is valid ts
|
||||
permissions: backfillPermissionV1SchemaToV2Schema(permission)
|
||||
|
||||
const { additionalPrivilege: privilege } = await server.services.additionalPrivilege.createAdditionalPrivilege({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
projectId,
|
||||
orgId: req.permission.orgId
|
||||
},
|
||||
data: {
|
||||
actorId: req.body.identityId,
|
||||
actorType: ActorType.IDENTITY,
|
||||
...req.body,
|
||||
isTemporary: false,
|
||||
name: req.body.slug || slugify(alphaNumericNanoId(8)),
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore-error this is valid ts
|
||||
permissions: backfillPermissionV1SchemaToV2Schema(permission)
|
||||
}
|
||||
});
|
||||
return { privilege };
|
||||
|
||||
return {
|
||||
privilege: {
|
||||
...privilege,
|
||||
identityId: req.body.identityId,
|
||||
projectMembershipId: projectId,
|
||||
projectId,
|
||||
slug: privilege.name
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
@@ -106,7 +126,7 @@ export const registerIdentityProjectAdditionalPrivilegeRouter = async (server: F
|
||||
IDENTITY_ADDITIONAL_PRIVILEGE.CREATE.privilegePermission
|
||||
).optional(),
|
||||
temporaryMode: z
|
||||
.nativeEnum(IdentityProjectAdditionalPrivilegeTemporaryMode)
|
||||
.nativeEnum(TemporaryPermissionMode)
|
||||
.describe(IDENTITY_ADDITIONAL_PRIVILEGE.CREATE.temporaryMode),
|
||||
temporaryRange: z
|
||||
.string()
|
||||
@@ -138,19 +158,39 @@ export const registerIdentityProjectAdditionalPrivilegeRouter = async (server: F
|
||||
}))
|
||||
: permissions!;
|
||||
|
||||
const privilege = await server.services.identityProjectAdditionalPrivilege.create({
|
||||
actorId: req.permission.id,
|
||||
actor: req.permission.type,
|
||||
actorOrgId: req.permission.orgId,
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
...req.body,
|
||||
slug: req.body.slug ?? slugify(alphaNumericNanoId(12)),
|
||||
isTemporary: true,
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore-error this is valid ts
|
||||
permissions: backfillPermissionV1SchemaToV2Schema(permission)
|
||||
const { id: projectId } = await server.services.convertor.projectSlugToId({
|
||||
orgId: req.permission.orgId,
|
||||
slug: req.body.projectSlug
|
||||
});
|
||||
return { privilege };
|
||||
|
||||
const { additionalPrivilege: privilege } = await server.services.additionalPrivilege.createAdditionalPrivilege({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
projectId,
|
||||
orgId: req.permission.orgId
|
||||
},
|
||||
data: {
|
||||
actorId: req.body.identityId,
|
||||
actorType: ActorType.IDENTITY,
|
||||
...req.body,
|
||||
isTemporary: true,
|
||||
name: req.body.slug || slugify(alphaNumericNanoId(8)),
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore-error this is valid ts
|
||||
permissions: backfillPermissionV1SchemaToV2Schema(permission)
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
privilege: {
|
||||
...privilege,
|
||||
identityId: req.body.identityId,
|
||||
projectMembershipId: projectId,
|
||||
projectId,
|
||||
slug: privilege.name
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
@@ -183,7 +223,7 @@ export const registerIdentityProjectAdditionalPrivilegeRouter = async (server: F
|
||||
).optional(),
|
||||
isTemporary: z.boolean().describe(IDENTITY_ADDITIONAL_PRIVILEGE.UPDATE.isTemporary),
|
||||
temporaryMode: z
|
||||
.nativeEnum(IdentityProjectAdditionalPrivilegeTemporaryMode)
|
||||
.nativeEnum(TemporaryPermissionMode)
|
||||
.describe(IDENTITY_ADDITIONAL_PRIVILEGE.UPDATE.temporaryMode),
|
||||
temporaryRange: z
|
||||
.string()
|
||||
@@ -216,18 +256,36 @@ export const registerIdentityProjectAdditionalPrivilegeRouter = async (server: F
|
||||
conditions: privilegePermission.conditions
|
||||
}))
|
||||
: permissions!;
|
||||
const privilege = await server.services.identityProjectAdditionalPrivilege.updateBySlug({
|
||||
actorId: req.permission.id,
|
||||
actor: req.permission.type,
|
||||
actorOrgId: req.permission.orgId,
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
slug: req.body.privilegeSlug,
|
||||
identityId: req.body.identityId,
|
||||
projectSlug: req.body.projectSlug,
|
||||
|
||||
const { id: projectId } = await server.services.convertor.projectSlugToId({
|
||||
orgId: req.permission.orgId,
|
||||
slug: req.body.projectSlug
|
||||
});
|
||||
|
||||
const { privilege: privilegeDoc } = await server.services.convertor.additionalPrivilegeNameToDoc(
|
||||
req.body.privilegeSlug,
|
||||
projectId
|
||||
);
|
||||
|
||||
const { additionalPrivilege: privilege } = await server.services.additionalPrivilege.updateAdditionalPrivilege({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
projectId,
|
||||
orgId: req.permission.orgId
|
||||
},
|
||||
selector: {
|
||||
actorId: req.body.identityId,
|
||||
actorType: ActorType.IDENTITY,
|
||||
id: privilegeDoc.id
|
||||
},
|
||||
data: {
|
||||
...req.body,
|
||||
...updatedInfo,
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore-error this is valid ts
|
||||
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore-error this is valid ts
|
||||
permissions: permission
|
||||
? // eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore-error this is valid ts
|
||||
@@ -235,7 +293,16 @@ export const registerIdentityProjectAdditionalPrivilegeRouter = async (server: F
|
||||
: undefined
|
||||
}
|
||||
});
|
||||
return { privilege };
|
||||
|
||||
return {
|
||||
privilege: {
|
||||
...privilege,
|
||||
identityId: req.body.identityId,
|
||||
projectMembershipId: projectId,
|
||||
projectId,
|
||||
slug: privilege.name
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
@@ -267,16 +334,39 @@ export const registerIdentityProjectAdditionalPrivilegeRouter = async (server: F
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
handler: async (req) => {
|
||||
const privilege = await server.services.identityProjectAdditionalPrivilege.deleteBySlug({
|
||||
actorId: req.permission.id,
|
||||
actor: req.permission.type,
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
actorOrgId: req.permission.orgId,
|
||||
slug: req.body.privilegeSlug,
|
||||
identityId: req.body.identityId,
|
||||
projectSlug: req.body.projectSlug
|
||||
const { id: projectId } = await server.services.convertor.projectSlugToId({
|
||||
orgId: req.permission.orgId,
|
||||
slug: req.body.projectSlug
|
||||
});
|
||||
return { privilege };
|
||||
|
||||
const { privilegeId } = await server.services.convertor.additionalPrivilegeNameToDoc(
|
||||
req.body.privilegeSlug,
|
||||
projectId
|
||||
);
|
||||
|
||||
const { additionalPrivilege: privilege } = await server.services.additionalPrivilege.deleteAdditionalPrivilege({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
projectId,
|
||||
orgId: req.permission.orgId
|
||||
},
|
||||
selector: {
|
||||
actorId: req.body.identityId,
|
||||
actorType: ActorType.IDENTITY,
|
||||
id: privilegeId
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
privilege: {
|
||||
...privilege,
|
||||
identityId: req.body.identityId,
|
||||
projectMembershipId: projectId,
|
||||
projectId,
|
||||
slug: privilege.name
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
@@ -310,15 +400,39 @@ export const registerIdentityProjectAdditionalPrivilegeRouter = async (server: F
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
handler: async (req) => {
|
||||
const privilege = await server.services.identityProjectAdditionalPrivilege.getPrivilegeDetailsBySlug({
|
||||
actorId: req.permission.id,
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
actor: req.permission.type,
|
||||
actorOrgId: req.permission.orgId,
|
||||
slug: req.params.privilegeSlug,
|
||||
...req.query
|
||||
const { id: projectId } = await server.services.convertor.projectSlugToId({
|
||||
orgId: req.permission.orgId,
|
||||
slug: req.query.projectSlug
|
||||
});
|
||||
return { privilege };
|
||||
|
||||
const { privilegeId } = await server.services.convertor.additionalPrivilegeNameToDoc(
|
||||
req.params.privilegeSlug,
|
||||
projectId
|
||||
);
|
||||
|
||||
const { additionalPrivilege: privilege } = await server.services.additionalPrivilege.getAdditionalPrivilegeById({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
projectId,
|
||||
orgId: req.permission.orgId
|
||||
},
|
||||
selector: {
|
||||
actorId: req.query.identityId,
|
||||
actorType: ActorType.IDENTITY,
|
||||
id: privilegeId
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
privilege: {
|
||||
...privilege,
|
||||
identityId: req.query.identityId,
|
||||
projectMembershipId: projectId,
|
||||
projectId,
|
||||
slug: privilege.name
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
@@ -349,15 +463,32 @@ export const registerIdentityProjectAdditionalPrivilegeRouter = async (server: F
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
handler: async (req) => {
|
||||
const privileges = await server.services.identityProjectAdditionalPrivilege.listIdentityProjectPrivileges({
|
||||
actorId: req.permission.id,
|
||||
actor: req.permission.type,
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
actorOrgId: req.permission.orgId,
|
||||
...req.query
|
||||
const { id: projectId } = await server.services.convertor.projectSlugToId({
|
||||
orgId: req.permission.orgId,
|
||||
slug: req.query.projectSlug
|
||||
});
|
||||
|
||||
const { additionalPrivileges: privileges } = await server.services.additionalPrivilege.listAdditionalPrivileges({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
projectId,
|
||||
orgId: req.permission.orgId
|
||||
},
|
||||
selector: {
|
||||
actorId: req.query.identityId,
|
||||
actorType: ActorType.IDENTITY
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
privileges
|
||||
privileges: privileges.map((privilege) => ({
|
||||
...privilege,
|
||||
identityId: req.query.identityId,
|
||||
projectMembershipId: projectId,
|
||||
projectId,
|
||||
slug: privilege.name
|
||||
}))
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
@@ -23,6 +23,12 @@ import { registerLdapRouter } from "./ldap-router";
|
||||
import { registerLicenseRouter } from "./license-router";
|
||||
import { registerOidcRouter } from "./oidc-router";
|
||||
import { registerOrgRoleRouter } from "./org-role-router";
|
||||
import { PAM_ACCOUNT_REGISTER_ROUTER_MAP } from "./pam-account-routers";
|
||||
import { registerPamAccountRouter } from "./pam-account-routers/pam-account-router";
|
||||
import { registerPamFolderRouter } from "./pam-folder-router";
|
||||
import { PAM_RESOURCE_REGISTER_ROUTER_MAP } from "./pam-resource-routers";
|
||||
import { registerPamResourceRouter } from "./pam-resource-routers/pam-resource-router";
|
||||
import { registerPamSessionRouter } from "./pam-session-router";
|
||||
import { registerPITRouter } from "./pit-router";
|
||||
import { registerProjectRoleRouter } from "./project-role-router";
|
||||
import { registerProjectRouter } from "./project-router";
|
||||
@@ -42,12 +48,14 @@ import { registerSshCertRouter } from "./ssh-certificate-router";
|
||||
import { registerSshCertificateTemplateRouter } from "./ssh-certificate-template-router";
|
||||
import { registerSshHostGroupRouter } from "./ssh-host-group-router";
|
||||
import { registerSshHostRouter } from "./ssh-host-router";
|
||||
import { registerSubOrgRouter } from "./sub-org-router";
|
||||
import { registerTrustedIpRouter } from "./trusted-ip-router";
|
||||
import { registerUserAdditionalPrivilegeRouter } from "./user-additional-privilege-router";
|
||||
|
||||
export const registerV1EERoutes = async (server: FastifyZodProvider) => {
|
||||
// org role starts with organization
|
||||
await server.register(registerOrgRoleRouter, { prefix: "/organization" });
|
||||
await server.register(registerSubOrgRouter, { prefix: "/sub-organizations" });
|
||||
await server.register(registerLicenseRouter, { prefix: "/organizations" });
|
||||
|
||||
// depreciated in favour of infisical workspace
|
||||
@@ -166,4 +174,40 @@ export const registerV1EERoutes = async (server: FastifyZodProvider) => {
|
||||
},
|
||||
{ prefix: "/kmip" }
|
||||
);
|
||||
|
||||
await server.register(
|
||||
async (pamRouter) => {
|
||||
await pamRouter.register(registerPamFolderRouter, { prefix: "/folders" });
|
||||
await pamRouter.register(registerPamSessionRouter, { prefix: "/sessions" });
|
||||
|
||||
await pamRouter.register(
|
||||
async (pamAccountRouter) => {
|
||||
await pamAccountRouter.register(registerPamAccountRouter);
|
||||
|
||||
// Provider-specific endpoints
|
||||
await Promise.all(
|
||||
Object.entries(PAM_ACCOUNT_REGISTER_ROUTER_MAP).map(([provider, router]) =>
|
||||
pamAccountRouter.register(router, { prefix: `/${provider}` })
|
||||
)
|
||||
);
|
||||
},
|
||||
{ prefix: "/accounts" }
|
||||
);
|
||||
|
||||
await pamRouter.register(
|
||||
async (pamResourceRouter) => {
|
||||
await pamResourceRouter.register(registerPamResourceRouter);
|
||||
|
||||
// Provider-specific endpoints
|
||||
await Promise.all(
|
||||
Object.entries(PAM_RESOURCE_REGISTER_ROUTER_MAP).map(([provider, router]) =>
|
||||
pamResourceRouter.register(router, { prefix: `/${provider}` })
|
||||
)
|
||||
);
|
||||
},
|
||||
{ prefix: "/resources" }
|
||||
);
|
||||
},
|
||||
{ prefix: "/pam" }
|
||||
);
|
||||
};
|
||||
|
||||
@@ -128,7 +128,8 @@ export const registerKmipSpecRouter = async (server: FastifyZodProvider) => {
|
||||
200: z.object({
|
||||
id: z.string(),
|
||||
value: z.string(),
|
||||
algorithm: z.string()
|
||||
algorithm: z.string(),
|
||||
kmipMetadata: z.record(z.any()).nullish()
|
||||
})
|
||||
}
|
||||
},
|
||||
@@ -433,7 +434,8 @@ export const registerKmipSpecRouter = async (server: FastifyZodProvider) => {
|
||||
body: z.object({
|
||||
key: z.string(),
|
||||
name: z.string(),
|
||||
algorithm: z.nativeEnum(SymmetricKeyAlgorithm)
|
||||
algorithm: z.nativeEnum(SymmetricKeyAlgorithm),
|
||||
kmipMetadata: z.record(z.any()).nullish()
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
|
||||
@@ -58,7 +58,7 @@ export const registerLicenseRouter = async (server: FastifyZodProvider) => {
|
||||
const plan = await server.services.license.getOrgPlan({
|
||||
actorId: req.permission.id,
|
||||
actor: req.permission.type,
|
||||
actorOrgId: req.permission.orgId,
|
||||
actorOrgId: req.permission.rootOrgId,
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
orgId: req.params.organizationId,
|
||||
refreshCache: req.query.refreshCache
|
||||
|
||||
@@ -1,12 +1,37 @@
|
||||
import { packRules } from "@casl/ability/extra";
|
||||
import { z } from "zod";
|
||||
|
||||
import { OrgMembershipRole, OrgMembershipsSchema, OrgRolesSchema } from "@app/db/schemas";
|
||||
import { AccessScope, OrgMembershipRole, OrgRolesSchema } from "@app/db/schemas";
|
||||
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
|
||||
import { OrgPermissionSchema, OrgPermissionSubjects } from "@app/ee/services/permission/org-permission";
|
||||
import { BadRequestError } from "@app/lib/errors";
|
||||
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
|
||||
import { slugSchema } from "@app/server/lib/schemas";
|
||||
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
||||
import { AuthMode } from "@app/services/auth/auth-type";
|
||||
|
||||
const INVALID_SUBORG_PERMISSIONS = [
|
||||
OrgPermissionSubjects.Sso,
|
||||
OrgPermissionSubjects.Ldap,
|
||||
OrgPermissionSubjects.Scim,
|
||||
OrgPermissionSubjects.GithubOrgSync,
|
||||
OrgPermissionSubjects.GithubOrgSyncManual,
|
||||
OrgPermissionSubjects.Billing,
|
||||
OrgPermissionSubjects.SubOrganization
|
||||
];
|
||||
|
||||
const validateSubOrganizationSubjects = (permissions: unknown) => {
|
||||
const invalidPermissionSubjects = (permissions as { subject: OrgPermissionSubjects }[])
|
||||
.filter((el) => INVALID_SUBORG_PERMISSIONS.includes(el.subject))
|
||||
.map((el) => el.subject);
|
||||
if (invalidPermissionSubjects.length) {
|
||||
const deduplication = Array.from(new Set(invalidPermissionSubjects));
|
||||
throw new BadRequestError({
|
||||
message: `Suborganization contains invalid permission subjects: ${deduplication.join(",")}`
|
||||
});
|
||||
}
|
||||
};
|
||||
|
||||
export const registerOrgRoleRouter = async (server: FastifyZodProvider) => {
|
||||
server.route({
|
||||
method: "POST",
|
||||
@@ -25,8 +50,7 @@ export const registerOrgRoleRouter = async (server: FastifyZodProvider) => {
|
||||
),
|
||||
name: z.string().trim(),
|
||||
description: z.string().trim().nullish(),
|
||||
// TODO(scott): once UI refactored permissions: OrgPermissionSchema.array()
|
||||
permissions: z.any().array()
|
||||
permissions: OrgPermissionSchema.array()
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
@@ -36,13 +60,23 @@ export const registerOrgRoleRouter = async (server: FastifyZodProvider) => {
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const role = await server.services.orgRole.createRole(
|
||||
req.permission.id,
|
||||
req.params.organizationId,
|
||||
req.body,
|
||||
req.permission.authMethod,
|
||||
req.permission.orgId
|
||||
);
|
||||
const isSubOrganization = req.permission.rootOrgId !== req.permission.orgId;
|
||||
if (isSubOrganization) {
|
||||
validateSubOrganizationSubjects(req.body.permissions);
|
||||
}
|
||||
|
||||
const stringifiedPermissions = JSON.stringify(packRules(req.body.permissions));
|
||||
const role = await server.services.role.createRole({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Organization,
|
||||
orgId: req.params.organizationId
|
||||
},
|
||||
data: {
|
||||
...req.body,
|
||||
permissions: stringifiedPermissions
|
||||
}
|
||||
});
|
||||
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
@@ -59,7 +93,7 @@ export const registerOrgRoleRouter = async (server: FastifyZodProvider) => {
|
||||
}
|
||||
});
|
||||
|
||||
return { role };
|
||||
return { role: { ...role, orgId: role.orgId as string } };
|
||||
}
|
||||
});
|
||||
|
||||
@@ -82,14 +116,17 @@ export const registerOrgRoleRouter = async (server: FastifyZodProvider) => {
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const role = await server.services.orgRole.getRole(
|
||||
req.permission.id,
|
||||
req.params.organizationId,
|
||||
req.params.roleId,
|
||||
req.permission.authMethod,
|
||||
req.permission.orgId
|
||||
);
|
||||
return { role };
|
||||
const role = await server.services.role.getRoleById({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Organization,
|
||||
orgId: req.params.organizationId
|
||||
},
|
||||
selector: {
|
||||
id: req.params.roleId
|
||||
}
|
||||
});
|
||||
return { role: { ...role, orgId: role.orgId as string } };
|
||||
}
|
||||
});
|
||||
|
||||
@@ -114,8 +151,7 @@ export const registerOrgRoleRouter = async (server: FastifyZodProvider) => {
|
||||
.optional(),
|
||||
name: z.string().trim().optional(),
|
||||
description: z.string().trim().nullish(),
|
||||
// TODO(scott): once UI refactored permissions: OrgPermissionSchema.array().optional()
|
||||
permissions: z.any().array().optional()
|
||||
permissions: OrgPermissionSchema.array().optional()
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
@@ -125,14 +161,26 @@ export const registerOrgRoleRouter = async (server: FastifyZodProvider) => {
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const role = await server.services.orgRole.updateRole(
|
||||
req.permission.id,
|
||||
req.params.organizationId,
|
||||
req.params.roleId,
|
||||
req.body,
|
||||
req.permission.authMethod,
|
||||
req.permission.orgId
|
||||
);
|
||||
const isSubOrganization = req.permission.rootOrgId !== req.permission.orgId;
|
||||
if (isSubOrganization && req.body.permissions) {
|
||||
validateSubOrganizationSubjects(req.body.permissions);
|
||||
}
|
||||
|
||||
const stringifiedPermissions = req.body.permissions ? JSON.stringify(packRules(req.body.permissions)) : undefined;
|
||||
const role = await server.services.role.updateRole({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Organization,
|
||||
orgId: req.params.organizationId
|
||||
},
|
||||
selector: {
|
||||
id: req.params.roleId
|
||||
},
|
||||
data: {
|
||||
...req.body,
|
||||
permissions: stringifiedPermissions
|
||||
}
|
||||
});
|
||||
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
@@ -149,7 +197,7 @@ export const registerOrgRoleRouter = async (server: FastifyZodProvider) => {
|
||||
}
|
||||
});
|
||||
|
||||
return { role };
|
||||
return { role: { ...role, orgId: role.orgId as string } };
|
||||
}
|
||||
});
|
||||
|
||||
@@ -172,13 +220,16 @@ export const registerOrgRoleRouter = async (server: FastifyZodProvider) => {
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const role = await server.services.orgRole.deleteRole(
|
||||
req.permission.id,
|
||||
req.params.organizationId,
|
||||
req.params.roleId,
|
||||
req.permission.authMethod,
|
||||
req.permission.orgId
|
||||
);
|
||||
const role = await server.services.role.deleteRole({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Organization,
|
||||
orgId: req.params.organizationId
|
||||
},
|
||||
selector: {
|
||||
id: req.params.roleId
|
||||
}
|
||||
});
|
||||
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
@@ -189,7 +240,7 @@ export const registerOrgRoleRouter = async (server: FastifyZodProvider) => {
|
||||
}
|
||||
});
|
||||
|
||||
return { role };
|
||||
return { role: { ...role, orgId: role.orgId as string } };
|
||||
}
|
||||
});
|
||||
|
||||
@@ -206,22 +257,26 @@ export const registerOrgRoleRouter = async (server: FastifyZodProvider) => {
|
||||
response: {
|
||||
200: z.object({
|
||||
data: z.object({
|
||||
roles: OrgRolesSchema.omit({ permissions: true })
|
||||
.merge(z.object({ permissions: z.unknown() }))
|
||||
.array()
|
||||
roles: OrgRolesSchema.omit({ permissions: true }).array()
|
||||
})
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const roles = await server.services.orgRole.listRoles(
|
||||
req.permission.id,
|
||||
req.params.organizationId,
|
||||
req.permission.authMethod,
|
||||
req.permission.orgId
|
||||
);
|
||||
return { data: { roles } };
|
||||
const { roles } = await server.services.role.listRoles({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Organization,
|
||||
orgId: req.permission.orgId
|
||||
},
|
||||
data: {}
|
||||
});
|
||||
return {
|
||||
data: {
|
||||
roles: roles.map((el) => ({ ...el, orgId: el.orgId as string }))
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
@@ -237,20 +292,33 @@ export const registerOrgRoleRouter = async (server: FastifyZodProvider) => {
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
membership: OrgMembershipsSchema,
|
||||
memberships: z
|
||||
.object({
|
||||
id: z.string(),
|
||||
roles: z
|
||||
.object({
|
||||
role: z.string()
|
||||
})
|
||||
.array()
|
||||
})
|
||||
.array(),
|
||||
permissions: z.any().array()
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const { permissions, membership } = await server.services.orgRole.getUserPermission(
|
||||
req.permission.id,
|
||||
req.params.organizationId,
|
||||
req.permission.authMethod,
|
||||
req.permission.orgId
|
||||
);
|
||||
return { permissions, membership };
|
||||
const { permissions, memberships } = await server.services.role.getUserPermission({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Organization,
|
||||
orgId: req.permission.orgId
|
||||
}
|
||||
});
|
||||
return {
|
||||
permissions,
|
||||
memberships
|
||||
};
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
@@ -0,0 +1,34 @@
|
||||
import {
|
||||
CreateMySQLAccountSchema,
|
||||
SanitizedMySQLAccountWithResourceSchema,
|
||||
UpdateMySQLAccountSchema
|
||||
} from "@app/ee/services/pam-resource/mysql/mysql-resource-schemas";
|
||||
import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums";
|
||||
import {
|
||||
CreatePostgresAccountSchema,
|
||||
SanitizedPostgresAccountWithResourceSchema,
|
||||
UpdatePostgresAccountSchema
|
||||
} from "@app/ee/services/pam-resource/postgres/postgres-resource-schemas";
|
||||
|
||||
import { registerPamResourceEndpoints } from "./pam-account-endpoints";
|
||||
|
||||
export const PAM_ACCOUNT_REGISTER_ROUTER_MAP: Record<PamResource, (server: FastifyZodProvider) => Promise<void>> = {
|
||||
[PamResource.Postgres]: async (server: FastifyZodProvider) => {
|
||||
registerPamResourceEndpoints({
|
||||
server,
|
||||
resourceType: PamResource.Postgres,
|
||||
accountResponseSchema: SanitizedPostgresAccountWithResourceSchema,
|
||||
createAccountSchema: CreatePostgresAccountSchema,
|
||||
updateAccountSchema: UpdatePostgresAccountSchema
|
||||
});
|
||||
},
|
||||
[PamResource.MySQL]: async (server: FastifyZodProvider) => {
|
||||
registerPamResourceEndpoints({
|
||||
server,
|
||||
resourceType: PamResource.MySQL,
|
||||
accountResponseSchema: SanitizedMySQLAccountWithResourceSchema,
|
||||
createAccountSchema: CreateMySQLAccountSchema,
|
||||
updateAccountSchema: UpdateMySQLAccountSchema
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,167 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
|
||||
import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums";
|
||||
import { TPamAccount } from "@app/ee/services/pam-resource/pam-resource-types";
|
||||
import { writeLimit } from "@app/server/config/rateLimiter";
|
||||
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
||||
import { AuthMode } from "@app/services/auth/auth-type";
|
||||
|
||||
export const registerPamResourceEndpoints = <C extends TPamAccount>({
|
||||
server,
|
||||
resourceType,
|
||||
createAccountSchema,
|
||||
updateAccountSchema,
|
||||
accountResponseSchema
|
||||
}: {
|
||||
server: FastifyZodProvider;
|
||||
resourceType: PamResource;
|
||||
createAccountSchema: z.ZodType<{
|
||||
credentials: C["credentials"];
|
||||
resourceId: C["resourceId"];
|
||||
folderId?: C["folderId"];
|
||||
name: C["name"];
|
||||
description?: C["description"];
|
||||
rotationEnabled: C["rotationEnabled"];
|
||||
rotationIntervalSeconds?: C["rotationIntervalSeconds"];
|
||||
}>;
|
||||
updateAccountSchema: z.ZodType<{
|
||||
credentials?: C["credentials"];
|
||||
name?: C["name"];
|
||||
description?: C["description"];
|
||||
rotationEnabled?: C["rotationEnabled"];
|
||||
rotationIntervalSeconds?: C["rotationIntervalSeconds"];
|
||||
}>;
|
||||
accountResponseSchema: z.ZodTypeAny;
|
||||
}) => {
|
||||
server.route({
|
||||
method: "POST",
|
||||
url: "/",
|
||||
config: {
|
||||
rateLimit: writeLimit
|
||||
},
|
||||
schema: {
|
||||
description: "Create PAM account",
|
||||
body: createAccountSchema,
|
||||
response: {
|
||||
200: z.object({
|
||||
account: accountResponseSchema
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const account = await server.services.pamAccount.create(req.body, req.permission);
|
||||
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: account.projectId,
|
||||
event: {
|
||||
type: EventType.PAM_ACCOUNT_CREATE,
|
||||
metadata: {
|
||||
resourceId: req.body.resourceId,
|
||||
resourceType,
|
||||
folderId: req.body.folderId,
|
||||
name: req.body.name,
|
||||
description: req.body.description,
|
||||
rotationEnabled: req.body.rotationEnabled,
|
||||
rotationIntervalSeconds: req.body.rotationIntervalSeconds
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return { account };
|
||||
}
|
||||
});
|
||||
|
||||
server.route({
|
||||
method: "PATCH",
|
||||
url: "/:accountId",
|
||||
config: {
|
||||
rateLimit: writeLimit
|
||||
},
|
||||
schema: {
|
||||
description: "Update PAM account",
|
||||
params: z.object({
|
||||
accountId: z.string().uuid()
|
||||
}),
|
||||
body: updateAccountSchema,
|
||||
response: {
|
||||
200: z.object({
|
||||
account: accountResponseSchema
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const account = await server.services.pamAccount.updateById(
|
||||
{
|
||||
...req.body,
|
||||
accountId: req.params.accountId
|
||||
},
|
||||
req.permission
|
||||
);
|
||||
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: account.projectId,
|
||||
event: {
|
||||
type: EventType.PAM_ACCOUNT_UPDATE,
|
||||
metadata: {
|
||||
accountId: req.params.accountId,
|
||||
resourceId: account.resourceId,
|
||||
resourceType,
|
||||
name: req.body.name,
|
||||
description: req.body.description,
|
||||
rotationEnabled: req.body.rotationEnabled,
|
||||
rotationIntervalSeconds: req.body.rotationIntervalSeconds
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return { account };
|
||||
}
|
||||
});
|
||||
|
||||
server.route({
|
||||
method: "DELETE",
|
||||
url: "/:accountId",
|
||||
config: {
|
||||
rateLimit: writeLimit
|
||||
},
|
||||
schema: {
|
||||
description: "Delete PAM account",
|
||||
params: z.object({
|
||||
accountId: z.string().uuid()
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
account: accountResponseSchema
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const account = await server.services.pamAccount.deleteById(req.params.accountId, req.permission);
|
||||
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: account.projectId,
|
||||
event: {
|
||||
type: EventType.PAM_ACCOUNT_DELETE,
|
||||
metadata: {
|
||||
accountId: req.params.accountId,
|
||||
accountName: account.name,
|
||||
resourceId: account.resourceId,
|
||||
resourceType
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return { account };
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,134 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { PamFoldersSchema } from "@app/db/schemas";
|
||||
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
|
||||
import { SanitizedMySQLAccountWithResourceSchema } from "@app/ee/services/pam-resource/mysql/mysql-resource-schemas";
|
||||
import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums";
|
||||
import { SanitizedPostgresAccountWithResourceSchema } from "@app/ee/services/pam-resource/postgres/postgres-resource-schemas";
|
||||
import { BadRequestError } from "@app/lib/errors";
|
||||
import { ms } from "@app/lib/ms";
|
||||
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
|
||||
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
||||
import { AuthMode } from "@app/services/auth/auth-type";
|
||||
|
||||
const SanitizedAccountSchema = z.union([
|
||||
SanitizedPostgresAccountWithResourceSchema,
|
||||
SanitizedMySQLAccountWithResourceSchema
|
||||
]);
|
||||
|
||||
export const registerPamAccountRouter = async (server: FastifyZodProvider) => {
|
||||
server.route({
|
||||
method: "GET",
|
||||
url: "/",
|
||||
config: {
|
||||
rateLimit: readLimit
|
||||
},
|
||||
schema: {
|
||||
description: "List PAM accounts",
|
||||
querystring: z.object({
|
||||
projectId: z.string().uuid()
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
accounts: SanitizedAccountSchema.array(),
|
||||
folders: PamFoldersSchema.array()
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const response = await server.services.pamAccount.list(req.query.projectId, req.permission);
|
||||
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: req.query.projectId,
|
||||
event: {
|
||||
type: EventType.PAM_ACCOUNT_LIST,
|
||||
metadata: {
|
||||
accountCount: response.accounts.length,
|
||||
folderCount: response.folders.length
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return response;
|
||||
}
|
||||
});
|
||||
|
||||
server.route({
|
||||
method: "POST",
|
||||
url: "/access",
|
||||
config: {
|
||||
rateLimit: writeLimit
|
||||
},
|
||||
schema: {
|
||||
description: "Access PAM account",
|
||||
body: z.object({
|
||||
accountId: z.string().uuid(),
|
||||
duration: z
|
||||
.string()
|
||||
.min(1)
|
||||
.transform((val, ctx) => {
|
||||
const parsedMs = ms(val);
|
||||
|
||||
if (typeof parsedMs !== "number" || parsedMs <= 0) {
|
||||
ctx.addIssue({
|
||||
code: z.ZodIssueCode.custom,
|
||||
message: "Invalid duration format. Must be a positive duration (e.g., '1h', '30m', '2d')."
|
||||
});
|
||||
return z.NEVER;
|
||||
}
|
||||
return parsedMs;
|
||||
})
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
sessionId: z.string(),
|
||||
resourceType: z.nativeEnum(PamResource),
|
||||
relayClientCertificate: z.string(),
|
||||
relayClientPrivateKey: z.string(),
|
||||
relayServerCertificateChain: z.string(),
|
||||
gatewayClientCertificate: z.string(),
|
||||
gatewayClientPrivateKey: z.string(),
|
||||
gatewayServerCertificateChain: z.string(),
|
||||
relayHost: z.string()
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
// To prevent type errors when accessing req.auth
|
||||
if (req.auth.authMode !== AuthMode.JWT) {
|
||||
throw new BadRequestError({ message: "You can only access PAM accounts using JWT auth tokens." });
|
||||
}
|
||||
|
||||
const response = await server.services.pamAccount.access(
|
||||
{
|
||||
actorEmail: req.auth.user.email ?? "",
|
||||
actorIp: req.realIp,
|
||||
actorName: `${req.auth.user.firstName ?? ""} ${req.auth.user.lastName ?? ""}`.trim(),
|
||||
actorUserAgent: req.auditLogInfo.userAgent ?? "",
|
||||
...req.body
|
||||
},
|
||||
req.permission
|
||||
);
|
||||
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: response.projectId,
|
||||
event: {
|
||||
type: EventType.PAM_ACCOUNT_ACCESS,
|
||||
metadata: {
|
||||
accountId: req.body.accountId,
|
||||
accountName: response.account.name,
|
||||
duration: req.body.duration ? new Date(req.body.duration).toISOString() : undefined
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return response;
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,150 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { PamFoldersSchema } from "@app/db/schemas";
|
||||
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
|
||||
import { isValidFolderName } from "@app/lib/validator";
|
||||
import { writeLimit } from "@app/server/config/rateLimiter";
|
||||
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
||||
import { AuthMode } from "@app/services/auth/auth-type";
|
||||
|
||||
export const registerPamFolderRouter = async (server: FastifyZodProvider) => {
|
||||
server.route({
|
||||
method: "POST",
|
||||
url: "/",
|
||||
config: {
|
||||
rateLimit: writeLimit
|
||||
},
|
||||
schema: {
|
||||
description: "Create PAM folder",
|
||||
body: z.object({
|
||||
projectId: z.string().uuid(),
|
||||
parentId: z.string().uuid().nullable().optional(),
|
||||
name: z
|
||||
.string()
|
||||
.trim()
|
||||
.refine((name) => isValidFolderName(name), {
|
||||
message: "Folder name can only contain alphanumeric characters, dashes, and underscores."
|
||||
}),
|
||||
description: z.string().trim().max(512).nullable().optional()
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
folder: PamFoldersSchema
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const folder = await server.services.pamFolder.createFolder(req.body, req.permission);
|
||||
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: req.body.projectId,
|
||||
event: {
|
||||
type: EventType.PAM_FOLDER_CREATE,
|
||||
metadata: {
|
||||
name: req.body.name,
|
||||
description: req.body.description,
|
||||
parentId: req.body.parentId
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return { folder };
|
||||
}
|
||||
});
|
||||
|
||||
server.route({
|
||||
method: "PATCH",
|
||||
url: "/:folderId",
|
||||
config: {
|
||||
rateLimit: writeLimit
|
||||
},
|
||||
schema: {
|
||||
description: "Update PAM folder",
|
||||
params: z.object({
|
||||
folderId: z.string().uuid()
|
||||
}),
|
||||
body: z.object({
|
||||
name: z
|
||||
.string()
|
||||
.trim()
|
||||
.optional()
|
||||
.refine((name) => (name ? isValidFolderName(name) : true), {
|
||||
message: "Folder name can only contain alphanumeric characters, dashes, and underscores."
|
||||
}),
|
||||
description: z.string().trim().max(512).nullable().optional()
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
folder: PamFoldersSchema
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const folder = await server.services.pamFolder.updateFolder(
|
||||
{
|
||||
...req.body,
|
||||
id: req.params.folderId
|
||||
},
|
||||
req.permission
|
||||
);
|
||||
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: folder.projectId,
|
||||
event: {
|
||||
type: EventType.PAM_FOLDER_UPDATE,
|
||||
metadata: {
|
||||
folderId: req.params.folderId,
|
||||
name: req.body.name,
|
||||
description: req.body.description
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return { folder };
|
||||
}
|
||||
});
|
||||
|
||||
server.route({
|
||||
method: "DELETE",
|
||||
url: "/:folderId",
|
||||
config: {
|
||||
rateLimit: writeLimit
|
||||
},
|
||||
schema: {
|
||||
description: "Delete PAM folder",
|
||||
params: z.object({
|
||||
folderId: z.string().uuid()
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
folder: PamFoldersSchema
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const folder = await server.services.pamFolder.deleteFolder(req.params.folderId, req.permission);
|
||||
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: folder.projectId,
|
||||
event: {
|
||||
type: EventType.PAM_FOLDER_DELETE,
|
||||
metadata: {
|
||||
folderName: folder.name,
|
||||
folderId: req.params.folderId
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return { folder };
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,34 @@
|
||||
import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums";
|
||||
import {
|
||||
CreatePostgresResourceSchema,
|
||||
SanitizedPostgresResourceSchema,
|
||||
UpdatePostgresResourceSchema
|
||||
} from "@app/ee/services/pam-resource/postgres/postgres-resource-schemas";
|
||||
import {
|
||||
CreateMySQLResourceSchema,
|
||||
MySQLResourceSchema,
|
||||
UpdateMySQLResourceSchema
|
||||
} from "@app/ee/services/pam-resource/mysql/mysql-resource-schemas";
|
||||
|
||||
import { registerPamResourceEndpoints } from "./pam-resource-endpoints";
|
||||
|
||||
export const PAM_RESOURCE_REGISTER_ROUTER_MAP: Record<PamResource, (server: FastifyZodProvider) => Promise<void>> = {
|
||||
[PamResource.Postgres]: async (server: FastifyZodProvider) => {
|
||||
registerPamResourceEndpoints({
|
||||
server,
|
||||
resourceType: PamResource.Postgres,
|
||||
resourceResponseSchema: SanitizedPostgresResourceSchema,
|
||||
createResourceSchema: CreatePostgresResourceSchema,
|
||||
updateResourceSchema: UpdatePostgresResourceSchema
|
||||
});
|
||||
},
|
||||
[PamResource.MySQL]: async (server: FastifyZodProvider) => {
|
||||
registerPamResourceEndpoints({
|
||||
server,
|
||||
resourceType: PamResource.MySQL,
|
||||
resourceResponseSchema: MySQLResourceSchema,
|
||||
createResourceSchema: CreateMySQLResourceSchema,
|
||||
updateResourceSchema: UpdateMySQLResourceSchema
|
||||
});
|
||||
}
|
||||
};
|
||||
@@ -0,0 +1,200 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
|
||||
import { PamResource } from "@app/ee/services/pam-resource/pam-resource-enums";
|
||||
import { TPamResource } from "@app/ee/services/pam-resource/pam-resource-types";
|
||||
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
|
||||
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
||||
import { AuthMode } from "@app/services/auth/auth-type";
|
||||
|
||||
export const registerPamResourceEndpoints = <T extends TPamResource>({
|
||||
server,
|
||||
resourceType,
|
||||
createResourceSchema,
|
||||
updateResourceSchema,
|
||||
resourceResponseSchema
|
||||
}: {
|
||||
server: FastifyZodProvider;
|
||||
resourceType: PamResource;
|
||||
createResourceSchema: z.ZodType<{
|
||||
projectId: T["projectId"];
|
||||
connectionDetails: T["connectionDetails"];
|
||||
gatewayId: T["gatewayId"];
|
||||
name: T["name"];
|
||||
rotationAccountCredentials?: T["rotationAccountCredentials"];
|
||||
}>;
|
||||
updateResourceSchema: z.ZodType<{
|
||||
connectionDetails?: T["connectionDetails"];
|
||||
gatewayId?: T["gatewayId"];
|
||||
name?: T["name"];
|
||||
rotationAccountCredentials?: T["rotationAccountCredentials"];
|
||||
}>;
|
||||
resourceResponseSchema: z.ZodTypeAny;
|
||||
}) => {
|
||||
server.route({
|
||||
method: "GET",
|
||||
url: "/:resourceId",
|
||||
config: {
|
||||
rateLimit: readLimit
|
||||
},
|
||||
schema: {
|
||||
description: "Get PAM resource",
|
||||
params: z.object({
|
||||
resourceId: z.string().uuid()
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
resource: resourceResponseSchema
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const resource = await server.services.pamResource.getById(req.params.resourceId, resourceType, req.permission);
|
||||
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: resource.projectId,
|
||||
event: {
|
||||
type: EventType.PAM_RESOURCE_GET,
|
||||
metadata: {
|
||||
resourceId: resource.id,
|
||||
resourceType: resource.resourceType,
|
||||
name: resource.name
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return { resource };
|
||||
}
|
||||
});
|
||||
|
||||
server.route({
|
||||
method: "POST",
|
||||
url: "/",
|
||||
config: {
|
||||
rateLimit: writeLimit
|
||||
},
|
||||
schema: {
|
||||
description: "Create PAM resource",
|
||||
body: createResourceSchema,
|
||||
response: {
|
||||
200: z.object({
|
||||
resource: resourceResponseSchema
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const resource = await server.services.pamResource.create(
|
||||
{
|
||||
...req.body,
|
||||
resourceType
|
||||
},
|
||||
req.permission
|
||||
);
|
||||
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: req.body.projectId,
|
||||
event: {
|
||||
type: EventType.PAM_RESOURCE_CREATE,
|
||||
metadata: {
|
||||
resourceType,
|
||||
gatewayId: req.body.gatewayId,
|
||||
name: req.body.name
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return { resource };
|
||||
}
|
||||
});
|
||||
|
||||
server.route({
|
||||
method: "PATCH",
|
||||
url: "/:resourceId",
|
||||
config: {
|
||||
rateLimit: writeLimit
|
||||
},
|
||||
schema: {
|
||||
description: "Update PAM resource",
|
||||
params: z.object({
|
||||
resourceId: z.string().uuid()
|
||||
}),
|
||||
body: updateResourceSchema,
|
||||
response: {
|
||||
200: z.object({
|
||||
resource: resourceResponseSchema
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const resource = await server.services.pamResource.updateById(
|
||||
{
|
||||
...req.body,
|
||||
resourceId: req.params.resourceId
|
||||
},
|
||||
req.permission
|
||||
);
|
||||
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: resource.projectId,
|
||||
event: {
|
||||
type: EventType.PAM_RESOURCE_UPDATE,
|
||||
metadata: {
|
||||
resourceId: req.params.resourceId,
|
||||
resourceType,
|
||||
gatewayId: req.body.gatewayId,
|
||||
name: req.body.name
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return { resource };
|
||||
}
|
||||
});
|
||||
|
||||
server.route({
|
||||
method: "DELETE",
|
||||
url: "/:resourceId",
|
||||
config: {
|
||||
rateLimit: writeLimit
|
||||
},
|
||||
schema: {
|
||||
description: "Delete PAM resource",
|
||||
params: z.object({
|
||||
resourceId: z.string().uuid()
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
resource: resourceResponseSchema
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const resource = await server.services.pamResource.deleteById(req.params.resourceId, req.permission);
|
||||
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: resource.projectId,
|
||||
event: {
|
||||
type: EventType.PAM_RESOURCE_DELETE,
|
||||
metadata: {
|
||||
resourceId: req.params.resourceId,
|
||||
resourceType
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return { resource };
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,82 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
|
||||
import {
|
||||
MySQLResourceListItemSchema,
|
||||
SanitizedMySQLResourceSchema
|
||||
} from "@app/ee/services/pam-resource/mysql/mysql-resource-schemas";
|
||||
import {
|
||||
PostgresResourceListItemSchema,
|
||||
SanitizedPostgresResourceSchema
|
||||
} from "@app/ee/services/pam-resource/postgres/postgres-resource-schemas";
|
||||
import { readLimit } from "@app/server/config/rateLimiter";
|
||||
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
||||
import { AuthMode } from "@app/services/auth/auth-type";
|
||||
|
||||
const SanitizedResourceSchema = z.union([SanitizedPostgresResourceSchema, SanitizedMySQLResourceSchema]);
|
||||
|
||||
const ResourceOptionsSchema = z.discriminatedUnion("resource", [
|
||||
PostgresResourceListItemSchema,
|
||||
MySQLResourceListItemSchema
|
||||
]);
|
||||
|
||||
export const registerPamResourceRouter = async (server: FastifyZodProvider) => {
|
||||
server.route({
|
||||
method: "GET",
|
||||
url: "/options",
|
||||
config: {
|
||||
rateLimit: readLimit
|
||||
},
|
||||
schema: {
|
||||
description: "List PAM resource types",
|
||||
response: {
|
||||
200: z.object({
|
||||
resourceOptions: ResourceOptionsSchema.array()
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: () => {
|
||||
const resourceOptions = server.services.pamResource.listResourceOptions();
|
||||
|
||||
return { resourceOptions };
|
||||
}
|
||||
});
|
||||
|
||||
server.route({
|
||||
method: "GET",
|
||||
url: "/",
|
||||
config: {
|
||||
rateLimit: readLimit
|
||||
},
|
||||
schema: {
|
||||
description: "List PAM resources",
|
||||
querystring: z.object({
|
||||
projectId: z.string().uuid()
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
resources: SanitizedResourceSchema.array()
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const response = await server.services.pamResource.list(req.query.projectId, req.permission);
|
||||
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: req.query.projectId,
|
||||
event: {
|
||||
type: EventType.PAM_RESOURCE_LIST,
|
||||
metadata: {
|
||||
count: response.resources.length
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return response;
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -0,0 +1,224 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { PamSessionsSchema } from "@app/db/schemas";
|
||||
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
|
||||
import { MySQLSessionCredentialsSchema } from "@app/ee/services/pam-resource/mysql/mysql-resource-schemas";
|
||||
import { PostgresSessionCredentialsSchema } from "@app/ee/services/pam-resource/postgres/postgres-resource-schemas";
|
||||
import { PamSessionCommandLogSchema, SanitizedSessionSchema } from "@app/ee/services/pam-session/pam-session-schemas";
|
||||
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
|
||||
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
||||
import { AuthMode } from "@app/services/auth/auth-type";
|
||||
|
||||
const SessionCredentialsSchema = z.union([PostgresSessionCredentialsSchema, MySQLSessionCredentialsSchema]);
|
||||
|
||||
export const registerPamSessionRouter = async (server: FastifyZodProvider) => {
|
||||
// Meant to be hit solely by gateway identities
|
||||
server.route({
|
||||
method: "GET",
|
||||
url: "/:sessionId/credentials",
|
||||
config: {
|
||||
rateLimit: readLimit
|
||||
},
|
||||
schema: {
|
||||
description: "Get PAM session credentials and start session",
|
||||
params: z.object({
|
||||
sessionId: z.string().uuid()
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
credentials: SessionCredentialsSchema
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
handler: async (req) => {
|
||||
const { credentials, projectId, account } = await server.services.pamAccount.getSessionCredentials(
|
||||
req.params.sessionId,
|
||||
req.permission
|
||||
);
|
||||
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: req.permission.orgId,
|
||||
projectId,
|
||||
event: {
|
||||
type: EventType.PAM_SESSION_START,
|
||||
metadata: {
|
||||
sessionId: req.params.sessionId,
|
||||
accountName: account.name
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return { credentials };
|
||||
}
|
||||
});
|
||||
|
||||
// Meant to be hit solely by gateway identities
|
||||
server.route({
|
||||
method: "POST",
|
||||
url: "/:sessionId/logs",
|
||||
config: {
|
||||
rateLimit: writeLimit
|
||||
},
|
||||
schema: {
|
||||
description: "Update PAM session logs",
|
||||
params: z.object({
|
||||
sessionId: z.string().uuid()
|
||||
}),
|
||||
body: z.object({
|
||||
logs: PamSessionCommandLogSchema.array()
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
session: PamSessionsSchema.omit({
|
||||
encryptedLogsBlob: true
|
||||
})
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
handler: async (req) => {
|
||||
const { session, projectId } = await server.services.pamSession.updateLogsById(
|
||||
{
|
||||
sessionId: req.params.sessionId,
|
||||
logs: req.body.logs
|
||||
},
|
||||
req.permission
|
||||
);
|
||||
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: req.permission.orgId,
|
||||
projectId,
|
||||
event: {
|
||||
type: EventType.PAM_SESSION_LOGS_UPDATE,
|
||||
metadata: {
|
||||
sessionId: req.params.sessionId,
|
||||
accountName: session.accountName
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return { session };
|
||||
}
|
||||
});
|
||||
|
||||
// Meant to be hit solely by gateway identities
|
||||
server.route({
|
||||
method: "POST",
|
||||
url: "/:sessionId/end",
|
||||
config: {
|
||||
rateLimit: writeLimit
|
||||
},
|
||||
schema: {
|
||||
description: "End PAM session",
|
||||
params: z.object({
|
||||
sessionId: z.string().uuid()
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
session: PamSessionsSchema.omit({
|
||||
encryptedLogsBlob: true
|
||||
})
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
handler: async (req) => {
|
||||
const { session, projectId } = await server.services.pamSession.endSessionById(
|
||||
req.params.sessionId,
|
||||
req.permission
|
||||
);
|
||||
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: req.permission.orgId,
|
||||
projectId,
|
||||
event: {
|
||||
type: EventType.PAM_SESSION_END,
|
||||
metadata: {
|
||||
sessionId: req.params.sessionId,
|
||||
accountName: session.accountName
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return { session };
|
||||
}
|
||||
});
|
||||
|
||||
server.route({
|
||||
method: "GET",
|
||||
url: "/:sessionId",
|
||||
config: {
|
||||
rateLimit: readLimit
|
||||
},
|
||||
schema: {
|
||||
description: "Get PAM session",
|
||||
params: z.object({
|
||||
sessionId: z.string().uuid()
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
session: SanitizedSessionSchema
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const response = await server.services.pamSession.getById(req.params.sessionId, req.permission);
|
||||
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: response.session.projectId,
|
||||
event: {
|
||||
type: EventType.PAM_SESSION_GET,
|
||||
metadata: {
|
||||
sessionId: req.params.sessionId
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return response;
|
||||
}
|
||||
});
|
||||
|
||||
server.route({
|
||||
method: "GET",
|
||||
url: "/",
|
||||
config: {
|
||||
rateLimit: readLimit
|
||||
},
|
||||
schema: {
|
||||
description: "List PAM sessions",
|
||||
querystring: z.object({
|
||||
projectId: z.string().uuid()
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
sessions: SanitizedSessionSchema.array()
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const response = await server.services.pamSession.list(req.query.projectId, req.permission);
|
||||
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: req.query.projectId,
|
||||
event: {
|
||||
type: EventType.PAM_SESSION_LIST,
|
||||
metadata: {
|
||||
count: response.sessions.length
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return response;
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -1,7 +1,7 @@
|
||||
import { packRules } from "@casl/ability/extra";
|
||||
import { z } from "zod";
|
||||
|
||||
import { ProjectMembershipRole, ProjectRolesSchema } from "@app/db/schemas";
|
||||
import { AccessScope, ProjectMembershipRole, ProjectRolesSchema } from "@app/db/schemas";
|
||||
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
|
||||
import { checkForInvalidPermissionCombination } from "@app/ee/services/permission/permission-fns";
|
||||
import { ProjectPermissionV2Schema } from "@app/ee/services/permission/project-permission";
|
||||
@@ -11,7 +11,6 @@ import { slugSchema } from "@app/server/lib/schemas";
|
||||
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
||||
import { SanitizedRoleSchema } from "@app/server/routes/sanitizedSchemas";
|
||||
import { AuthMode } from "@app/services/auth/auth-type";
|
||||
import { ProjectRoleServiceIdentifierType } from "@app/services/project-role/project-role-types";
|
||||
|
||||
export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
|
||||
server.route({
|
||||
@@ -55,13 +54,11 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
|
||||
handler: async (req) => {
|
||||
const stringifiedPermissions = JSON.stringify(packRules(req.body.permissions));
|
||||
|
||||
const role = await server.services.projectRole.createRole({
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
actorId: req.permission.id,
|
||||
actorOrgId: req.permission.orgId,
|
||||
actor: req.permission.type,
|
||||
filter: {
|
||||
type: ProjectRoleServiceIdentifierType.ID,
|
||||
const role = await server.services.role.createRole({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: req.params.projectId
|
||||
},
|
||||
data: {
|
||||
@@ -73,7 +70,7 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: role.projectId,
|
||||
projectId: role.projectId as string,
|
||||
event: {
|
||||
type: EventType.CREATE_PROJECT_ROLE,
|
||||
metadata: {
|
||||
@@ -86,7 +83,7 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
|
||||
}
|
||||
});
|
||||
|
||||
return { role };
|
||||
return { role: { ...role, projectId: role.projectId as string } };
|
||||
}
|
||||
});
|
||||
|
||||
@@ -133,12 +130,16 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
handler: async (req) => {
|
||||
const stringifiedPermissions = req.body.permissions ? JSON.stringify(packRules(req.body.permissions)) : undefined;
|
||||
const role = await server.services.projectRole.updateRole({
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
actorId: req.permission.id,
|
||||
actorOrgId: req.permission.orgId,
|
||||
actor: req.permission.type,
|
||||
roleId: req.params.roleId,
|
||||
const role = await server.services.role.updateRole({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: req.params.projectId
|
||||
},
|
||||
selector: {
|
||||
id: req.params.roleId
|
||||
},
|
||||
data: {
|
||||
...req.body,
|
||||
permissions: stringifiedPermissions
|
||||
@@ -148,7 +149,7 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: role.projectId,
|
||||
projectId: role.projectId as string,
|
||||
event: {
|
||||
type: EventType.UPDATE_PROJECT_ROLE,
|
||||
metadata: {
|
||||
@@ -161,7 +162,7 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
|
||||
}
|
||||
});
|
||||
|
||||
return { role };
|
||||
return { role: { ...role, projectId: role.projectId as string } };
|
||||
}
|
||||
});
|
||||
|
||||
@@ -192,18 +193,22 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
handler: async (req) => {
|
||||
const role = await server.services.projectRole.deleteRole({
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
actorId: req.permission.id,
|
||||
actorOrgId: req.permission.orgId,
|
||||
actor: req.permission.type,
|
||||
roleId: req.params.roleId
|
||||
const role = await server.services.role.deleteRole({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: req.params.projectId
|
||||
},
|
||||
selector: {
|
||||
id: req.params.roleId
|
||||
}
|
||||
});
|
||||
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: role.projectId,
|
||||
projectId: role.projectId as string,
|
||||
event: {
|
||||
type: EventType.DELETE_PROJECT_ROLE,
|
||||
metadata: {
|
||||
@@ -214,7 +219,7 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
|
||||
}
|
||||
});
|
||||
|
||||
return { role };
|
||||
return { role: { ...role, projectId: role.projectId as string } };
|
||||
}
|
||||
});
|
||||
|
||||
@@ -244,17 +249,16 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
handler: async (req) => {
|
||||
const roles = await server.services.projectRole.listRoles({
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
actorId: req.permission.id,
|
||||
actorOrgId: req.permission.orgId,
|
||||
actor: req.permission.type,
|
||||
filter: {
|
||||
type: ProjectRoleServiceIdentifierType.ID,
|
||||
const { roles } = await server.services.role.listRoles({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: req.params.projectId
|
||||
}
|
||||
},
|
||||
data: {}
|
||||
});
|
||||
return { roles };
|
||||
return { roles: roles.map((el) => ({ ...el, projectId: el.projectId as string })) };
|
||||
}
|
||||
});
|
||||
|
||||
@@ -273,24 +277,25 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
role: SanitizedRoleSchema.omit({ version: true })
|
||||
role: SanitizedRoleSchema
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
handler: async (req) => {
|
||||
const role = await server.services.projectRole.getRoleBySlug({
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
actorId: req.permission.id,
|
||||
actorOrgId: req.permission.orgId,
|
||||
actor: req.permission.type,
|
||||
filter: {
|
||||
type: ProjectRoleServiceIdentifierType.ID,
|
||||
const role = await server.services.role.getRoleBySlug({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: req.params.projectId
|
||||
},
|
||||
roleSlug: req.params.roleSlug
|
||||
selector: {
|
||||
slug: req.params.roleSlug
|
||||
}
|
||||
});
|
||||
return { role };
|
||||
|
||||
return { role: { ...role, projectId: role.projectId as string } };
|
||||
}
|
||||
});
|
||||
|
||||
@@ -307,14 +312,16 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
|
||||
response: {
|
||||
200: z.object({
|
||||
data: z.object({
|
||||
membership: z.object({
|
||||
id: z.string(),
|
||||
roles: z
|
||||
.object({
|
||||
role: z.string()
|
||||
})
|
||||
.array()
|
||||
}),
|
||||
memberships: z
|
||||
.object({
|
||||
id: z.string(),
|
||||
roles: z
|
||||
.object({
|
||||
role: z.string()
|
||||
})
|
||||
.array()
|
||||
})
|
||||
.array(),
|
||||
assumedPrivilegeDetails: z
|
||||
.object({
|
||||
actorId: z.string(),
|
||||
@@ -330,17 +337,19 @@ export const registerProjectRoleRouter = async (server: FastifyZodProvider) => {
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const { permissions, membership, assumedPrivilegeDetails } = await server.services.projectRole.getUserPermission(
|
||||
req.permission.id,
|
||||
req.params.projectId,
|
||||
req.permission.authMethod,
|
||||
req.permission.orgId
|
||||
);
|
||||
const { permissions, memberships, assumedPrivilegeDetails } = await server.services.role.getUserPermission({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
projectId: req.params.projectId,
|
||||
orgId: req.permission.orgId
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
data: {
|
||||
permissions,
|
||||
membership,
|
||||
memberships,
|
||||
assumedPrivilegeDetails
|
||||
}
|
||||
};
|
||||
|
||||
@@ -146,4 +146,85 @@ export const registerRelayRouter = async (server: FastifyZodProvider) => {
|
||||
});
|
||||
}
|
||||
});
|
||||
|
||||
server.route({
|
||||
method: "POST",
|
||||
url: "/heartbeat-instance-relay",
|
||||
config: {
|
||||
rateLimit: writeLimit
|
||||
},
|
||||
schema: {
|
||||
body: z.object({
|
||||
name: slugSchema({ min: 1, max: 32, field: "name" })
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
message: z.string()
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: (req, _, next) => {
|
||||
const authHeader = req.headers.authorization;
|
||||
|
||||
if (!appCfg.RELAY_AUTH_SECRET) {
|
||||
throw new UnauthorizedError({
|
||||
message: "Relay authentication not configured"
|
||||
});
|
||||
}
|
||||
|
||||
if (!authHeader) {
|
||||
throw new UnauthorizedError({
|
||||
message: "Missing authorization header"
|
||||
});
|
||||
}
|
||||
|
||||
const expectedHeader = `Bearer ${appCfg.RELAY_AUTH_SECRET}`;
|
||||
if (
|
||||
authHeader.length === expectedHeader.length &&
|
||||
crypto.nativeCrypto.timingSafeEqual(Buffer.from(authHeader), Buffer.from(expectedHeader))
|
||||
) {
|
||||
return next();
|
||||
}
|
||||
|
||||
throw new UnauthorizedError({
|
||||
message: "Invalid relay auth secret"
|
||||
});
|
||||
},
|
||||
handler: async (req) => {
|
||||
await server.services.relay.heartbeat({
|
||||
name: req.body.name
|
||||
});
|
||||
|
||||
return { message: "Successfully triggered heartbeat" };
|
||||
}
|
||||
});
|
||||
|
||||
server.route({
|
||||
method: "POST",
|
||||
url: "/heartbeat-org-relay",
|
||||
config: {
|
||||
rateLimit: writeLimit
|
||||
},
|
||||
schema: {
|
||||
body: z.object({
|
||||
name: slugSchema({ min: 1, max: 32, field: "name" })
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
message: z.string()
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
handler: async (req) => {
|
||||
await server.services.relay.heartbeat({
|
||||
name: req.body.name,
|
||||
identityId: req.permission.id,
|
||||
orgId: req.permission.orgId,
|
||||
actorAuthMethod: req.permission.authMethod
|
||||
});
|
||||
|
||||
return { message: "Successfully triggered heartbeat" };
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
@@ -11,7 +11,6 @@ const AccessListEntrySchema = z
|
||||
.object({
|
||||
allowedActions: z.nativeEnum(ProjectPermissionSecretActions).array(),
|
||||
id: z.string(),
|
||||
membershipId: z.string(),
|
||||
name: z.string()
|
||||
})
|
||||
.array();
|
||||
|
||||
@@ -0,0 +1,163 @@
|
||||
import { z } from "zod";
|
||||
|
||||
import { OrganizationsSchema } from "@app/db/schemas";
|
||||
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
|
||||
import { ApiDocsTags, SUB_ORGANIZATIONS } from "@app/lib/api-docs";
|
||||
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
|
||||
import { slugSchema } from "@app/server/lib/schemas";
|
||||
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
||||
import { AuthMode } from "@app/services/auth/auth-type";
|
||||
|
||||
const sanitizedSubOrganizationSchema = OrganizationsSchema.pick({
|
||||
id: true,
|
||||
name: true,
|
||||
slug: true,
|
||||
createdAt: true,
|
||||
updatedAt: true,
|
||||
parentOrgId: true
|
||||
});
|
||||
|
||||
export const registerSubOrgRouter = async (server: FastifyZodProvider) => {
|
||||
server.route({
|
||||
method: "POST",
|
||||
url: "/",
|
||||
config: {
|
||||
rateLimit: writeLimit
|
||||
},
|
||||
schema: {
|
||||
hide: false,
|
||||
tags: [ApiDocsTags.SubOrganizations],
|
||||
description: "Create a sub organization",
|
||||
security: [
|
||||
{
|
||||
bearerAuth: []
|
||||
}
|
||||
],
|
||||
body: z.object({
|
||||
name: slugSchema().describe(SUB_ORGANIZATIONS.CREATE.name)
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
organization: sanitizedSubOrganizationSchema
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const { organization } = await server.services.subOrganization.createSubOrg({
|
||||
name: req.body.name,
|
||||
permissionActor: req.permission
|
||||
});
|
||||
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: req.permission.orgId,
|
||||
event: {
|
||||
type: EventType.CREATE_SUB_ORGANIZATION,
|
||||
metadata: {
|
||||
name: req.body.name,
|
||||
organizationId: organization.id
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return { organization };
|
||||
}
|
||||
});
|
||||
|
||||
server.route({
|
||||
method: "GET",
|
||||
url: "/",
|
||||
config: {
|
||||
rateLimit: readLimit
|
||||
},
|
||||
schema: {
|
||||
hide: false,
|
||||
tags: [ApiDocsTags.SubOrganizations],
|
||||
description: "List of sub organizations",
|
||||
security: [
|
||||
{
|
||||
bearerAuth: []
|
||||
}
|
||||
],
|
||||
querystring: z.object({
|
||||
limit: z.coerce.number().min(1).max(1000).default(25).describe(SUB_ORGANIZATIONS.LIST.limit),
|
||||
offset: z.coerce.number().min(0).default(0).describe(SUB_ORGANIZATIONS.LIST.offset),
|
||||
isAccessible: z
|
||||
.enum(["true", "false"])
|
||||
.optional()
|
||||
.transform((value) => value === "true")
|
||||
.describe(SUB_ORGANIZATIONS.LIST.isAccessible)
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
organizations: sanitizedSubOrganizationSchema.array()
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const { organizations } = await server.services.subOrganization.listSubOrgs({
|
||||
permissionActor: req.permission,
|
||||
data: {
|
||||
limit: req.query.limit,
|
||||
offset: req.query.offset,
|
||||
isAccessible: req.query.isAccessible
|
||||
}
|
||||
});
|
||||
|
||||
return { organizations };
|
||||
}
|
||||
});
|
||||
|
||||
server.route({
|
||||
method: "PATCH",
|
||||
url: "/:subOrgId",
|
||||
config: {
|
||||
rateLimit: writeLimit
|
||||
},
|
||||
schema: {
|
||||
hide: false,
|
||||
tags: [ApiDocsTags.SubOrganizations],
|
||||
description: "Update a sub organization",
|
||||
security: [
|
||||
{
|
||||
bearerAuth: []
|
||||
}
|
||||
],
|
||||
params: z.object({
|
||||
subOrgId: z.string().trim().describe(SUB_ORGANIZATIONS.UPDATE.subOrgId)
|
||||
}),
|
||||
body: z.object({
|
||||
name: slugSchema().describe(SUB_ORGANIZATIONS.UPDATE.name)
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
organization: sanitizedSubOrganizationSchema
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const { organization } = await server.services.subOrganization.updateSubOrg({
|
||||
subOrgId: req.params.subOrgId,
|
||||
name: req.body.name,
|
||||
permissionActor: req.permission
|
||||
});
|
||||
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: req.permission.orgId,
|
||||
event: {
|
||||
type: EventType.UPDATE_SUB_ORGANIZATION,
|
||||
metadata: {
|
||||
name: req.body.name,
|
||||
organizationId: organization.id
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
return { organization };
|
||||
}
|
||||
});
|
||||
};
|
||||
@@ -1,17 +1,18 @@
|
||||
import slugify from "@sindresorhus/slugify";
|
||||
import { z } from "zod";
|
||||
|
||||
import { AccessScope, TemporaryPermissionMode } from "@app/db/schemas";
|
||||
import { checkForInvalidPermissionCombination } from "@app/ee/services/permission/permission-fns";
|
||||
import { ProjectPermissionV2Schema } from "@app/ee/services/permission/project-permission";
|
||||
import { ProjectUserAdditionalPrivilegeTemporaryMode } from "@app/ee/services/project-user-additional-privilege/project-user-additional-privilege-types";
|
||||
import { PROJECT_USER_ADDITIONAL_PRIVILEGE } from "@app/lib/api-docs";
|
||||
import { NotFoundError } from "@app/lib/errors";
|
||||
import { ms } from "@app/lib/ms";
|
||||
import { alphaNumericNanoId } from "@app/lib/nanoid";
|
||||
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
|
||||
import { slugSchema } from "@app/server/lib/schemas";
|
||||
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
||||
import { SanitizedUserProjectAdditionalPrivilegeSchema } from "@app/server/routes/sanitizedSchema/user-additional-privilege";
|
||||
import { AuthMode } from "@app/services/auth/auth-type";
|
||||
import { ActorType, AuthMode } from "@app/services/auth/auth-type";
|
||||
|
||||
export const registerUserAdditionalPrivilegeRouter = async (server: FastifyZodProvider) => {
|
||||
server.route({
|
||||
@@ -34,7 +35,7 @@ export const registerUserAdditionalPrivilegeRouter = async (server: FastifyZodPr
|
||||
z.object({
|
||||
isTemporary: z.literal(true),
|
||||
temporaryMode: z
|
||||
.nativeEnum(ProjectUserAdditionalPrivilegeTemporaryMode)
|
||||
.nativeEnum(TemporaryPermissionMode)
|
||||
.describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.CREATE.temporaryMode),
|
||||
temporaryRange: z
|
||||
.string()
|
||||
@@ -55,17 +56,31 @@ export const registerUserAdditionalPrivilegeRouter = async (server: FastifyZodPr
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const privilege = await server.services.projectUserAdditionalPrivilege.create({
|
||||
actorId: req.permission.id,
|
||||
actor: req.permission.type,
|
||||
actorOrgId: req.permission.orgId,
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
projectMembershipId: req.body.projectMembershipId,
|
||||
...req.body.type,
|
||||
slug: req.body.slug || slugify(alphaNumericNanoId(8)),
|
||||
permissions: req.body.permissions
|
||||
const { userId, membership } = await server.services.convertor.userMembershipIdToUserId(
|
||||
req.body.projectMembershipId,
|
||||
AccessScope.Project,
|
||||
req.permission.orgId
|
||||
);
|
||||
|
||||
const { additionalPrivilege: privilege } = await server.services.additionalPrivilege.createAdditionalPrivilege({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
projectId: membership.scopeProjectId as string,
|
||||
orgId: req.permission.orgId
|
||||
},
|
||||
data: {
|
||||
actorId: userId,
|
||||
actorType: ActorType.USER,
|
||||
...req.body.type,
|
||||
name: req.body.slug || slugify(alphaNumericNanoId(8)),
|
||||
permissions: req.body.permissions
|
||||
}
|
||||
});
|
||||
return { privilege };
|
||||
|
||||
return {
|
||||
privilege: { ...privilege, userId, projectId: membership.scopeProjectId as string, slug: privilege.name }
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
@@ -91,7 +106,7 @@ export const registerUserAdditionalPrivilegeRouter = async (server: FastifyZodPr
|
||||
z.object({
|
||||
isTemporary: z.literal(true).describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.UPDATE.isTemporary),
|
||||
temporaryMode: z
|
||||
.nativeEnum(ProjectUserAdditionalPrivilegeTemporaryMode)
|
||||
.nativeEnum(TemporaryPermissionMode)
|
||||
.describe(PROJECT_USER_ADDITIONAL_PRIVILEGE.UPDATE.temporaryMode),
|
||||
temporaryRange: z
|
||||
.string()
|
||||
@@ -113,21 +128,41 @@ export const registerUserAdditionalPrivilegeRouter = async (server: FastifyZodPr
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const privilege = await server.services.projectUserAdditionalPrivilege.updateById({
|
||||
actorId: req.permission.id,
|
||||
actor: req.permission.type,
|
||||
actorOrgId: req.permission.orgId,
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
...req.body,
|
||||
...req.body.type,
|
||||
permissions: req.body.permissions
|
||||
? // eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore-error this is valid ts
|
||||
req.body.permissions
|
||||
: undefined,
|
||||
privilegeId: req.params.privilegeId
|
||||
const data = await server.services.convertor.additionalPrivilegeIdToDoc(req.params.privilegeId);
|
||||
if (!data.privilege.actorUserId)
|
||||
throw new NotFoundError({ message: `Privilege with id ${req.params.privilegeId} not found` });
|
||||
|
||||
const { additionalPrivilege: privilege } = await server.services.additionalPrivilege.updateAdditionalPrivilege({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
projectId: data.privilege.projectId as string,
|
||||
orgId: req.permission.orgId
|
||||
},
|
||||
data: {
|
||||
...req.body,
|
||||
...req.body.type,
|
||||
permissions: req.body.permissions
|
||||
? // eslint-disable-next-line @typescript-eslint/ban-ts-comment
|
||||
// @ts-ignore-error this is valid ts
|
||||
req.body.permissions
|
||||
: undefined
|
||||
},
|
||||
selector: {
|
||||
id: req.params.privilegeId,
|
||||
actorId: data.privilege.actorUserId,
|
||||
actorType: ActorType.USER
|
||||
}
|
||||
});
|
||||
return { privilege };
|
||||
|
||||
return {
|
||||
privilege: {
|
||||
...privilege,
|
||||
userId: data.privilege.actorUserId,
|
||||
projectId: data.privilege.projectId as string,
|
||||
slug: privilege.name
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
@@ -149,14 +184,32 @@ export const registerUserAdditionalPrivilegeRouter = async (server: FastifyZodPr
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const privilege = await server.services.projectUserAdditionalPrivilege.deleteById({
|
||||
actorId: req.permission.id,
|
||||
actor: req.permission.type,
|
||||
actorOrgId: req.permission.orgId,
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
privilegeId: req.params.privilegeId
|
||||
const data = await server.services.convertor.additionalPrivilegeIdToDoc(req.params.privilegeId);
|
||||
if (!data.privilege.actorUserId)
|
||||
throw new NotFoundError({ message: `Privilege with id ${req.params.privilegeId} not found` });
|
||||
|
||||
const { additionalPrivilege: privilege } = await server.services.additionalPrivilege.deleteAdditionalPrivilege({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
projectId: data.privilege.projectId as string,
|
||||
orgId: req.permission.orgId
|
||||
},
|
||||
selector: {
|
||||
id: req.params.privilegeId,
|
||||
actorId: data.privilege.actorUserId,
|
||||
actorType: ActorType.USER
|
||||
}
|
||||
});
|
||||
return { privilege };
|
||||
|
||||
return {
|
||||
privilege: {
|
||||
...privilege,
|
||||
userId: data.privilege.actorUserId,
|
||||
projectId: data.privilege.projectId as string,
|
||||
slug: privilege.name
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
@@ -178,14 +231,33 @@ export const registerUserAdditionalPrivilegeRouter = async (server: FastifyZodPr
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const privileges = await server.services.projectUserAdditionalPrivilege.listPrivileges({
|
||||
actorId: req.permission.id,
|
||||
actor: req.permission.type,
|
||||
actorOrgId: req.permission.orgId,
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
projectMembershipId: req.query.projectMembershipId
|
||||
const { userId, membership } = await server.services.convertor.userMembershipIdToUserId(
|
||||
req.query.projectMembershipId,
|
||||
AccessScope.Project,
|
||||
req.permission.orgId
|
||||
);
|
||||
|
||||
const { additionalPrivileges: privileges } = await server.services.additionalPrivilege.listAdditionalPrivileges({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
projectId: membership.scopeProjectId as string,
|
||||
orgId: req.permission.orgId
|
||||
},
|
||||
selector: {
|
||||
actorId: userId,
|
||||
actorType: ActorType.USER
|
||||
}
|
||||
});
|
||||
return { privileges };
|
||||
|
||||
return {
|
||||
privileges: privileges.map((privilege) => ({
|
||||
...privilege,
|
||||
userId: membership.actorUserId as string,
|
||||
projectId: membership.scopeProjectId as string,
|
||||
slug: privilege.name
|
||||
}))
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
@@ -207,14 +279,32 @@ export const registerUserAdditionalPrivilegeRouter = async (server: FastifyZodPr
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT]),
|
||||
handler: async (req) => {
|
||||
const privilege = await server.services.projectUserAdditionalPrivilege.getPrivilegeDetailsById({
|
||||
actorId: req.permission.id,
|
||||
actor: req.permission.type,
|
||||
actorOrgId: req.permission.orgId,
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
privilegeId: req.params.privilegeId
|
||||
const data = await server.services.convertor.additionalPrivilegeIdToDoc(req.params.privilegeId);
|
||||
if (!data.privilege.actorUserId)
|
||||
throw new NotFoundError({ message: `Privilege with id ${req.params.privilegeId} not found` });
|
||||
|
||||
const { additionalPrivilege: privilege } = await server.services.additionalPrivilege.getAdditionalPrivilegeById({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
projectId: data.privilege.projectId as string,
|
||||
orgId: req.permission.orgId
|
||||
},
|
||||
selector: {
|
||||
id: req.params.privilegeId,
|
||||
actorId: data.privilege.actorUserId,
|
||||
actorType: ActorType.USER
|
||||
}
|
||||
});
|
||||
return { privilege };
|
||||
|
||||
return {
|
||||
privilege: {
|
||||
...privilege,
|
||||
userId: data.privilege.actorUserId,
|
||||
projectId: data.privilege.projectId as string,
|
||||
slug: privilege.name
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { packRules } from "@casl/ability/extra";
|
||||
import { z } from "zod";
|
||||
|
||||
import { ProjectMembershipRole, ProjectRolesSchema } from "@app/db/schemas";
|
||||
import { AccessScope, ProjectMembershipRole, ProjectRolesSchema } from "@app/db/schemas";
|
||||
import { EventType } from "@app/ee/services/audit-log/audit-log-types";
|
||||
import { checkForInvalidPermissionCombination } from "@app/ee/services/permission/permission-fns";
|
||||
import { ProjectPermissionV2Schema } from "@app/ee/services/permission/project-permission";
|
||||
@@ -11,7 +11,6 @@ import { slugSchema } from "@app/server/lib/schemas";
|
||||
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
||||
import { SanitizedRoleSchema } from "@app/server/routes/sanitizedSchemas";
|
||||
import { AuthMode } from "@app/services/auth/auth-type";
|
||||
import { ProjectRoleServiceIdentifierType } from "@app/services/project-role/project-role-types";
|
||||
|
||||
export const registerDeprecatedProjectRoleRouter = async (server: FastifyZodProvider) => {
|
||||
server.route({
|
||||
@@ -55,13 +54,11 @@ export const registerDeprecatedProjectRoleRouter = async (server: FastifyZodProv
|
||||
handler: async (req) => {
|
||||
const stringifiedPermissions = JSON.stringify(packRules(req.body.permissions));
|
||||
|
||||
const role = await server.services.projectRole.createRole({
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
actorId: req.permission.id,
|
||||
actorOrgId: req.permission.orgId,
|
||||
actor: req.permission.type,
|
||||
filter: {
|
||||
type: ProjectRoleServiceIdentifierType.ID,
|
||||
const role = await server.services.role.createRole({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: req.params.projectId
|
||||
},
|
||||
data: {
|
||||
@@ -73,7 +70,7 @@ export const registerDeprecatedProjectRoleRouter = async (server: FastifyZodProv
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: role.projectId,
|
||||
projectId: req.params.projectId,
|
||||
event: {
|
||||
type: EventType.CREATE_PROJECT_ROLE,
|
||||
metadata: {
|
||||
@@ -86,7 +83,7 @@ export const registerDeprecatedProjectRoleRouter = async (server: FastifyZodProv
|
||||
}
|
||||
});
|
||||
|
||||
return { role };
|
||||
return { role: { ...role, projectId: role.projectId as string } };
|
||||
}
|
||||
});
|
||||
|
||||
@@ -133,12 +130,16 @@ export const registerDeprecatedProjectRoleRouter = async (server: FastifyZodProv
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
handler: async (req) => {
|
||||
const stringifiedPermissions = req.body.permissions ? JSON.stringify(packRules(req.body.permissions)) : undefined;
|
||||
const role = await server.services.projectRole.updateRole({
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
actorId: req.permission.id,
|
||||
actorOrgId: req.permission.orgId,
|
||||
actor: req.permission.type,
|
||||
roleId: req.params.roleId,
|
||||
const role = await server.services.role.updateRole({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: req.params.projectId
|
||||
},
|
||||
selector: {
|
||||
id: req.params.roleId
|
||||
},
|
||||
data: {
|
||||
...req.body,
|
||||
permissions: stringifiedPermissions
|
||||
@@ -148,7 +149,7 @@ export const registerDeprecatedProjectRoleRouter = async (server: FastifyZodProv
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: role.projectId,
|
||||
projectId: role.projectId as string,
|
||||
event: {
|
||||
type: EventType.UPDATE_PROJECT_ROLE,
|
||||
metadata: {
|
||||
@@ -161,7 +162,7 @@ export const registerDeprecatedProjectRoleRouter = async (server: FastifyZodProv
|
||||
}
|
||||
});
|
||||
|
||||
return { role };
|
||||
return { role: { ...role, projectId: role.projectId as string } };
|
||||
}
|
||||
});
|
||||
|
||||
@@ -192,18 +193,22 @@ export const registerDeprecatedProjectRoleRouter = async (server: FastifyZodProv
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
handler: async (req) => {
|
||||
const role = await server.services.projectRole.deleteRole({
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
actorId: req.permission.id,
|
||||
actorOrgId: req.permission.orgId,
|
||||
actor: req.permission.type,
|
||||
roleId: req.params.roleId
|
||||
const role = await server.services.role.deleteRole({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: req.params.projectId
|
||||
},
|
||||
selector: {
|
||||
id: req.params.roleId
|
||||
}
|
||||
});
|
||||
|
||||
await server.services.auditLog.createAuditLog({
|
||||
...req.auditLogInfo,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: role.projectId,
|
||||
projectId: role.projectId as string,
|
||||
event: {
|
||||
type: EventType.DELETE_PROJECT_ROLE,
|
||||
metadata: {
|
||||
@@ -214,7 +219,7 @@ export const registerDeprecatedProjectRoleRouter = async (server: FastifyZodProv
|
||||
}
|
||||
});
|
||||
|
||||
return { role };
|
||||
return { role: { ...role, projectId: role.projectId as string } };
|
||||
}
|
||||
});
|
||||
|
||||
@@ -244,17 +249,16 @@ export const registerDeprecatedProjectRoleRouter = async (server: FastifyZodProv
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
handler: async (req) => {
|
||||
const roles = await server.services.projectRole.listRoles({
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
actorId: req.permission.id,
|
||||
actorOrgId: req.permission.orgId,
|
||||
actor: req.permission.type,
|
||||
filter: {
|
||||
type: ProjectRoleServiceIdentifierType.ID,
|
||||
const { roles } = await server.services.role.listRoles({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: req.params.projectId
|
||||
}
|
||||
},
|
||||
data: {}
|
||||
});
|
||||
return { roles };
|
||||
return { roles: roles.map((el) => ({ ...el, projectId: el.projectId as string })) };
|
||||
}
|
||||
});
|
||||
|
||||
@@ -273,24 +277,25 @@ export const registerDeprecatedProjectRoleRouter = async (server: FastifyZodProv
|
||||
}),
|
||||
response: {
|
||||
200: z.object({
|
||||
role: SanitizedRoleSchema.omit({ version: true })
|
||||
role: SanitizedRoleSchema
|
||||
})
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
handler: async (req) => {
|
||||
const role = await server.services.projectRole.getRoleBySlug({
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
actorId: req.permission.id,
|
||||
actorOrgId: req.permission.orgId,
|
||||
actor: req.permission.type,
|
||||
filter: {
|
||||
type: ProjectRoleServiceIdentifierType.ID,
|
||||
const role = await server.services.role.getRoleBySlug({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
orgId: req.permission.orgId,
|
||||
projectId: req.params.projectId
|
||||
},
|
||||
roleSlug: req.params.roleSlug
|
||||
selector: {
|
||||
slug: req.params.roleSlug
|
||||
}
|
||||
});
|
||||
return { role };
|
||||
|
||||
return { role: { ...role, projectId: role.projectId as string } };
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
import z from "zod";
|
||||
|
||||
import { GatewaysV2Schema } from "@app/db/schemas";
|
||||
import { zodBuffer } from "@app/lib/zod";
|
||||
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
|
||||
import { slugSchema } from "@app/server/lib/schemas";
|
||||
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
||||
@@ -130,4 +131,25 @@ export const registerGatewayV2Router = async (server: FastifyZodProvider) => {
|
||||
return gateway;
|
||||
}
|
||||
});
|
||||
|
||||
server.route({
|
||||
method: "GET",
|
||||
url: "/pam-session-key",
|
||||
config: {
|
||||
rateLimit: readLimit
|
||||
},
|
||||
schema: {
|
||||
response: {
|
||||
200: zodBuffer
|
||||
}
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
handler: async (req) => {
|
||||
const pamSessionKey = await server.services.gatewayV2.getPamSessionKey({
|
||||
orgPermission: req.permission
|
||||
});
|
||||
|
||||
return pamSessionKey;
|
||||
}
|
||||
});
|
||||
};
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import slugify from "@sindresorhus/slugify";
|
||||
import { z } from "zod";
|
||||
|
||||
import { IdentityProjectAdditionalPrivilegeTemporaryMode } from "@app/ee/services/identity-project-additional-privilege-v2/identity-project-additional-privilege-v2-types";
|
||||
import { AccessScope, TemporaryPermissionMode } from "@app/db/schemas";
|
||||
import { checkForInvalidPermissionCombination } from "@app/ee/services/permission/permission-fns";
|
||||
import { ProjectPermissionV2Schema } from "@app/ee/services/permission/project-permission";
|
||||
import { ApiDocsTags, IDENTITY_ADDITIONAL_PRIVILEGE_V2 } from "@app/lib/api-docs";
|
||||
@@ -11,7 +11,7 @@ import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
|
||||
import { slugSchema } from "@app/server/lib/schemas";
|
||||
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
||||
import { SanitizedIdentityPrivilegeSchema } from "@app/server/routes/sanitizedSchema/identitiy-additional-privilege";
|
||||
import { AuthMode } from "@app/services/auth/auth-type";
|
||||
import { ActorType, AuthMode } from "@app/services/auth/auth-type";
|
||||
|
||||
export const registerIdentityProjectAdditionalPrivilegeRouter = async (server: FastifyZodProvider) => {
|
||||
server.route({
|
||||
@@ -43,7 +43,7 @@ export const registerIdentityProjectAdditionalPrivilegeRouter = async (server: F
|
||||
z.object({
|
||||
isTemporary: z.literal(true),
|
||||
temporaryMode: z
|
||||
.nativeEnum(IdentityProjectAdditionalPrivilegeTemporaryMode)
|
||||
.nativeEnum(TemporaryPermissionMode)
|
||||
.describe(IDENTITY_ADDITIONAL_PRIVILEGE_V2.CREATE.temporaryMode),
|
||||
temporaryRange: z
|
||||
.string()
|
||||
@@ -64,18 +64,31 @@ export const registerIdentityProjectAdditionalPrivilegeRouter = async (server: F
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
handler: async (req) => {
|
||||
const privilege = await server.services.identityProjectAdditionalPrivilegeV2.create({
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
actorId: req.permission.id,
|
||||
actorOrgId: req.permission.orgId,
|
||||
actor: req.permission.type,
|
||||
projectId: req.body.projectId,
|
||||
identityId: req.body.identityId,
|
||||
...req.body.type,
|
||||
slug: req.body.slug || slugify(alphaNumericNanoId(8)),
|
||||
permissions: req.body.permissions
|
||||
const { additionalPrivilege: privilege } = await server.services.additionalPrivilege.createAdditionalPrivilege({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
projectId: req.body.projectId,
|
||||
orgId: req.permission.orgId
|
||||
},
|
||||
data: {
|
||||
actorId: req.body.identityId,
|
||||
actorType: ActorType.IDENTITY,
|
||||
...req.body.type,
|
||||
name: req.body.slug || slugify(alphaNumericNanoId(8)),
|
||||
permissions: req.body.permissions
|
||||
}
|
||||
});
|
||||
return { privilege };
|
||||
|
||||
return {
|
||||
privilege: {
|
||||
...privilege,
|
||||
identityId: req.body.identityId,
|
||||
projectMembershipId: req.body.projectId,
|
||||
projectId: req.body.projectId,
|
||||
slug: privilege.name
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
@@ -108,7 +121,7 @@ export const registerIdentityProjectAdditionalPrivilegeRouter = async (server: F
|
||||
z.object({
|
||||
isTemporary: z.literal(true).describe(IDENTITY_ADDITIONAL_PRIVILEGE_V2.UPDATE.isTemporary),
|
||||
temporaryMode: z
|
||||
.nativeEnum(IdentityProjectAdditionalPrivilegeTemporaryMode)
|
||||
.nativeEnum(TemporaryPermissionMode)
|
||||
.describe(IDENTITY_ADDITIONAL_PRIVILEGE_V2.UPDATE.temporaryMode),
|
||||
temporaryRange: z
|
||||
.string()
|
||||
@@ -129,19 +142,36 @@ export const registerIdentityProjectAdditionalPrivilegeRouter = async (server: F
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
handler: async (req) => {
|
||||
const privilege = await server.services.identityProjectAdditionalPrivilegeV2.updateById({
|
||||
actorId: req.permission.id,
|
||||
actor: req.permission.type,
|
||||
actorOrgId: req.permission.orgId,
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
id: req.params.id,
|
||||
const { privilege: privilegeDoc } = await server.services.convertor.additionalPrivilegeIdToDoc(req.params.id);
|
||||
|
||||
const { additionalPrivilege: privilege } = await server.services.additionalPrivilege.updateAdditionalPrivilege({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
projectId: privilegeDoc.projectId as string,
|
||||
orgId: req.permission.orgId
|
||||
},
|
||||
selector: {
|
||||
id: req.params.id,
|
||||
actorId: privilegeDoc.actorIdentityId as string,
|
||||
actorType: ActorType.IDENTITY
|
||||
},
|
||||
data: {
|
||||
...req.body,
|
||||
...req.body.type,
|
||||
permissions: req.body.permissions || undefined
|
||||
}
|
||||
});
|
||||
return { privilege };
|
||||
|
||||
return {
|
||||
privilege: {
|
||||
...privilege,
|
||||
identityId: privilegeDoc.actorIdentityId as string,
|
||||
projectMembershipId: privilegeDoc.projectId as string,
|
||||
projectId: privilegeDoc.projectId as string,
|
||||
slug: privilege.name
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
@@ -171,14 +201,31 @@ export const registerIdentityProjectAdditionalPrivilegeRouter = async (server: F
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
handler: async (req) => {
|
||||
const privilege = await server.services.identityProjectAdditionalPrivilegeV2.deleteById({
|
||||
actorId: req.permission.id,
|
||||
actor: req.permission.type,
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
actorOrgId: req.permission.orgId,
|
||||
id: req.params.id
|
||||
const { privilege: privilegeDoc } = await server.services.convertor.additionalPrivilegeIdToDoc(req.params.id);
|
||||
|
||||
const { additionalPrivilege: privilege } = await server.services.additionalPrivilege.deleteAdditionalPrivilege({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
projectId: privilegeDoc.projectId as string,
|
||||
orgId: req.permission.orgId
|
||||
},
|
||||
selector: {
|
||||
id: req.params.id,
|
||||
actorId: privilegeDoc.actorIdentityId as string,
|
||||
actorType: ActorType.IDENTITY
|
||||
}
|
||||
});
|
||||
return { privilege };
|
||||
|
||||
return {
|
||||
privilege: {
|
||||
...privilege,
|
||||
identityId: privilegeDoc.actorIdentityId as string,
|
||||
projectMembershipId: privilegeDoc.projectId as string,
|
||||
projectId: privilegeDoc.projectId as string,
|
||||
slug: privilege.name
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
@@ -208,14 +255,31 @@ export const registerIdentityProjectAdditionalPrivilegeRouter = async (server: F
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
handler: async (req) => {
|
||||
const privilege = await server.services.identityProjectAdditionalPrivilegeV2.getPrivilegeDetailsById({
|
||||
actorId: req.permission.id,
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
actor: req.permission.type,
|
||||
actorOrgId: req.permission.orgId,
|
||||
id: req.params.id
|
||||
const { privilege: privilegeDoc } = await server.services.convertor.additionalPrivilegeIdToDoc(req.params.id);
|
||||
|
||||
const { additionalPrivilege: privilege } = await server.services.additionalPrivilege.getAdditionalPrivilegeById({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
projectId: privilegeDoc.projectId as string,
|
||||
orgId: req.permission.orgId
|
||||
},
|
||||
selector: {
|
||||
id: req.params.id,
|
||||
actorId: privilegeDoc.actorIdentityId as string,
|
||||
actorType: ActorType.IDENTITY
|
||||
}
|
||||
});
|
||||
return { privilege };
|
||||
|
||||
return {
|
||||
privilege: {
|
||||
...privilege,
|
||||
identityId: privilegeDoc.actorIdentityId as string,
|
||||
projectMembershipId: privilegeDoc.projectId as string,
|
||||
projectId: privilegeDoc.projectId as string,
|
||||
slug: privilege.name
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
@@ -249,15 +313,36 @@ export const registerIdentityProjectAdditionalPrivilegeRouter = async (server: F
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
handler: async (req) => {
|
||||
const privilege = await server.services.identityProjectAdditionalPrivilegeV2.getPrivilegeDetailsBySlug({
|
||||
actorId: req.permission.id,
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
actor: req.permission.type,
|
||||
actorOrgId: req.permission.orgId,
|
||||
slug: req.params.privilegeSlug,
|
||||
...req.query
|
||||
const { id: projectId } = await server.services.convertor.projectSlugToId({
|
||||
slug: req.query.projectSlug,
|
||||
orgId: req.permission.orgId
|
||||
});
|
||||
return { privilege };
|
||||
|
||||
const { additionalPrivilege: privilege } = await server.services.additionalPrivilege.getAdditionalPrivilegeByName(
|
||||
{
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
projectId,
|
||||
orgId: req.permission.orgId
|
||||
},
|
||||
selector: {
|
||||
name: req.params.privilegeSlug,
|
||||
actorId: req.query.identityId,
|
||||
actorType: ActorType.IDENTITY
|
||||
}
|
||||
}
|
||||
);
|
||||
|
||||
return {
|
||||
privilege: {
|
||||
...privilege,
|
||||
identityId: req.query.identityId,
|
||||
projectMembershipId: privilege.projectId as string,
|
||||
projectId,
|
||||
slug: privilege.name
|
||||
}
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
@@ -288,15 +373,27 @@ export const registerIdentityProjectAdditionalPrivilegeRouter = async (server: F
|
||||
},
|
||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||
handler: async (req) => {
|
||||
const privileges = await server.services.identityProjectAdditionalPrivilegeV2.listIdentityProjectPrivileges({
|
||||
actorId: req.permission.id,
|
||||
actor: req.permission.type,
|
||||
actorAuthMethod: req.permission.authMethod,
|
||||
actorOrgId: req.permission.orgId,
|
||||
...req.query
|
||||
const { additionalPrivileges: privileges } = await server.services.additionalPrivilege.listAdditionalPrivileges({
|
||||
permission: req.permission,
|
||||
scopeData: {
|
||||
scope: AccessScope.Project,
|
||||
projectId: req.query.projectId,
|
||||
orgId: req.permission.orgId
|
||||
},
|
||||
selector: {
|
||||
actorId: req.query.identityId,
|
||||
actorType: ActorType.IDENTITY
|
||||
}
|
||||
});
|
||||
|
||||
return {
|
||||
privileges
|
||||
privileges: privileges.map((privilege) => ({
|
||||
...privilege,
|
||||
identityId: req.query.identityId,
|
||||
projectMembershipId: privilege.projectId as string,
|
||||
projectId: req.query.projectId,
|
||||
slug: privilege.name
|
||||
}))
|
||||
};
|
||||
}
|
||||
});
|
||||
|
||||
@@ -3,8 +3,9 @@ import { ForbiddenError } from "@casl/ability";
|
||||
import { ActionProjectType } from "@app/db/schemas";
|
||||
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
|
||||
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
|
||||
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
|
||||
import { BadRequestError, NotFoundError } from "@app/lib/errors";
|
||||
import { groupBy } from "@app/lib/fn";
|
||||
import { TAdditionalPrivilegeDALFactory } from "@app/services/additional-privilege/additional-privilege-dal";
|
||||
import { TProjectDALFactory } from "@app/services/project/project-dal";
|
||||
import { TProjectEnvDALFactory } from "@app/services/project-env/project-env-dal";
|
||||
import { TProjectMembershipDALFactory } from "@app/services/project-membership/project-membership-dal";
|
||||
@@ -14,7 +15,6 @@ import { TAccessApprovalRequestDALFactory } from "../access-approval-request/acc
|
||||
import { TAccessApprovalRequestReviewerDALFactory } from "../access-approval-request/access-approval-request-reviewer-dal";
|
||||
import { ApprovalStatus } from "../access-approval-request/access-approval-request-types";
|
||||
import { TGroupDALFactory } from "../group/group-dal";
|
||||
import { TProjectUserAdditionalPrivilegeDALFactory } from "../project-user-additional-privilege/project-user-additional-privilege-dal";
|
||||
import {
|
||||
TAccessApprovalPolicyApproverDALFactory,
|
||||
TAccessApprovalPolicyBypasserDALFactory
|
||||
@@ -38,11 +38,11 @@ type TAccessApprovalPolicyServiceFactoryDep = {
|
||||
projectEnvDAL: Pick<TProjectEnvDALFactory, "find" | "findOne">;
|
||||
accessApprovalPolicyApproverDAL: TAccessApprovalPolicyApproverDALFactory;
|
||||
accessApprovalPolicyBypasserDAL: TAccessApprovalPolicyBypasserDALFactory;
|
||||
projectMembershipDAL: Pick<TProjectMembershipDALFactory, "find">;
|
||||
projectMembershipDAL: Pick<TProjectMembershipDALFactory, "findProjectMembershipsByUserIds">;
|
||||
groupDAL: TGroupDALFactory;
|
||||
userDAL: Pick<TUserDALFactory, "find">;
|
||||
accessApprovalRequestDAL: Pick<TAccessApprovalRequestDALFactory, "update" | "find" | "resetReviewByPolicyId">;
|
||||
additionalPrivilegeDAL: Pick<TProjectUserAdditionalPrivilegeDALFactory, "delete">;
|
||||
additionalPrivilegeDAL: Pick<TAdditionalPrivilegeDALFactory, "delete">;
|
||||
accessApprovalRequestReviewerDAL: Pick<TAccessApprovalRequestReviewerDALFactory, "update" | "delete">;
|
||||
accessApprovalPolicyEnvironmentDAL: TAccessApprovalPolicyEnvironmentDALFactory;
|
||||
};
|
||||
@@ -83,12 +83,11 @@ export const accessApprovalPolicyServiceFactory = ({
|
||||
return policyId ? policy && policy.id !== policyId : Boolean(policy);
|
||||
};
|
||||
|
||||
const verifyProjectUserMembership = async (userIds: string[], projectId: string) => {
|
||||
const verifyProjectUserMembership = async (userIds: string[], orgId: string, projectId: string) => {
|
||||
if (userIds.length === 0) return;
|
||||
const projectMemberships = await projectMembershipDAL.find({
|
||||
$in: { userId: userIds },
|
||||
projectId
|
||||
});
|
||||
const projectMemberships = (await projectMembershipDAL.findProjectMembershipsByUserIds(orgId, userIds)).filter(
|
||||
(v) => v.projectId === projectId
|
||||
);
|
||||
|
||||
if (projectMemberships.length !== userIds.length) {
|
||||
const projectMemberUserIds = new Set(projectMemberships.map((member) => member.userId));
|
||||
@@ -191,6 +190,7 @@ export const accessApprovalPolicyServiceFactory = ({
|
||||
if (approverUserIds.length > 0) {
|
||||
await verifyProjectUserMembership(
|
||||
approverUserIds.map((au) => au.id),
|
||||
project.orgId,
|
||||
project.id
|
||||
);
|
||||
}
|
||||
@@ -445,7 +445,7 @@ export const accessApprovalPolicyServiceFactory = ({
|
||||
|
||||
// Validate user bypassers
|
||||
if (bypasserUserIds.length > 0) {
|
||||
await verifyProjectUserMembership(bypasserUserIds, accessApprovalPolicy.projectId);
|
||||
await verifyProjectUserMembership(bypasserUserIds, actorOrgId, accessApprovalPolicy.projectId);
|
||||
}
|
||||
|
||||
// Validate group bypassers
|
||||
@@ -513,6 +513,7 @@ export const accessApprovalPolicyServiceFactory = ({
|
||||
if (approverUserIds.length > 0) {
|
||||
await verifyProjectUserMembership(
|
||||
approverUserIds.map((au) => au.id),
|
||||
actorOrgId,
|
||||
accessApprovalPolicy.projectId
|
||||
);
|
||||
}
|
||||
@@ -650,7 +651,7 @@ export const accessApprovalPolicyServiceFactory = ({
|
||||
|
||||
if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
|
||||
|
||||
const { membership } = await permissionService.getProjectPermission({
|
||||
await permissionService.getProjectPermission({
|
||||
actor,
|
||||
actorId,
|
||||
projectId: project.id,
|
||||
@@ -658,9 +659,6 @@ export const accessApprovalPolicyServiceFactory = ({
|
||||
actorOrgId,
|
||||
actionProjectType: ActionProjectType.SecretManager
|
||||
});
|
||||
if (!membership) {
|
||||
throw new ForbiddenRequestError({ message: "You are not a member of this project" });
|
||||
}
|
||||
|
||||
const environment = await projectEnvDAL.findOne({ projectId: project.id, slug: envSlug });
|
||||
if (!environment) throw new NotFoundError({ message: `Environment with slug '${envSlug}' not found` });
|
||||
|
||||
@@ -3,9 +3,10 @@ import { Knex } from "knex";
|
||||
import { TDbClient } from "@app/db";
|
||||
import {
|
||||
AccessApprovalRequestsSchema,
|
||||
AccessScope,
|
||||
TableName,
|
||||
TAccessApprovalRequests,
|
||||
TOrgMemberships,
|
||||
TMemberships,
|
||||
TUserGroupMembership,
|
||||
TUsers
|
||||
} from "@app/db/schemas";
|
||||
@@ -244,11 +245,10 @@ export const accessApprovalRequestDALFactory = (db: TDbClient): TAccessApprovalR
|
||||
const docs = await db
|
||||
.replicaNode()(TableName.AccessApprovalRequest)
|
||||
.whereIn(`${TableName.AccessApprovalRequest}.policyId`, policyIds)
|
||||
|
||||
.leftJoin(
|
||||
TableName.ProjectUserAdditionalPrivilege,
|
||||
TableName.AdditionalPrivilege,
|
||||
`${TableName.AccessApprovalRequest}.privilegeId`,
|
||||
`${TableName.ProjectUserAdditionalPrivilege}.id`
|
||||
`${TableName.AdditionalPrivilege}.id`
|
||||
)
|
||||
.leftJoin(
|
||||
TableName.AccessApprovalPolicy,
|
||||
@@ -276,7 +276,6 @@ export const accessApprovalRequestDALFactory = (db: TDbClient): TAccessApprovalR
|
||||
`${TableName.UserGroupMembership}.groupId`
|
||||
)
|
||||
.leftJoin(TableName.Users, `${TableName.UserGroupMembership}.userId`, `${TableName.Users}.id`)
|
||||
|
||||
.leftJoin(
|
||||
TableName.AccessApprovalPolicyBypasser,
|
||||
`${TableName.AccessApprovalPolicy}.id`,
|
||||
@@ -294,24 +293,24 @@ export const accessApprovalRequestDALFactory = (db: TDbClient): TAccessApprovalR
|
||||
`requestedByUser.id`
|
||||
)
|
||||
|
||||
.leftJoin<TOrgMemberships>(
|
||||
db(TableName.OrgMembership).as("approverOrgMembership"),
|
||||
`${TableName.AccessApprovalPolicyApprover}.approverUserId`,
|
||||
`approverOrgMembership.userId`
|
||||
)
|
||||
|
||||
.leftJoin<TOrgMemberships>(
|
||||
db(TableName.OrgMembership).as("approverGroupOrgMembership"),
|
||||
`${TableName.Users}.id`,
|
||||
`approverGroupOrgMembership.userId`
|
||||
)
|
||||
|
||||
.leftJoin<TOrgMemberships>(
|
||||
db(TableName.OrgMembership).as("reviewerOrgMembership"),
|
||||
`${TableName.AccessApprovalRequestReviewer}.reviewerUserId`,
|
||||
`reviewerOrgMembership.userId`
|
||||
)
|
||||
|
||||
.leftJoin<TMemberships>(db(TableName.Membership).as("approverOrgMembership"), (qb) => {
|
||||
qb.on(
|
||||
`${TableName.AccessApprovalPolicyApprover}.approverUserId`,
|
||||
`approverOrgMembership.actorUserId`
|
||||
).andOn(`approverOrgMembership.scope`, db.raw("?", [AccessScope.Organization]));
|
||||
})
|
||||
.leftJoin<TMemberships>(db(TableName.Membership).as("approverGroupOrgMembership"), (qb) => {
|
||||
qb.on(`${TableName.Users}.id`, `approverGroupOrgMembership.actorUserId`).andOn(
|
||||
`approverGroupOrgMembership.scope`,
|
||||
db.raw("?", [AccessScope.Organization])
|
||||
);
|
||||
})
|
||||
.leftJoin<TMemberships>(db(TableName.Membership).as("reviewerOrgMembership"), (qb) => {
|
||||
qb.on(
|
||||
`${TableName.AccessApprovalRequestReviewer}.reviewerUserId`,
|
||||
`reviewerOrgMembership.actorUserId`
|
||||
).andOn(`reviewerOrgMembership.scope`, db.raw("?", [AccessScope.Organization]));
|
||||
})
|
||||
.leftJoin(TableName.Environment, `${TableName.AccessApprovalPolicy}.envId`, `${TableName.Environment}.id`)
|
||||
|
||||
.select(selectAllTableCols(TableName.AccessApprovalRequest))
|
||||
@@ -360,22 +359,22 @@ export const accessApprovalRequestDALFactory = (db: TDbClient): TAccessApprovalR
|
||||
db.ref("firstName").withSchema("requestedByUser").as("requestedByUserFirstName"),
|
||||
db.ref("lastName").withSchema("requestedByUser").as("requestedByUserLastName"),
|
||||
|
||||
db.ref("userId").withSchema(TableName.ProjectUserAdditionalPrivilege).as("privilegeUserId"),
|
||||
db.ref("projectId").withSchema(TableName.ProjectUserAdditionalPrivilege).as("privilegeMembershipId"),
|
||||
db.ref("actorUserId").withSchema(TableName.AdditionalPrivilege).as("privilegeUserId"),
|
||||
db.ref("projectId").withSchema(TableName.AdditionalPrivilege).as("privilegeMembershipId"),
|
||||
|
||||
db.ref("isTemporary").withSchema(TableName.ProjectUserAdditionalPrivilege).as("privilegeIsTemporary"),
|
||||
db.ref("temporaryMode").withSchema(TableName.ProjectUserAdditionalPrivilege).as("privilegeTemporaryMode"),
|
||||
db.ref("temporaryRange").withSchema(TableName.ProjectUserAdditionalPrivilege).as("privilegeTemporaryRange"),
|
||||
db.ref("isTemporary").withSchema(TableName.AdditionalPrivilege).as("privilegeIsTemporary"),
|
||||
db.ref("temporaryMode").withSchema(TableName.AdditionalPrivilege).as("privilegeTemporaryMode"),
|
||||
db.ref("temporaryRange").withSchema(TableName.AdditionalPrivilege).as("privilegeTemporaryRange"),
|
||||
db
|
||||
.ref("temporaryAccessStartTime")
|
||||
.withSchema(TableName.ProjectUserAdditionalPrivilege)
|
||||
.withSchema(TableName.AdditionalPrivilege)
|
||||
.as("privilegeTemporaryAccessStartTime"),
|
||||
db
|
||||
.ref("temporaryAccessEndTime")
|
||||
.withSchema(TableName.ProjectUserAdditionalPrivilege)
|
||||
.withSchema(TableName.AdditionalPrivilege)
|
||||
.as("privilegeTemporaryAccessEndTime"),
|
||||
|
||||
db.ref("permissions").withSchema(TableName.ProjectUserAdditionalPrivilege).as("privilegePermissions")
|
||||
db.ref("permissions").withSchema(TableName.AdditionalPrivilege).as("privilegePermissions")
|
||||
)
|
||||
.orderBy(`${TableName.AccessApprovalRequest}.createdAt`, "desc");
|
||||
|
||||
@@ -408,7 +407,7 @@ export const accessApprovalRequestDALFactory = (db: TDbClient): TAccessApprovalR
|
||||
privilege: doc.privilegeId
|
||||
? {
|
||||
membershipId: doc.privilegeMembershipId,
|
||||
userId: doc.privilegeUserId,
|
||||
userId: doc.privilegeUserId || "",
|
||||
projectId: doc.projectId,
|
||||
isTemporary: doc.privilegeIsTemporary,
|
||||
temporaryMode: doc.privilegeTemporaryMode,
|
||||
@@ -773,9 +772,9 @@ export const accessApprovalRequestDALFactory = (db: TDbClient): TAccessApprovalR
|
||||
)
|
||||
.leftJoin(TableName.Environment, `${TableName.AccessApprovalPolicy}.envId`, `${TableName.Environment}.id`)
|
||||
.leftJoin(
|
||||
TableName.ProjectUserAdditionalPrivilege,
|
||||
TableName.AdditionalPrivilege,
|
||||
`${TableName.AccessApprovalRequest}.privilegeId`,
|
||||
`${TableName.ProjectUserAdditionalPrivilege}.id`
|
||||
`${TableName.AdditionalPrivilege}.id`
|
||||
)
|
||||
|
||||
.leftJoin(
|
||||
|
||||
+13
-33
@@ -1,7 +1,7 @@
|
||||
import slugify from "@sindresorhus/slugify";
|
||||
import msFn from "ms";
|
||||
|
||||
import { ActionProjectType, ProjectMembershipRole } from "@app/db/schemas";
|
||||
import { ActionProjectType, ProjectMembershipRole, TemporaryPermissionMode } from "@app/db/schemas";
|
||||
import { getConfig } from "@app/lib/config/env";
|
||||
import { BadRequestError, ForbiddenRequestError, NotFoundError } from "@app/lib/errors";
|
||||
import { groupBy } from "@app/lib/fn";
|
||||
@@ -10,12 +10,12 @@ import { alphaNumericNanoId } from "@app/lib/nanoid";
|
||||
import { EnforcementLevel } from "@app/lib/types";
|
||||
import { triggerWorkflowIntegrationNotification } from "@app/lib/workflow-integrations/trigger-notification";
|
||||
import { TriggerFeature } from "@app/lib/workflow-integrations/types";
|
||||
import { TAdditionalPrivilegeDALFactory } from "@app/services/additional-privilege/additional-privilege-dal";
|
||||
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
|
||||
import { TMicrosoftTeamsServiceFactory } from "@app/services/microsoft-teams/microsoft-teams-service";
|
||||
import { TProjectMicrosoftTeamsConfigDALFactory } from "@app/services/microsoft-teams/project-microsoft-teams-config-dal";
|
||||
import { TProjectDALFactory } from "@app/services/project/project-dal";
|
||||
import { TProjectEnvDALFactory } from "@app/services/project-env/project-env-dal";
|
||||
import { TProjectMembershipDALFactory } from "@app/services/project-membership/project-membership-dal";
|
||||
import { TProjectSlackConfigDALFactory } from "@app/services/slack/project-slack-config-dal";
|
||||
import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";
|
||||
import { TUserDALFactory } from "@app/services/user/user-dal";
|
||||
@@ -26,15 +26,13 @@ import { TAccessApprovalPolicyApproverDALFactory } from "../access-approval-poli
|
||||
import { TAccessApprovalPolicyDALFactory } from "../access-approval-policy/access-approval-policy-dal";
|
||||
import { TGroupDALFactory } from "../group/group-dal";
|
||||
import { TPermissionServiceFactory } from "../permission/permission-service-types";
|
||||
import { TProjectUserAdditionalPrivilegeDALFactory } from "../project-user-additional-privilege/project-user-additional-privilege-dal";
|
||||
import { ProjectUserAdditionalPrivilegeTemporaryMode } from "../project-user-additional-privilege/project-user-additional-privilege-types";
|
||||
import { TAccessApprovalRequestDALFactory } from "./access-approval-request-dal";
|
||||
import { verifyRequestedPermissions } from "./access-approval-request-fns";
|
||||
import { TAccessApprovalRequestReviewerDALFactory } from "./access-approval-request-reviewer-dal";
|
||||
import { ApprovalStatus, TAccessApprovalRequestServiceFactory } from "./access-approval-request-types";
|
||||
|
||||
type TSecretApprovalRequestServiceFactoryDep = {
|
||||
additionalPrivilegeDAL: Pick<TProjectUserAdditionalPrivilegeDALFactory, "create" | "findById">;
|
||||
additionalPrivilegeDAL: Pick<TAdditionalPrivilegeDALFactory, "create" | "findById">;
|
||||
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission" | "invalidateProjectPermissionCache">;
|
||||
accessApprovalPolicyApproverDAL: Pick<TAccessApprovalPolicyApproverDALFactory, "find">;
|
||||
projectEnvDAL: Pick<TProjectEnvDALFactory, "findOne">;
|
||||
@@ -59,7 +57,6 @@ type TSecretApprovalRequestServiceFactoryDep = {
|
||||
"create" | "find" | "findOne" | "transaction" | "delete"
|
||||
>;
|
||||
groupDAL: Pick<TGroupDALFactory, "findAllGroupPossibleMembers">;
|
||||
projectMembershipDAL: Pick<TProjectMembershipDALFactory, "findById">;
|
||||
smtpService: Pick<TSmtpService, "sendMail">;
|
||||
userDAL: Pick<
|
||||
TUserDALFactory,
|
||||
@@ -125,7 +122,7 @@ export const accessApprovalRequestServiceFactory = ({
|
||||
if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
|
||||
|
||||
// Anyone can create an access approval request.
|
||||
const { membership } = await permissionService.getProjectPermission({
|
||||
await permissionService.getProjectPermission({
|
||||
actor,
|
||||
actorId,
|
||||
projectId: project.id,
|
||||
@@ -133,9 +130,6 @@ export const accessApprovalRequestServiceFactory = ({
|
||||
actorOrgId,
|
||||
actionProjectType: ActionProjectType.SecretManager
|
||||
});
|
||||
if (!membership) {
|
||||
throw new ForbiddenRequestError({ message: "You are not a member of this project" });
|
||||
}
|
||||
|
||||
const requestedByUser = await userDAL.findById(actorId);
|
||||
if (!requestedByUser) throw new ForbiddenRequestError({ message: "User not found" });
|
||||
@@ -340,7 +334,7 @@ export const accessApprovalRequestServiceFactory = ({
|
||||
});
|
||||
}
|
||||
|
||||
const { membership, hasRole } = await permissionService.getProjectPermission({
|
||||
const { hasRole } = await permissionService.getProjectPermission({
|
||||
actor,
|
||||
actorId,
|
||||
projectId: accessApprovalRequest.projectId,
|
||||
@@ -349,10 +343,6 @@ export const accessApprovalRequestServiceFactory = ({
|
||||
actionProjectType: ActionProjectType.SecretManager
|
||||
});
|
||||
|
||||
if (!membership) {
|
||||
throw new ForbiddenRequestError({ message: "You are not a member of this project" });
|
||||
}
|
||||
|
||||
const isApprover = policy.approvers.find((approver) => approver.userId === actorId);
|
||||
|
||||
if (!hasRole(ProjectMembershipRole.Admin) && !isApprover) {
|
||||
@@ -496,7 +486,7 @@ export const accessApprovalRequestServiceFactory = ({
|
||||
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
|
||||
if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
|
||||
|
||||
const { membership } = await permissionService.getProjectPermission({
|
||||
await permissionService.getProjectPermission({
|
||||
actor,
|
||||
actorId,
|
||||
projectId: project.id,
|
||||
@@ -504,9 +494,6 @@ export const accessApprovalRequestServiceFactory = ({
|
||||
actorOrgId,
|
||||
actionProjectType: ActionProjectType.SecretManager
|
||||
});
|
||||
if (!membership) {
|
||||
throw new ForbiddenRequestError({ message: "You are not a member of this project" });
|
||||
}
|
||||
|
||||
const policies = await accessApprovalPolicyDAL.find({ projectId: project.id });
|
||||
let requests = await accessApprovalRequestDAL.findRequestsWithPrivilegeByPolicyIds(policies.map((p) => p.id));
|
||||
@@ -566,7 +553,7 @@ export const accessApprovalRequestServiceFactory = ({
|
||||
slug: permissionEnvironment
|
||||
});
|
||||
|
||||
const { membership, hasRole } = await permissionService.getProjectPermission({
|
||||
const { hasRole } = await permissionService.getProjectPermission({
|
||||
actor,
|
||||
actorId,
|
||||
projectId: accessApprovalRequest.projectId,
|
||||
@@ -575,10 +562,6 @@ export const accessApprovalRequestServiceFactory = ({
|
||||
actionProjectType: ActionProjectType.SecretManager
|
||||
});
|
||||
|
||||
if (!membership) {
|
||||
throw new ForbiddenRequestError({ message: "You are not a member of this project" });
|
||||
}
|
||||
|
||||
const isSelfApproval = actorId === accessApprovalRequest.requestedByUserId;
|
||||
const isSoftEnforcement = policy.enforcementLevel === EnforcementLevel.Soft;
|
||||
const canBypass = !policy.bypassers.length || policy.bypassers.some((bypasser) => bypasser.userId === actorId);
|
||||
@@ -724,9 +707,9 @@ export const accessApprovalRequestServiceFactory = ({
|
||||
// Permanent access
|
||||
const privilege = await additionalPrivilegeDAL.create(
|
||||
{
|
||||
userId: accessApprovalRequest.requestedByUserId,
|
||||
actorUserId: accessApprovalRequest.requestedByUserId,
|
||||
projectId: accessApprovalRequest.projectId,
|
||||
slug: `requested-privilege-${slugify(alphaNumericNanoId(12))}`,
|
||||
name: `requested-privilege-${slugify(alphaNumericNanoId(12))}`,
|
||||
permissions: JSON.stringify(accessApprovalRequest.permissions)
|
||||
},
|
||||
tx
|
||||
@@ -739,12 +722,12 @@ export const accessApprovalRequestServiceFactory = ({
|
||||
|
||||
const privilege = await additionalPrivilegeDAL.create(
|
||||
{
|
||||
userId: accessApprovalRequest.requestedByUserId,
|
||||
actorUserId: accessApprovalRequest.requestedByUserId,
|
||||
projectId: accessApprovalRequest.projectId,
|
||||
slug: `requested-privilege-${slugify(alphaNumericNanoId(12))}`,
|
||||
name: `requested-privilege-${slugify(alphaNumericNanoId(12))}`,
|
||||
permissions: JSON.stringify(accessApprovalRequest.permissions),
|
||||
isTemporary: true, // Explicitly set to true for the privilege
|
||||
temporaryMode: ProjectUserAdditionalPrivilegeTemporaryMode.Relative,
|
||||
temporaryMode: TemporaryPermissionMode.Relative,
|
||||
temporaryRange: accessApprovalRequest.temporaryRange!,
|
||||
temporaryAccessStartTime: startTime,
|
||||
temporaryAccessEndTime: new Date(startTime.getTime() + relativeTempAllocatedTimeInMs)
|
||||
@@ -830,7 +813,7 @@ export const accessApprovalRequestServiceFactory = ({
|
||||
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
|
||||
if (!project) throw new NotFoundError({ message: `Project with slug '${projectSlug}' not found` });
|
||||
|
||||
const { membership } = await permissionService.getProjectPermission({
|
||||
await permissionService.getProjectPermission({
|
||||
actor,
|
||||
actorId,
|
||||
projectId: project.id,
|
||||
@@ -838,9 +821,6 @@ export const accessApprovalRequestServiceFactory = ({
|
||||
actorOrgId,
|
||||
actionProjectType: ActionProjectType.SecretManager
|
||||
});
|
||||
if (!membership) {
|
||||
throw new ForbiddenRequestError({ message: "You are not a member of this project" });
|
||||
}
|
||||
|
||||
const count = await accessApprovalRequestDAL.getCount({ projectId: project.id, policyId });
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { ForbiddenError } from "@casl/ability";
|
||||
import { AxiosError } from "axios";
|
||||
|
||||
import { TAuditLogs } from "@app/db/schemas";
|
||||
import { OrganizationActionScope, TAuditLogs } from "@app/db/schemas";
|
||||
import {
|
||||
decryptLogStream,
|
||||
decryptLogStreamCredentials,
|
||||
@@ -45,13 +45,14 @@ export const auditLogStreamServiceFactory = ({
|
||||
});
|
||||
}
|
||||
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
actor.type,
|
||||
actor.id,
|
||||
actor.orgId,
|
||||
actor.authMethod,
|
||||
actor.orgId
|
||||
);
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
scope: OrganizationActionScope.Any,
|
||||
actor: actor.type,
|
||||
actorId: actor.id,
|
||||
orgId: actor.orgId,
|
||||
actorAuthMethod: actor.authMethod,
|
||||
actorOrgId: actor.orgId
|
||||
});
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Create, OrgPermissionSubjects.Settings);
|
||||
|
||||
@@ -94,13 +95,14 @@ export const auditLogStreamServiceFactory = ({
|
||||
const logStream = await auditLogStreamDAL.findById(logStreamId);
|
||||
if (!logStream) throw new NotFoundError({ message: `Audit Log Stream with ID '${logStreamId}' not found` });
|
||||
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
actor.type,
|
||||
actor.id,
|
||||
actor.orgId,
|
||||
actor.authMethod,
|
||||
logStream.orgId
|
||||
);
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
scope: OrganizationActionScope.Any,
|
||||
actor: actor.type,
|
||||
actorId: actor.id,
|
||||
orgId: actor.orgId,
|
||||
actorAuthMethod: actor.authMethod,
|
||||
actorOrgId: actor.orgId
|
||||
});
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.Settings);
|
||||
|
||||
@@ -160,13 +162,14 @@ export const auditLogStreamServiceFactory = ({
|
||||
const logStream = await auditLogStreamDAL.findById(logStreamId);
|
||||
if (!logStream) throw new NotFoundError({ message: `Audit Log Stream with ID '${logStreamId}' not found` });
|
||||
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
actor.type,
|
||||
actor.id,
|
||||
actor.orgId,
|
||||
actor.authMethod,
|
||||
logStream.orgId
|
||||
);
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
scope: OrganizationActionScope.Any,
|
||||
actor: actor.type,
|
||||
actorId: actor.id,
|
||||
orgId: actor.orgId,
|
||||
actorAuthMethod: actor.authMethod,
|
||||
actorOrgId: actor.orgId
|
||||
});
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Delete, OrgPermissionSubjects.Settings);
|
||||
|
||||
@@ -185,14 +188,14 @@ export const auditLogStreamServiceFactory = ({
|
||||
const logStream = await auditLogStreamDAL.findById(logStreamId);
|
||||
|
||||
if (!logStream) throw new NotFoundError({ message: `Audit log stream with ID '${logStreamId}' not found` });
|
||||
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
actor.type,
|
||||
actor.id,
|
||||
logStream.orgId,
|
||||
actor.authMethod,
|
||||
actor.orgId
|
||||
);
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
scope: OrganizationActionScope.Any,
|
||||
actor: actor.type,
|
||||
actorId: actor.id,
|
||||
orgId: actor.orgId,
|
||||
actorAuthMethod: actor.authMethod,
|
||||
actorOrgId: actor.orgId
|
||||
});
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.Settings);
|
||||
|
||||
@@ -206,13 +209,14 @@ export const auditLogStreamServiceFactory = ({
|
||||
};
|
||||
|
||||
const list = async (actor: OrgServiceActor) => {
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
actor.type,
|
||||
actor.id,
|
||||
actor.orgId,
|
||||
actor.authMethod,
|
||||
actor.orgId
|
||||
);
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
scope: OrganizationActionScope.Any,
|
||||
actor: actor.type,
|
||||
actorId: actor.id,
|
||||
orgId: actor.orgId,
|
||||
actorAuthMethod: actor.authMethod,
|
||||
actorOrgId: actor.orgId
|
||||
});
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.Settings);
|
||||
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { ForbiddenError } from "@casl/ability";
|
||||
import { requestContext } from "@fastify/request-context";
|
||||
|
||||
import { ActionProjectType } from "@app/db/schemas";
|
||||
import { ActionProjectType, OrganizationActionScope } from "@app/db/schemas";
|
||||
import { getConfig } from "@app/lib/config/env";
|
||||
import { BadRequestError } from "@app/lib/errors";
|
||||
import { ActorType } from "@app/services/auth/auth-type";
|
||||
@@ -47,13 +47,14 @@ export const auditLogServiceFactory = ({
|
||||
);
|
||||
} else {
|
||||
// Organization-wide logs
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
scope: OrganizationActionScope.Any,
|
||||
actor,
|
||||
actorId,
|
||||
actorOrgId,
|
||||
orgId: actorOrgId,
|
||||
actorAuthMethod,
|
||||
actorOrgId
|
||||
);
|
||||
});
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(
|
||||
OrgPermissionAuditLogsActions.Read,
|
||||
|
||||
@@ -173,6 +173,9 @@ export enum EventType {
|
||||
UPDATE_TOKEN_IDENTITY_TOKEN_AUTH = "update-token-identity-token-auth",
|
||||
GET_TOKENS_IDENTITY_TOKEN_AUTH = "get-tokens-identity-token-auth",
|
||||
|
||||
CREATE_SUB_ORGANIZATION = "create-sub-organization",
|
||||
UPDATE_SUB_ORGANIZATION = "update-sub-organization",
|
||||
|
||||
ADD_IDENTITY_TOKEN_AUTH = "add-identity-token-auth",
|
||||
UPDATE_IDENTITY_TOKEN_AUTH = "update-identity-token-auth",
|
||||
GET_IDENTITY_TOKEN_AUTH = "get-identity-token-auth",
|
||||
@@ -352,9 +355,18 @@ export enum EventType {
|
||||
UPDATE_CERTIFICATE_TEMPLATE = "update-certificate-template",
|
||||
DELETE_CERTIFICATE_TEMPLATE = "delete-certificate-template",
|
||||
GET_CERTIFICATE_TEMPLATE = "get-certificate-template",
|
||||
LIST_CERTIFICATE_TEMPLATES = "list-certificate-templates",
|
||||
CREATE_CERTIFICATE_TEMPLATE_EST_CONFIG = "create-certificate-template-est-config",
|
||||
UPDATE_CERTIFICATE_TEMPLATE_EST_CONFIG = "update-certificate-template-est-config",
|
||||
GET_CERTIFICATE_TEMPLATE_EST_CONFIG = "get-certificate-template-est-config",
|
||||
CREATE_CERTIFICATE_PROFILE = "create-certificate-profile",
|
||||
UPDATE_CERTIFICATE_PROFILE = "update-certificate-profile",
|
||||
DELETE_CERTIFICATE_PROFILE = "delete-certificate-profile",
|
||||
GET_CERTIFICATE_PROFILE = "get-certificate-profile",
|
||||
LIST_CERTIFICATE_PROFILES = "list-certificate-profiles",
|
||||
ISSUE_CERTIFICATE_FROM_PROFILE = "issue-certificate-from-profile",
|
||||
SIGN_CERTIFICATE_FROM_PROFILE = "sign-certificate-from-profile",
|
||||
ORDER_CERTIFICATE_FROM_PROFILE = "order-certificate-from-profile",
|
||||
ATTEMPT_CREATE_SLACK_INTEGRATION = "attempt-create-slack-integration",
|
||||
ATTEMPT_REINSTALL_SLACK_INTEGRATION = "attempt-reinstall-slack-integration",
|
||||
GET_PROJECT_SLACK_CONFIG = "get-project-slack-config",
|
||||
@@ -500,7 +512,28 @@ export enum EventType {
|
||||
|
||||
DASHBOARD_LIST_SECRETS = "dashboard-list-secrets",
|
||||
DASHBOARD_GET_SECRET_VALUE = "dashboard-get-secret-value",
|
||||
DASHBOARD_GET_SECRET_VERSION_VALUE = "dashboard-get-secret-version-value"
|
||||
DASHBOARD_GET_SECRET_VERSION_VALUE = "dashboard-get-secret-version-value",
|
||||
|
||||
PAM_SESSION_START = "pam-session-start",
|
||||
PAM_SESSION_LOGS_UPDATE = "pam-session-logs-update",
|
||||
PAM_SESSION_END = "pam-session-end",
|
||||
PAM_SESSION_GET = "pam-session-get",
|
||||
PAM_SESSION_LIST = "pam-session-list",
|
||||
PAM_FOLDER_CREATE = "pam-folder-create",
|
||||
PAM_FOLDER_UPDATE = "pam-folder-update",
|
||||
PAM_FOLDER_DELETE = "pam-folder-delete",
|
||||
PAM_ACCOUNT_LIST = "pam-account-list",
|
||||
PAM_ACCOUNT_ACCESS = "pam-account-access",
|
||||
PAM_ACCOUNT_CREATE = "pam-account-create",
|
||||
PAM_ACCOUNT_UPDATE = "pam-account-update",
|
||||
PAM_ACCOUNT_DELETE = "pam-account-delete",
|
||||
PAM_ACCOUNT_CREDENTIAL_ROTATION = "pam-account-credential-rotation",
|
||||
PAM_ACCOUNT_CREDENTIAL_ROTATION_FAILED = "pam-account-credential-rotation-failed",
|
||||
PAM_RESOURCE_LIST = "pam-resource-list",
|
||||
PAM_RESOURCE_GET = "pam-resource-get",
|
||||
PAM_RESOURCE_CREATE = "pam-resource-create",
|
||||
PAM_RESOURCE_UPDATE = "pam-resource-update",
|
||||
PAM_RESOURCE_DELETE = "pam-resource-delete"
|
||||
}
|
||||
|
||||
export const filterableSecretEvents: EventType[] = [
|
||||
@@ -588,6 +621,22 @@ interface GetSecretsEvent {
|
||||
};
|
||||
}
|
||||
|
||||
interface CreateSubOrganizationEvent {
|
||||
type: EventType.CREATE_SUB_ORGANIZATION;
|
||||
metadata: {
|
||||
name: string;
|
||||
organizationId: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface UpdateSubOrganizationEvent {
|
||||
type: EventType.UPDATE_SUB_ORGANIZATION;
|
||||
metadata: {
|
||||
name: string;
|
||||
organizationId: string;
|
||||
};
|
||||
}
|
||||
|
||||
type TSecretMetadata = { key: string; value: string }[];
|
||||
|
||||
interface GetSecretEvent {
|
||||
@@ -2493,46 +2542,6 @@ interface LoadProjectKmsBackupEvent {
|
||||
metadata: Record<string, string>; // no metadata yet
|
||||
}
|
||||
|
||||
interface CreateCertificateTemplate {
|
||||
type: EventType.CREATE_CERTIFICATE_TEMPLATE;
|
||||
metadata: {
|
||||
certificateTemplateId: string;
|
||||
caId: string;
|
||||
pkiCollectionId?: string;
|
||||
name: string;
|
||||
commonName: string;
|
||||
subjectAlternativeName: string;
|
||||
ttl: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface GetCertificateTemplate {
|
||||
type: EventType.GET_CERTIFICATE_TEMPLATE;
|
||||
metadata: {
|
||||
certificateTemplateId: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface UpdateCertificateTemplate {
|
||||
type: EventType.UPDATE_CERTIFICATE_TEMPLATE;
|
||||
metadata: {
|
||||
certificateTemplateId: string;
|
||||
caId: string;
|
||||
pkiCollectionId?: string;
|
||||
name: string;
|
||||
commonName: string;
|
||||
subjectAlternativeName: string;
|
||||
ttl: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface DeleteCertificateTemplate {
|
||||
type: EventType.DELETE_CERTIFICATE_TEMPLATE;
|
||||
metadata: {
|
||||
certificateTemplateId: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface OrgAdminAccessProjectEvent {
|
||||
type: EventType.ORG_ADMIN_ACCESS_PROJECT;
|
||||
metadata: {
|
||||
@@ -2579,6 +2588,138 @@ interface GetCertificateTemplateEstConfig {
|
||||
};
|
||||
}
|
||||
|
||||
interface CreateCertificateTemplate {
|
||||
type: EventType.CREATE_CERTIFICATE_TEMPLATE;
|
||||
metadata:
|
||||
| {
|
||||
certificateTemplateId: string;
|
||||
name: string;
|
||||
projectId: string;
|
||||
}
|
||||
| {
|
||||
certificateTemplateId: string;
|
||||
caId: string;
|
||||
pkiCollectionId: string;
|
||||
name: string;
|
||||
commonName: string;
|
||||
subjectAlternativeName: string;
|
||||
ttl: string;
|
||||
projectId: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface UpdateCertificateTemplate {
|
||||
type: EventType.UPDATE_CERTIFICATE_TEMPLATE;
|
||||
metadata:
|
||||
| {
|
||||
certificateTemplateId: string;
|
||||
name: string;
|
||||
}
|
||||
| {
|
||||
certificateTemplateId: string;
|
||||
caId: string;
|
||||
pkiCollectionId: string;
|
||||
name: string;
|
||||
commonName: string;
|
||||
subjectAlternativeName: string;
|
||||
ttl: string;
|
||||
projectId: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface DeleteCertificateTemplate {
|
||||
type: EventType.DELETE_CERTIFICATE_TEMPLATE;
|
||||
metadata: {
|
||||
certificateTemplateId: string;
|
||||
name: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface GetCertificateTemplate {
|
||||
type: EventType.GET_CERTIFICATE_TEMPLATE;
|
||||
metadata: {
|
||||
certificateTemplateId: string;
|
||||
name: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface ListCertificateTemplates {
|
||||
type: EventType.LIST_CERTIFICATE_TEMPLATES;
|
||||
metadata: {
|
||||
projectId: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface CreateCertificateProfile {
|
||||
type: EventType.CREATE_CERTIFICATE_PROFILE;
|
||||
metadata: {
|
||||
certificateProfileId: string;
|
||||
name: string;
|
||||
projectId: string;
|
||||
enrollmentType: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface UpdateCertificateProfile {
|
||||
type: EventType.UPDATE_CERTIFICATE_PROFILE;
|
||||
metadata: {
|
||||
certificateProfileId: string;
|
||||
name: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface DeleteCertificateProfile {
|
||||
type: EventType.DELETE_CERTIFICATE_PROFILE;
|
||||
metadata: {
|
||||
certificateProfileId: string;
|
||||
name: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface GetCertificateProfile {
|
||||
type: EventType.GET_CERTIFICATE_PROFILE;
|
||||
metadata: {
|
||||
certificateProfileId: string;
|
||||
name: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface ListCertificateProfiles {
|
||||
type: EventType.LIST_CERTIFICATE_PROFILES;
|
||||
metadata: {
|
||||
projectId: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface IssueCertificateFromProfile {
|
||||
type: EventType.ISSUE_CERTIFICATE_FROM_PROFILE;
|
||||
metadata: {
|
||||
certificateProfileId: string;
|
||||
certificateId: string;
|
||||
commonName: string;
|
||||
profileName: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface SignCertificateFromProfile {
|
||||
type: EventType.SIGN_CERTIFICATE_FROM_PROFILE;
|
||||
metadata: {
|
||||
certificateProfileId: string;
|
||||
certificateId: string;
|
||||
profileName: string;
|
||||
commonName: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface OrderCertificateFromProfile {
|
||||
type: EventType.ORDER_CERTIFICATE_FROM_PROFILE;
|
||||
metadata: {
|
||||
certificateProfileId: string;
|
||||
orderId: string;
|
||||
profileName: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface AttemptCreateSlackIntegration {
|
||||
type: EventType.ATTEMPT_CREATE_SLACK_INTEGRATION;
|
||||
metadata: {
|
||||
@@ -3687,7 +3828,190 @@ interface OrgRoleDeleteEvent {
|
||||
};
|
||||
}
|
||||
|
||||
interface PamSessionStartEvent {
|
||||
type: EventType.PAM_SESSION_START;
|
||||
metadata: {
|
||||
sessionId: string;
|
||||
accountName: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface PamSessionLogsUpdateEvent {
|
||||
type: EventType.PAM_SESSION_LOGS_UPDATE;
|
||||
metadata: {
|
||||
sessionId: string;
|
||||
accountName: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface PamSessionEndEvent {
|
||||
type: EventType.PAM_SESSION_END;
|
||||
metadata: {
|
||||
sessionId: string;
|
||||
accountName: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface PamSessionGetEvent {
|
||||
type: EventType.PAM_SESSION_GET;
|
||||
metadata: {
|
||||
sessionId: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface PamSessionListEvent {
|
||||
type: EventType.PAM_SESSION_LIST;
|
||||
metadata: {
|
||||
count: number;
|
||||
};
|
||||
}
|
||||
|
||||
interface PamFolderCreateEvent {
|
||||
type: EventType.PAM_FOLDER_CREATE;
|
||||
metadata: {
|
||||
parentId?: string | null;
|
||||
name: string;
|
||||
description?: string | null;
|
||||
};
|
||||
}
|
||||
|
||||
interface PamFolderUpdateEvent {
|
||||
type: EventType.PAM_FOLDER_UPDATE;
|
||||
metadata: {
|
||||
folderId: string;
|
||||
name?: string;
|
||||
description?: string | null;
|
||||
};
|
||||
}
|
||||
|
||||
interface PamFolderDeleteEvent {
|
||||
type: EventType.PAM_FOLDER_DELETE;
|
||||
metadata: {
|
||||
folderId: string;
|
||||
folderName: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface PamAccountListEvent {
|
||||
type: EventType.PAM_ACCOUNT_LIST;
|
||||
metadata: {
|
||||
accountCount: number;
|
||||
folderCount: number;
|
||||
};
|
||||
}
|
||||
|
||||
interface PamAccountAccessEvent {
|
||||
type: EventType.PAM_ACCOUNT_ACCESS;
|
||||
metadata: {
|
||||
accountId: string;
|
||||
accountName: string;
|
||||
duration?: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface PamAccountCreateEvent {
|
||||
type: EventType.PAM_ACCOUNT_CREATE;
|
||||
metadata: {
|
||||
resourceId: string;
|
||||
resourceType: string;
|
||||
folderId?: string | null;
|
||||
name: string;
|
||||
description?: string | null;
|
||||
rotationEnabled: boolean;
|
||||
rotationIntervalSeconds?: number | null;
|
||||
};
|
||||
}
|
||||
|
||||
interface PamAccountUpdateEvent {
|
||||
type: EventType.PAM_ACCOUNT_UPDATE;
|
||||
metadata: {
|
||||
accountId: string;
|
||||
resourceId: string;
|
||||
resourceType: string;
|
||||
name?: string;
|
||||
description?: string | null;
|
||||
rotationEnabled?: boolean;
|
||||
rotationIntervalSeconds?: number | null;
|
||||
};
|
||||
}
|
||||
|
||||
interface PamAccountDeleteEvent {
|
||||
type: EventType.PAM_ACCOUNT_DELETE;
|
||||
metadata: {
|
||||
accountName: string;
|
||||
accountId: string;
|
||||
resourceId: string;
|
||||
resourceType: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface PamAccountCredentialRotationEvent {
|
||||
type: EventType.PAM_ACCOUNT_CREDENTIAL_ROTATION;
|
||||
metadata: {
|
||||
accountName: string;
|
||||
accountId: string;
|
||||
resourceId: string;
|
||||
resourceType: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface PamAccountCredentialRotationFailedEvent {
|
||||
type: EventType.PAM_ACCOUNT_CREDENTIAL_ROTATION_FAILED;
|
||||
metadata: {
|
||||
accountName: string;
|
||||
accountId: string;
|
||||
resourceId: string;
|
||||
resourceType: string;
|
||||
errorMessage: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface PamResourceListEvent {
|
||||
type: EventType.PAM_RESOURCE_LIST;
|
||||
metadata: {
|
||||
count: number;
|
||||
};
|
||||
}
|
||||
|
||||
interface PamResourceGetEvent {
|
||||
type: EventType.PAM_RESOURCE_GET;
|
||||
metadata: {
|
||||
resourceId: string;
|
||||
resourceType: string;
|
||||
name: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface PamResourceCreateEvent {
|
||||
type: EventType.PAM_RESOURCE_CREATE;
|
||||
metadata: {
|
||||
resourceType: string;
|
||||
gatewayId: string;
|
||||
name: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface PamResourceUpdateEvent {
|
||||
type: EventType.PAM_RESOURCE_UPDATE;
|
||||
metadata: {
|
||||
resourceId: string;
|
||||
resourceType: string;
|
||||
gatewayId?: string;
|
||||
name?: string;
|
||||
};
|
||||
}
|
||||
|
||||
interface PamResourceDeleteEvent {
|
||||
type: EventType.PAM_RESOURCE_DELETE;
|
||||
metadata: {
|
||||
resourceId: string;
|
||||
resourceType: string;
|
||||
};
|
||||
}
|
||||
|
||||
export type Event =
|
||||
| CreateSubOrganizationEvent
|
||||
| UpdateSubOrganizationEvent
|
||||
| GetSecretsEvent
|
||||
| GetSecretEvent
|
||||
| CreateSecretEvent
|
||||
@@ -3876,13 +4200,22 @@ export type Event =
|
||||
| LoadProjectKmsBackupEvent
|
||||
| OrgAdminAccessProjectEvent
|
||||
| OrgAdminBypassSSOEvent
|
||||
| CreateCertificateTemplate
|
||||
| UpdateCertificateTemplate
|
||||
| GetCertificateTemplate
|
||||
| DeleteCertificateTemplate
|
||||
| CreateCertificateTemplateEstConfig
|
||||
| UpdateCertificateTemplateEstConfig
|
||||
| GetCertificateTemplateEstConfig
|
||||
| CreateCertificateTemplate
|
||||
| UpdateCertificateTemplate
|
||||
| DeleteCertificateTemplate
|
||||
| GetCertificateTemplate
|
||||
| ListCertificateTemplates
|
||||
| CreateCertificateProfile
|
||||
| UpdateCertificateProfile
|
||||
| DeleteCertificateProfile
|
||||
| GetCertificateProfile
|
||||
| ListCertificateProfiles
|
||||
| IssueCertificateFromProfile
|
||||
| SignCertificateFromProfile
|
||||
| OrderCertificateFromProfile
|
||||
| GetAzureAdCsTemplatesEvent
|
||||
| AttemptCreateSlackIntegration
|
||||
| AttemptReinstallSlackIntegration
|
||||
@@ -4020,4 +4353,24 @@ export type Event =
|
||||
| ProjectRoleDeleteEvent
|
||||
| OrgRoleCreateEvent
|
||||
| OrgRoleUpdateEvent
|
||||
| OrgRoleDeleteEvent;
|
||||
| OrgRoleDeleteEvent
|
||||
| PamSessionStartEvent
|
||||
| PamSessionLogsUpdateEvent
|
||||
| PamSessionEndEvent
|
||||
| PamSessionGetEvent
|
||||
| PamSessionListEvent
|
||||
| PamFolderCreateEvent
|
||||
| PamFolderUpdateEvent
|
||||
| PamFolderDeleteEvent
|
||||
| PamAccountListEvent
|
||||
| PamAccountAccessEvent
|
||||
| PamAccountCreateEvent
|
||||
| PamAccountUpdateEvent
|
||||
| PamAccountDeleteEvent
|
||||
| PamAccountCredentialRotationEvent
|
||||
| PamAccountCredentialRotationFailedEvent
|
||||
| PamResourceListEvent
|
||||
| PamResourceGetEvent
|
||||
| PamResourceCreateEvent
|
||||
| PamResourceUpdateEvent
|
||||
| PamResourceDeleteEvent;
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { ForbiddenError, subject } from "@casl/ability";
|
||||
|
||||
import { ActionProjectType } from "@app/db/schemas";
|
||||
import { ActionProjectType, OrganizationActionScope } from "@app/db/schemas";
|
||||
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
|
||||
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service-types";
|
||||
import {
|
||||
@@ -134,13 +134,14 @@ export const dynamicSecretServiceFactory = ({
|
||||
isGatewayV1 = false;
|
||||
}
|
||||
|
||||
const { permission: orgPermission } = await permissionService.getOrgPermission(
|
||||
const { permission: orgPermission } = await permissionService.getOrgPermission({
|
||||
scope: OrganizationActionScope.Any,
|
||||
actor,
|
||||
actorId,
|
||||
gateway?.orgId ?? gatewayv2?.orgId,
|
||||
orgId: gateway?.orgId || gatewayv2?.orgId,
|
||||
actorAuthMethod,
|
||||
actorOrgId
|
||||
);
|
||||
});
|
||||
|
||||
ForbiddenError.from(orgPermission).throwUnlessCan(
|
||||
OrgPermissionGatewayActions.AttachGateways,
|
||||
@@ -297,13 +298,14 @@ export const dynamicSecretServiceFactory = ({
|
||||
isGatewayV1 = false;
|
||||
}
|
||||
|
||||
const { permission: orgPermission } = await permissionService.getOrgPermission(
|
||||
const { permission: orgPermission } = await permissionService.getOrgPermission({
|
||||
scope: OrganizationActionScope.Any,
|
||||
actor,
|
||||
actorId,
|
||||
actorOrgId,
|
||||
orgId: gateway?.orgId || gatewayv2?.orgId,
|
||||
actorAuthMethod,
|
||||
actorOrgId
|
||||
);
|
||||
});
|
||||
|
||||
ForbiddenError.from(orgPermission).throwUnlessCan(
|
||||
OrgPermissionGatewayActions.AttachGateways,
|
||||
|
||||
@@ -34,6 +34,7 @@ export const ElasticSearchProvider = (): TDynamicProviderFns => {
|
||||
|
||||
const $getClient = async (providerInputs: z.infer<typeof DynamicSecretElasticSearchSchema>) => {
|
||||
const connection = new ElasticSearchClient({
|
||||
requestTimeout: 30_000,
|
||||
node: {
|
||||
url: new URL(`${providerInputs.host}:${providerInputs.port}`),
|
||||
...(providerInputs.ca && {
|
||||
|
||||
@@ -3,6 +3,7 @@ import { STSServiceException } from "@aws-sdk/client-sts";
|
||||
import { ForbiddenError } from "@casl/ability";
|
||||
import slugify from "@sindresorhus/slugify";
|
||||
|
||||
import { OrganizationActionScope } from "@app/db/schemas";
|
||||
import { BadRequestError, InternalServerError, NotFoundError } from "@app/lib/errors";
|
||||
import { alphaNumericNanoId } from "@app/lib/nanoid";
|
||||
import { TKmsKeyDALFactory } from "@app/services/kms/kms-key-dal";
|
||||
@@ -51,13 +52,14 @@ export const externalKmsServiceFactory = ({
|
||||
actorOrgId,
|
||||
actorAuthMethod
|
||||
}: TCreateExternalKmsDTO) => {
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
scope: OrganizationActionScope.Any,
|
||||
actor,
|
||||
actorId,
|
||||
actorOrgId,
|
||||
orgId: actorOrgId,
|
||||
actorAuthMethod,
|
||||
actorOrgId
|
||||
);
|
||||
});
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Create, OrgPermissionSubjects.Kms);
|
||||
const plan = await licenseService.getPlan(actorOrgId);
|
||||
@@ -154,13 +156,14 @@ export const externalKmsServiceFactory = ({
|
||||
actorAuthMethod
|
||||
}: TUpdateExternalKmsDTO) => {
|
||||
const kmsDoc = await kmsDAL.findById(kmsId);
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
scope: OrganizationActionScope.Any,
|
||||
actor,
|
||||
actorId,
|
||||
kmsDoc.orgId,
|
||||
orgId: kmsDoc.orgId,
|
||||
actorAuthMethod,
|
||||
actorOrgId
|
||||
);
|
||||
});
|
||||
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.Kms);
|
||||
|
||||
const plan = await licenseService.getPlan(kmsDoc.orgId);
|
||||
@@ -257,13 +260,14 @@ export const externalKmsServiceFactory = ({
|
||||
|
||||
const deleteById = async ({ actor, id: kmsId, actorId, actorOrgId, actorAuthMethod }: TDeleteExternalKmsDTO) => {
|
||||
const kmsDoc = await kmsDAL.findById(kmsId);
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
scope: OrganizationActionScope.Any,
|
||||
actor,
|
||||
actorId,
|
||||
kmsDoc.orgId,
|
||||
orgId: kmsDoc.orgId,
|
||||
actorAuthMethod,
|
||||
actorOrgId
|
||||
);
|
||||
});
|
||||
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Delete, OrgPermissionSubjects.Kms);
|
||||
|
||||
const externalKmsDoc = await externalKmsDAL.findOne({ kmsKeyId: kmsDoc.id });
|
||||
@@ -278,13 +282,14 @@ export const externalKmsServiceFactory = ({
|
||||
};
|
||||
|
||||
const list = async ({ actor, actorId, actorOrgId, actorAuthMethod }: TListExternalKmsDTO) => {
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
scope: OrganizationActionScope.Any,
|
||||
actor,
|
||||
actorId,
|
||||
actorOrgId,
|
||||
orgId: actorOrgId,
|
||||
actorAuthMethod,
|
||||
actorOrgId
|
||||
);
|
||||
});
|
||||
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.Kms);
|
||||
|
||||
const externalKmsDocs = await externalKmsDAL.find({ orgId: actorOrgId });
|
||||
@@ -294,13 +299,14 @@ export const externalKmsServiceFactory = ({
|
||||
|
||||
const findById = async ({ actor, actorId, actorOrgId, actorAuthMethod, id: kmsId }: TGetExternalKmsByIdDTO) => {
|
||||
const kmsDoc = await kmsDAL.findById(kmsId);
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
scope: OrganizationActionScope.Any,
|
||||
actor,
|
||||
actorId,
|
||||
kmsDoc.orgId,
|
||||
orgId: kmsDoc.orgId,
|
||||
actorAuthMethod,
|
||||
actorOrgId
|
||||
);
|
||||
});
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.Kms);
|
||||
|
||||
@@ -342,13 +348,14 @@ export const externalKmsServiceFactory = ({
|
||||
name: kmsName
|
||||
}: TGetExternalKmsBySlugDTO) => {
|
||||
const kmsDoc = await kmsDAL.findOne({ name: kmsName, orgId: actorOrgId });
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
scope: OrganizationActionScope.Any,
|
||||
actor,
|
||||
actorId,
|
||||
kmsDoc.orgId,
|
||||
orgId: kmsDoc.orgId,
|
||||
actorAuthMethod,
|
||||
actorOrgId
|
||||
);
|
||||
});
|
||||
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.Kms);
|
||||
|
||||
const externalKmsDoc = await externalKmsDAL.findOne({ kmsKeyId: kmsDoc.id });
|
||||
|
||||
@@ -1,2 +1,3 @@
|
||||
export const GATEWAY_ROUTING_INFO_OID = "1.3.6.1.4.1.12345.100.1";
|
||||
export const GATEWAY_ACTOR_OID = "1.3.6.1.4.1.12345.100.2";
|
||||
export const PAM_INFO_OID = "1.3.6.1.4.1.12345.100.3";
|
||||
|
||||
@@ -10,20 +10,34 @@ export type TGatewayV2DALFactory = ReturnType<typeof gatewayV2DalFactory>;
|
||||
export const gatewayV2DalFactory = (db: TDbClient) => {
|
||||
const orm = ormify(db, TableName.GatewayV2);
|
||||
|
||||
const find = async (filter: TFindFilter<TGatewaysV2>, { offset, limit, sort, tx }: TFindOpt<TGatewaysV2> = {}) => {
|
||||
const find = async (
|
||||
filter: TFindFilter<TGatewaysV2> & { isHeartbeatStale?: boolean },
|
||||
{ offset, limit, sort, tx }: TFindOpt<TGatewaysV2> = {}
|
||||
) => {
|
||||
try {
|
||||
const { isHeartbeatStale, ...regularFilter } = filter;
|
||||
|
||||
const query = (tx || db.replicaNode())(TableName.GatewayV2)
|
||||
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
||||
.where(buildFindFilter(filter, TableName.GatewayV2))
|
||||
.where(buildFindFilter(regularFilter, TableName.GatewayV2))
|
||||
.join(TableName.Identity, `${TableName.Identity}.id`, `${TableName.GatewayV2}.identityId`)
|
||||
.join(
|
||||
TableName.IdentityOrgMembership,
|
||||
`${TableName.IdentityOrgMembership}.identityId`,
|
||||
`${TableName.GatewayV2}.identityId`
|
||||
)
|
||||
.select(selectAllTableCols(TableName.GatewayV2))
|
||||
.select(db.ref("name").withSchema(TableName.Identity).as("identityName"));
|
||||
|
||||
if (isHeartbeatStale) {
|
||||
const oneHourAgo = new Date(Date.now() - 60 * 60 * 1000);
|
||||
void query.where(`${TableName.GatewayV2}.heartbeat`, "<", oneHourAgo);
|
||||
void query.where((v) => {
|
||||
void v
|
||||
.whereNull(`${TableName.GatewayV2}.healthAlertedAt`)
|
||||
.orWhere(
|
||||
`${TableName.GatewayV2}.healthAlertedAt`,
|
||||
"<",
|
||||
db.ref("heartbeat").withSchema(TableName.GatewayV2)
|
||||
);
|
||||
});
|
||||
}
|
||||
|
||||
if (limit) void query.limit(limit);
|
||||
if (offset) void query.offset(offset);
|
||||
if (sort) {
|
||||
|
||||
@@ -3,13 +3,15 @@ import net from "node:net";
|
||||
import { ForbiddenError } from "@casl/ability";
|
||||
import * as x509 from "@peculiar/x509";
|
||||
|
||||
import { TRelays } from "@app/db/schemas";
|
||||
import { OrganizationActionScope, OrgMembershipRole, TRelays } from "@app/db/schemas";
|
||||
import { PgSqlLock } from "@app/keystore/keystore";
|
||||
import { crypto } from "@app/lib/crypto";
|
||||
import { DatabaseErrorCode } from "@app/lib/error-codes";
|
||||
import { BadRequestError, DatabaseError, NotFoundError } from "@app/lib/errors";
|
||||
import { groupBy } from "@app/lib/fn";
|
||||
import { GatewayProxyProtocol } from "@app/lib/gateway/types";
|
||||
import { withGatewayV2Proxy } from "@app/lib/gateway-v2/gateway-v2";
|
||||
import { logger } from "@app/lib/logger";
|
||||
import { OrgServiceActor } from "@app/lib/types";
|
||||
import { ActorAuthMethod, ActorType } from "@app/services/auth/auth-type";
|
||||
import { constructPemChainFromCerts } from "@app/services/certificate/certificate-fns";
|
||||
@@ -20,13 +22,18 @@ import {
|
||||
} from "@app/services/certificate-authority/certificate-authority-fns";
|
||||
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
|
||||
import { KmsDataKey } from "@app/services/kms/kms-types";
|
||||
import { TNotificationServiceFactory } from "@app/services/notification/notification-service";
|
||||
import { NotificationType } from "@app/services/notification/notification-types";
|
||||
import { TOrgDALFactory } from "@app/services/org/org-dal";
|
||||
import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";
|
||||
|
||||
import { TLicenseServiceFactory } from "../license/license-service";
|
||||
import { PamResource } from "../pam-resource/pam-resource-enums";
|
||||
import { OrgPermissionGatewayActions, OrgPermissionSubjects } from "../permission/org-permission";
|
||||
import { TPermissionServiceFactory } from "../permission/permission-service-types";
|
||||
import { TRelayDALFactory } from "../relay/relay-dal";
|
||||
import { TRelayServiceFactory } from "../relay/relay-service";
|
||||
import { GATEWAY_ACTOR_OID, GATEWAY_ROUTING_INFO_OID } from "./gateway-v2-constants";
|
||||
import { GATEWAY_ACTOR_OID, GATEWAY_ROUTING_INFO_OID, PAM_INFO_OID } from "./gateway-v2-constants";
|
||||
import { TGatewayV2DALFactory } from "./gateway-v2-dal";
|
||||
import { TOrgGatewayConfigV2DALFactory } from "./org-gateway-config-v2-dal";
|
||||
|
||||
@@ -38,6 +45,9 @@ type TGatewayV2ServiceFactoryDep = {
|
||||
gatewayV2DAL: TGatewayV2DALFactory;
|
||||
relayDAL: TRelayDALFactory;
|
||||
permissionService: TPermissionServiceFactory;
|
||||
orgDAL: Pick<TOrgDALFactory, "findOrgMembersByRole">;
|
||||
notificationService: Pick<TNotificationServiceFactory, "createUserNotifications">;
|
||||
smtpService: Pick<TSmtpService, "sendMail">;
|
||||
};
|
||||
|
||||
export type TGatewayV2ServiceFactory = ReturnType<typeof gatewayV2ServiceFactory>;
|
||||
@@ -49,7 +59,10 @@ export const gatewayV2ServiceFactory = ({
|
||||
relayService,
|
||||
gatewayV2DAL,
|
||||
relayDAL,
|
||||
permissionService
|
||||
permissionService,
|
||||
orgDAL,
|
||||
notificationService,
|
||||
smtpService
|
||||
}: TGatewayV2ServiceFactoryDep) => {
|
||||
const $validateIdentityAccessToGateway = async (orgId: string, actorId: string, actorAuthMethod: ActorAuthMethod) => {
|
||||
const orgLicensePlan = await licenseService.getPlan(orgId);
|
||||
@@ -60,13 +73,14 @@ export const gatewayV2ServiceFactory = ({
|
||||
});
|
||||
}
|
||||
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
ActorType.IDENTITY,
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
scope: OrganizationActionScope.Any,
|
||||
actor: ActorType.IDENTITY,
|
||||
actorId,
|
||||
orgId,
|
||||
actorAuthMethod,
|
||||
orgId
|
||||
);
|
||||
actorOrgId: orgId
|
||||
});
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(
|
||||
OrgPermissionGatewayActions.CreateGateways,
|
||||
@@ -245,13 +259,14 @@ export const gatewayV2ServiceFactory = ({
|
||||
};
|
||||
|
||||
const listGateways = async ({ orgPermission }: { orgPermission: OrgServiceActor }) => {
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
orgPermission.type,
|
||||
orgPermission.id,
|
||||
orgPermission.orgId,
|
||||
orgPermission.authMethod,
|
||||
orgPermission.orgId
|
||||
);
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
actor: orgPermission.type,
|
||||
actorId: orgPermission.id,
|
||||
orgId: orgPermission.orgId,
|
||||
actorAuthMethod: orgPermission.authMethod,
|
||||
actorOrgId: orgPermission.orgId,
|
||||
scope: OrganizationActionScope.Any
|
||||
});
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(
|
||||
OrgPermissionGatewayActions.ListGateways,
|
||||
@@ -414,6 +429,176 @@ export const gatewayV2ServiceFactory = ({
|
||||
};
|
||||
};
|
||||
|
||||
const getPAMConnectionDetails = async ({
|
||||
gatewayId,
|
||||
sessionId,
|
||||
duration,
|
||||
resourceType,
|
||||
host,
|
||||
port,
|
||||
actorMetadata
|
||||
}: {
|
||||
gatewayId: string;
|
||||
sessionId: string;
|
||||
resourceType: PamResource;
|
||||
duration?: number;
|
||||
host: string;
|
||||
port: number;
|
||||
actorMetadata: { id: string; type: ActorType; name: string };
|
||||
}) => {
|
||||
const gateway = await gatewayV2DAL.findById(gatewayId);
|
||||
if (!gateway) {
|
||||
return;
|
||||
}
|
||||
|
||||
const orgGatewayConfig = await orgGatewayConfigV2DAL.findOne({ orgId: gateway.orgId });
|
||||
if (!orgGatewayConfig) {
|
||||
throw new NotFoundError({ message: `Gateway Config for org ${gateway.orgId} not found.` });
|
||||
}
|
||||
|
||||
if (!gateway.relayId) {
|
||||
throw new BadRequestError({
|
||||
message: "Gateway is not associated with a relay"
|
||||
});
|
||||
}
|
||||
|
||||
const orgLicensePlan = await licenseService.getPlan(orgGatewayConfig.orgId);
|
||||
if (!orgLicensePlan.gateway) {
|
||||
throw new BadRequestError({
|
||||
message: "Please upgrade your instance to Infisical's Enterprise plan to use gateways."
|
||||
});
|
||||
}
|
||||
|
||||
const { decryptor: orgKmsDecryptor } = await kmsService.createCipherPairWithDataKey({
|
||||
type: KmsDataKey.Organization,
|
||||
orgId: orgGatewayConfig.orgId
|
||||
});
|
||||
|
||||
const alg = keyAlgorithmToAlgCfg(CertKeyAlgorithm.RSA_2048);
|
||||
|
||||
const rootGatewayCaCert = new x509.X509Certificate(
|
||||
orgKmsDecryptor({
|
||||
cipherTextBlob: orgGatewayConfig.encryptedRootGatewayCaCertificate
|
||||
})
|
||||
);
|
||||
|
||||
const gatewayClientCaCert = new x509.X509Certificate(
|
||||
orgKmsDecryptor({
|
||||
cipherTextBlob: orgGatewayConfig.encryptedGatewayClientCaCertificate
|
||||
})
|
||||
);
|
||||
|
||||
const gatewayServerCaCert = new x509.X509Certificate(
|
||||
orgKmsDecryptor({
|
||||
cipherTextBlob: orgGatewayConfig.encryptedGatewayServerCaCertificate
|
||||
})
|
||||
);
|
||||
|
||||
const gatewayClientCaPrivateKey = orgKmsDecryptor({
|
||||
cipherTextBlob: orgGatewayConfig.encryptedGatewayClientCaPrivateKey
|
||||
});
|
||||
|
||||
const gatewayClientCaSkObj = crypto.nativeCrypto.createPrivateKey({
|
||||
key: gatewayClientCaPrivateKey,
|
||||
format: "der",
|
||||
type: "pkcs8"
|
||||
});
|
||||
|
||||
const importedGatewayClientCaPrivateKey = await crypto.nativeCrypto.subtle.importKey(
|
||||
"pkcs8",
|
||||
gatewayClientCaSkObj.export({ format: "der", type: "pkcs8" }),
|
||||
alg,
|
||||
true,
|
||||
["sign"]
|
||||
);
|
||||
|
||||
const clientCertIssuedAt = new Date();
|
||||
const clientCertExpiration = new Date(new Date().getTime() + (duration ?? 5 * 60 * 1000));
|
||||
const clientKeys = await crypto.nativeCrypto.subtle.generateKey(alg, true, ["sign", "verify"]);
|
||||
const clientCertSerialNumber = createSerialNumber();
|
||||
|
||||
const routingInfo = {
|
||||
targetHost: host,
|
||||
targetPort: port
|
||||
};
|
||||
|
||||
const routingExtension = new x509.Extension(
|
||||
GATEWAY_ROUTING_INFO_OID,
|
||||
false,
|
||||
Buffer.from(JSON.stringify(routingInfo))
|
||||
);
|
||||
|
||||
const pamInfoExtension = new x509.Extension(
|
||||
PAM_INFO_OID,
|
||||
false,
|
||||
Buffer.from(
|
||||
JSON.stringify({
|
||||
sessionId,
|
||||
resourceType
|
||||
})
|
||||
)
|
||||
);
|
||||
|
||||
const actorExtension = new x509.Extension(
|
||||
GATEWAY_ACTOR_OID,
|
||||
false,
|
||||
Buffer.from(JSON.stringify({ type: actorMetadata.type, id: actorMetadata.id, name: actorMetadata.name }))
|
||||
);
|
||||
|
||||
const clientCert = await x509.X509CertificateGenerator.create({
|
||||
serialNumber: clientCertSerialNumber,
|
||||
subject: `O=${orgGatewayConfig.orgId},OU=gateway-client,CN=${actorMetadata.type}:${gatewayId}`,
|
||||
issuer: gatewayClientCaCert.subject,
|
||||
notAfter: clientCertExpiration,
|
||||
notBefore: clientCertIssuedAt,
|
||||
signingKey: importedGatewayClientCaPrivateKey,
|
||||
publicKey: clientKeys.publicKey,
|
||||
signingAlgorithm: alg,
|
||||
extensions: [
|
||||
new x509.BasicConstraintsExtension(false),
|
||||
await x509.AuthorityKeyIdentifierExtension.create(gatewayClientCaCert, false),
|
||||
await x509.SubjectKeyIdentifierExtension.create(clientKeys.publicKey),
|
||||
new x509.CertificatePolicyExtension(["2.5.29.32.0"]), // anyPolicy
|
||||
new x509.KeyUsagesExtension(
|
||||
// eslint-disable-next-line no-bitwise
|
||||
x509.KeyUsageFlags[CertKeyUsage.DIGITAL_SIGNATURE] |
|
||||
x509.KeyUsageFlags[CertKeyUsage.KEY_ENCIPHERMENT] |
|
||||
x509.KeyUsageFlags[CertKeyUsage.KEY_AGREEMENT],
|
||||
true
|
||||
),
|
||||
new x509.ExtendedKeyUsageExtension([x509.ExtendedKeyUsage[CertExtendedKeyUsage.CLIENT_AUTH]], true),
|
||||
routingExtension,
|
||||
actorExtension,
|
||||
pamInfoExtension
|
||||
]
|
||||
});
|
||||
|
||||
const gatewayClientCertPrivateKey = crypto.nativeCrypto.KeyObject.from(clientKeys.privateKey);
|
||||
|
||||
const relayCredentials = await relayService.getCredentialsForClient({
|
||||
relayId: gateway.relayId,
|
||||
orgId: gateway.orgId,
|
||||
orgName: gateway.orgName,
|
||||
gatewayId,
|
||||
gatewayName: gateway.name,
|
||||
duration
|
||||
});
|
||||
|
||||
return {
|
||||
relayHost: relayCredentials.relayHost,
|
||||
gateway: {
|
||||
clientCertificate: clientCert.toString("pem"),
|
||||
clientPrivateKey: gatewayClientCertPrivateKey.export({ format: "pem", type: "pkcs8" }).toString(),
|
||||
serverCertificateChain: constructPemChainFromCerts([gatewayServerCaCert, rootGatewayCaCert])
|
||||
},
|
||||
relay: {
|
||||
clientCertificate: relayCredentials.clientCertificate,
|
||||
clientPrivateKey: relayCredentials.clientPrivateKey,
|
||||
serverCertificateChain: relayCredentials.serverCertificateChain
|
||||
}
|
||||
};
|
||||
};
|
||||
|
||||
const registerGateway = async ({
|
||||
orgId,
|
||||
actorId,
|
||||
@@ -632,27 +817,145 @@ export const gatewayV2ServiceFactory = ({
|
||||
throw new NotFoundError({ message: `Gateway ${id} not found` });
|
||||
}
|
||||
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
orgPermission.type,
|
||||
orgPermission.id,
|
||||
gateway.orgId,
|
||||
orgPermission.authMethod,
|
||||
orgPermission.orgId
|
||||
);
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
actor: orgPermission.type,
|
||||
actorId: orgPermission.id,
|
||||
orgId: gateway.orgId,
|
||||
actorAuthMethod: orgPermission.authMethod,
|
||||
actorOrgId: orgPermission.orgId,
|
||||
scope: OrganizationActionScope.Any
|
||||
});
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(
|
||||
OrgPermissionGatewayActions.DeleteGateways,
|
||||
OrgPermissionSubjects.Gateway
|
||||
);
|
||||
|
||||
return gatewayV2DAL.deleteById(gateway.id);
|
||||
try {
|
||||
return await gatewayV2DAL.deleteById(gateway.id);
|
||||
} catch (err) {
|
||||
if (
|
||||
err instanceof DatabaseError &&
|
||||
(err.error as { code: string })?.code === DatabaseErrorCode.ForeignKeyViolation
|
||||
) {
|
||||
throw new BadRequestError({
|
||||
message: "Failed to delete gateway because it is attached to active resources"
|
||||
});
|
||||
}
|
||||
|
||||
throw err;
|
||||
}
|
||||
};
|
||||
|
||||
const getPamSessionKey = async ({ orgPermission }: { orgPermission: OrgServiceActor }) => {
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
actor: orgPermission.type,
|
||||
actorId: orgPermission.id,
|
||||
orgId: orgPermission.orgId,
|
||||
actorAuthMethod: orgPermission.authMethod,
|
||||
actorOrgId: orgPermission.orgId,
|
||||
scope: OrganizationActionScope.Any
|
||||
});
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(
|
||||
OrgPermissionGatewayActions.CreateGateways,
|
||||
OrgPermissionSubjects.Gateway
|
||||
);
|
||||
|
||||
return gatewayV2DAL.transaction(async (tx) => {
|
||||
const gateway = await gatewayV2DAL.findOne(
|
||||
{
|
||||
identityId: orgPermission.id
|
||||
},
|
||||
tx
|
||||
);
|
||||
|
||||
if (!gateway) {
|
||||
throw new NotFoundError({ message: "Gateway not found" });
|
||||
}
|
||||
|
||||
const { encryptor, decryptor } = await kmsService.createCipherPairWithDataKey({
|
||||
type: KmsDataKey.Organization,
|
||||
orgId: orgPermission.orgId
|
||||
});
|
||||
|
||||
if (gateway.encryptedPamSessionKey) {
|
||||
return decryptor({ cipherTextBlob: gateway.encryptedPamSessionKey });
|
||||
}
|
||||
|
||||
await tx.raw("SELECT pg_advisory_xact_lock(?)", [PgSqlLock.GatewayPamSessionKey(gateway.id)]);
|
||||
|
||||
const newPamSessionKey = crypto.randomBytes(32);
|
||||
const { cipherTextBlob: encryptedPamSessionKey } = encryptor({ plainText: newPamSessionKey });
|
||||
|
||||
await gatewayV2DAL.updateById(gateway.id, { encryptedPamSessionKey }, tx);
|
||||
|
||||
return newPamSessionKey;
|
||||
});
|
||||
};
|
||||
|
||||
const healthcheckNotify = async () => {
|
||||
const unhealthyGateways = await gatewayV2DAL.find({
|
||||
isHeartbeatStale: true
|
||||
});
|
||||
|
||||
if (unhealthyGateways.length === 0) return;
|
||||
|
||||
logger.warn(
|
||||
{ gatewayIds: unhealthyGateways.map((g) => g.id) },
|
||||
"Found gateways with last heartbeat over an hour ago. Sending notifications."
|
||||
);
|
||||
|
||||
const gatewaysByOrg = groupBy(unhealthyGateways, (gw) => gw.orgId);
|
||||
|
||||
for await (const [orgId, gateways] of Object.entries(gatewaysByOrg)) {
|
||||
try {
|
||||
const admins = await orgDAL.findOrgMembersByRole(orgId, OrgMembershipRole.Admin);
|
||||
if (admins.length === 0) {
|
||||
logger.warn({ orgId }, "Organization has no admins to notify about unhealthy gateway.");
|
||||
// eslint-disable-next-line no-continue
|
||||
continue;
|
||||
}
|
||||
|
||||
const gatewayNames = gateways.map((g) => `"${g.name}"`).join(", ");
|
||||
const body = `The following gateway(s) in your organization may be offline as they haven't reported a heartbeat in over an hour: ${gatewayNames}. Please check their status.`;
|
||||
|
||||
await notificationService.createUserNotifications(
|
||||
admins.map((admin) => ({
|
||||
userId: admin.user.id,
|
||||
orgId,
|
||||
type: NotificationType.GATEWAY_HEALTH_ALERT,
|
||||
title: "Gateway Health Alert",
|
||||
body,
|
||||
link: "/organization/networking"
|
||||
}))
|
||||
);
|
||||
|
||||
await smtpService.sendMail({
|
||||
recipients: admins.map((admin) => admin.user.email).filter((v): v is string => !!v),
|
||||
subjectLine: "Gateway Health Alert",
|
||||
substitutions: {
|
||||
type: "gateway",
|
||||
names: gatewayNames
|
||||
},
|
||||
template: SmtpTemplates.HealthAlert
|
||||
});
|
||||
|
||||
await Promise.all(gateways.map((gw) => gatewayV2DAL.updateById(gw.id, { healthAlertedAt: new Date() })));
|
||||
} catch (error) {
|
||||
logger.error(error, `Failed to send gateway health notifications for organization [orgId=${orgId}]`);
|
||||
}
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
listGateways,
|
||||
registerGateway,
|
||||
getPlatformConnectionDetailsByGatewayId,
|
||||
getPAMConnectionDetails,
|
||||
deleteGatewayById,
|
||||
heartbeat
|
||||
heartbeat,
|
||||
getPamSessionKey,
|
||||
healthcheckNotify
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,5 +1,5 @@
|
||||
import { TDbClient } from "@app/db";
|
||||
import { GatewaysSchema, TableName, TGateways } from "@app/db/schemas";
|
||||
import { AccessScope, GatewaysSchema, TableName, TGateways } from "@app/db/schemas";
|
||||
import { DatabaseError } from "@app/lib/errors";
|
||||
import { buildFindFilter, ormify, selectAllTableCols, TFindFilter, TFindOpt } from "@app/lib/knex";
|
||||
|
||||
@@ -17,17 +17,14 @@ export const gatewayDALFactory = (db: TDbClient) => {
|
||||
// eslint-disable-next-line @typescript-eslint/no-misused-promises
|
||||
.where(buildFindFilter(filter, TableName.Gateway, ["orgId"]))
|
||||
.join(TableName.Identity, `${TableName.Identity}.id`, `${TableName.Gateway}.identityId`)
|
||||
.join(
|
||||
TableName.IdentityOrgMembership,
|
||||
`${TableName.IdentityOrgMembership}.identityId`,
|
||||
`${TableName.Gateway}.identityId`
|
||||
)
|
||||
.join(TableName.Membership, `${TableName.Membership}.actorIdentityId`, `${TableName.Gateway}.identityId`)
|
||||
.select(selectAllTableCols(TableName.Gateway))
|
||||
.select(db.ref("orgId").withSchema(TableName.IdentityOrgMembership).as("identityOrgId"))
|
||||
.select(db.ref("name").withSchema(TableName.Identity).as("identityName"));
|
||||
.select(db.ref("scopeOrgId").withSchema(TableName.Membership).as("identityOrgId"))
|
||||
.select(db.ref("name").withSchema(TableName.Identity).as("identityName"))
|
||||
.where(`${TableName.Membership}.scope`, AccessScope.Organization);
|
||||
|
||||
if (filter.orgId) {
|
||||
void query.where(`${TableName.IdentityOrgMembership}.orgId`, filter.orgId);
|
||||
void query.where(`${TableName.Membership}.scopeOrgId`, filter.orgId);
|
||||
}
|
||||
if (limit) void query.limit(limit);
|
||||
if (offset) void query.offset(offset);
|
||||
@@ -39,7 +36,7 @@ export const gatewayDALFactory = (db: TDbClient) => {
|
||||
|
||||
return docs.map((el) => ({
|
||||
...GatewaysSchema.parse(el),
|
||||
orgId: el.identityOrgId as string, // todo(daniel): figure out why typescript is not inferring this as a string
|
||||
orgId: el.identityOrgId,
|
||||
identity: { id: el.identityId, name: el.identityName }
|
||||
}));
|
||||
} catch (error) {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { ForbiddenError } from "@casl/ability";
|
||||
import * as x509 from "@peculiar/x509";
|
||||
import { z } from "zod";
|
||||
|
||||
import { OrganizationActionScope } from "@app/db/schemas";
|
||||
import { KeyStorePrefixes, PgSqlLock, TKeyStoreFactory } from "@app/keystore/keystore";
|
||||
import { getConfig } from "@app/lib/config/env";
|
||||
import { crypto } from "@app/lib/crypto/cryptography";
|
||||
@@ -68,13 +69,14 @@ export const gatewayServiceFactory = ({
|
||||
"Gateway handshake failed due to organization plan restrictions. Please upgrade your instance to Infisical's Enterprise plan."
|
||||
});
|
||||
}
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
ActorType.IDENTITY,
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
actor: ActorType.IDENTITY,
|
||||
actorId,
|
||||
orgId,
|
||||
actorAuthMethod,
|
||||
orgId
|
||||
);
|
||||
actorOrgId: orgId,
|
||||
scope: OrganizationActionScope.Any
|
||||
});
|
||||
ForbiddenError.from(permission).throwUnlessCan(
|
||||
OrgPermissionGatewayActions.CreateGateways,
|
||||
OrgPermissionSubjects.Gateway
|
||||
@@ -480,13 +482,14 @@ export const gatewayServiceFactory = ({
|
||||
};
|
||||
|
||||
const listGateways = async ({ orgPermission }: TListGatewaysDTO) => {
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
orgPermission.type,
|
||||
orgPermission.id,
|
||||
orgPermission.orgId,
|
||||
orgPermission.authMethod,
|
||||
orgPermission.orgId
|
||||
);
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
actor: orgPermission.type,
|
||||
actorId: orgPermission.id,
|
||||
orgId: orgPermission.orgId,
|
||||
actorAuthMethod: orgPermission.authMethod,
|
||||
actorOrgId: orgPermission.orgId,
|
||||
scope: OrganizationActionScope.Any
|
||||
});
|
||||
ForbiddenError.from(permission).throwUnlessCan(
|
||||
OrgPermissionGatewayActions.ListGateways,
|
||||
OrgPermissionSubjects.Gateway
|
||||
@@ -501,13 +504,14 @@ export const gatewayServiceFactory = ({
|
||||
};
|
||||
|
||||
const getGatewayById = async ({ orgPermission, id }: TGetGatewayByIdDTO) => {
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
orgPermission.type,
|
||||
orgPermission.id,
|
||||
orgPermission.orgId,
|
||||
orgPermission.authMethod,
|
||||
orgPermission.orgId
|
||||
);
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
actor: orgPermission.type,
|
||||
actorId: orgPermission.id,
|
||||
orgId: orgPermission.orgId,
|
||||
actorAuthMethod: orgPermission.authMethod,
|
||||
actorOrgId: orgPermission.orgId,
|
||||
scope: OrganizationActionScope.Any
|
||||
});
|
||||
ForbiddenError.from(permission).throwUnlessCan(
|
||||
OrgPermissionGatewayActions.ListGateways,
|
||||
OrgPermissionSubjects.Gateway
|
||||
@@ -521,13 +525,14 @@ export const gatewayServiceFactory = ({
|
||||
};
|
||||
|
||||
const updateGatewayById = async ({ orgPermission, id, name }: TUpdateGatewayByIdDTO) => {
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
orgPermission.type,
|
||||
orgPermission.id,
|
||||
orgPermission.orgId,
|
||||
orgPermission.authMethod,
|
||||
orgPermission.orgId
|
||||
);
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
actor: orgPermission.type,
|
||||
actorId: orgPermission.id,
|
||||
orgId: orgPermission.orgId,
|
||||
actorAuthMethod: orgPermission.authMethod,
|
||||
actorOrgId: orgPermission.orgId,
|
||||
scope: OrganizationActionScope.Any
|
||||
});
|
||||
ForbiddenError.from(permission).throwUnlessCan(
|
||||
OrgPermissionGatewayActions.EditGateways,
|
||||
OrgPermissionSubjects.Gateway
|
||||
@@ -542,13 +547,14 @@ export const gatewayServiceFactory = ({
|
||||
};
|
||||
|
||||
const deleteGatewayById = async ({ orgPermission, id }: TGetGatewayByIdDTO) => {
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
orgPermission.type,
|
||||
orgPermission.id,
|
||||
orgPermission.orgId,
|
||||
orgPermission.authMethod,
|
||||
orgPermission.orgId
|
||||
);
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
actor: orgPermission.type,
|
||||
actorId: orgPermission.id,
|
||||
orgId: orgPermission.orgId,
|
||||
actorAuthMethod: orgPermission.authMethod,
|
||||
actorOrgId: orgPermission.orgId,
|
||||
scope: OrganizationActionScope.Any
|
||||
});
|
||||
ForbiddenError.from(permission).throwUnlessCan(
|
||||
OrgPermissionGatewayActions.DeleteGateways,
|
||||
OrgPermissionSubjects.Gateway
|
||||
|
||||
@@ -6,13 +6,15 @@ import { paginateGraphql } from "@octokit/plugin-paginate-graphql";
|
||||
import { Octokit as OctokitRest } from "@octokit/rest";
|
||||
import RE2 from "re2";
|
||||
|
||||
import { OrgMembershipRole } from "@app/db/schemas";
|
||||
import { AccessScope, OrganizationActionScope, OrgMembershipRole } from "@app/db/schemas";
|
||||
import { BadRequestError, NotFoundError } from "@app/lib/errors";
|
||||
import { groupBy } from "@app/lib/fn";
|
||||
import { logger } from "@app/lib/logger";
|
||||
import { retryWithBackoff } from "@app/lib/retry";
|
||||
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
|
||||
import { KmsDataKey } from "@app/services/kms/kms-types";
|
||||
import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";
|
||||
import { TMembershipGroupDALFactory } from "@app/services/membership-group/membership-group-dal";
|
||||
import { TOrgMembershipDALFactory } from "@app/services/org-membership/org-membership-dal";
|
||||
|
||||
import { TGroupDALFactory } from "../group/group-dal";
|
||||
@@ -77,11 +79,10 @@ type TGithubOrgSyncServiceFactoryDep = {
|
||||
"findGroupMembershipsByUserIdInOrg" | "findGroupMembershipsByGroupIdInOrg" | "insertMany" | "delete"
|
||||
>;
|
||||
groupDAL: Pick<TGroupDALFactory, "insertMany" | "transaction" | "find">;
|
||||
membershipRoleDAL: Pick<TMembershipRoleDALFactory, "insertMany">;
|
||||
membershipGroupDAL: Pick<TMembershipGroupDALFactory, "insertMany">;
|
||||
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
|
||||
orgMembershipDAL: Pick<
|
||||
TOrgMembershipDALFactory,
|
||||
"find" | "findOrgMembershipById" | "findOrgMembershipsWithUsersByOrgId"
|
||||
>;
|
||||
orgMembershipDAL: Pick<TOrgMembershipDALFactory, "findOrgMembershipById" | "findOrgMembershipsWithUsersByOrgId">;
|
||||
};
|
||||
|
||||
export type TGithubOrgSyncServiceFactory = ReturnType<typeof githubOrgSyncServiceFactory>;
|
||||
@@ -93,7 +94,9 @@ export const githubOrgSyncServiceFactory = ({
|
||||
userGroupMembershipDAL,
|
||||
groupDAL,
|
||||
licenseService,
|
||||
orgMembershipDAL
|
||||
orgMembershipDAL,
|
||||
membershipRoleDAL,
|
||||
membershipGroupDAL
|
||||
}: TGithubOrgSyncServiceFactoryDep) => {
|
||||
const createGithubOrgSync = async ({
|
||||
githubOrgName,
|
||||
@@ -101,13 +104,14 @@ export const githubOrgSyncServiceFactory = ({
|
||||
githubOrgAccessToken,
|
||||
isActive
|
||||
}: TCreateGithubOrgSyncDTO) => {
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
orgPermission.type,
|
||||
orgPermission.id,
|
||||
orgPermission.orgId,
|
||||
orgPermission.authMethod,
|
||||
orgPermission.orgId
|
||||
);
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
scope: OrganizationActionScope.ParentOrganization,
|
||||
actor: orgPermission.type,
|
||||
actorId: orgPermission.id,
|
||||
orgId: orgPermission.orgId,
|
||||
actorAuthMethod: orgPermission.authMethod,
|
||||
actorOrgId: orgPermission.orgId
|
||||
});
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Create, OrgPermissionSubjects.GithubOrgSync);
|
||||
const plan = await licenseService.getPlan(orgPermission.orgId);
|
||||
@@ -159,13 +163,14 @@ export const githubOrgSyncServiceFactory = ({
|
||||
githubOrgAccessToken,
|
||||
isActive
|
||||
}: TUpdateGithubOrgSyncDTO) => {
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
orgPermission.type,
|
||||
orgPermission.id,
|
||||
orgPermission.orgId,
|
||||
orgPermission.authMethod,
|
||||
orgPermission.orgId
|
||||
);
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
actor: orgPermission.type,
|
||||
scope: OrganizationActionScope.ParentOrganization,
|
||||
actorId: orgPermission.id,
|
||||
orgId: orgPermission.orgId,
|
||||
actorAuthMethod: orgPermission.authMethod,
|
||||
actorOrgId: orgPermission.orgId
|
||||
});
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.GithubOrgSync);
|
||||
const plan = await licenseService.getPlan(orgPermission.orgId);
|
||||
@@ -223,13 +228,14 @@ export const githubOrgSyncServiceFactory = ({
|
||||
};
|
||||
|
||||
const deleteGithubOrgSync = async ({ orgPermission }: TDeleteGithubOrgSyncDTO) => {
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
orgPermission.type,
|
||||
orgPermission.id,
|
||||
orgPermission.orgId,
|
||||
orgPermission.authMethod,
|
||||
orgPermission.orgId
|
||||
);
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
actor: orgPermission.type,
|
||||
actorId: orgPermission.id,
|
||||
orgId: orgPermission.orgId,
|
||||
actorAuthMethod: orgPermission.authMethod,
|
||||
actorOrgId: orgPermission.orgId,
|
||||
scope: OrganizationActionScope.ParentOrganization
|
||||
});
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Delete, OrgPermissionSubjects.GithubOrgSync);
|
||||
|
||||
@@ -253,13 +259,14 @@ export const githubOrgSyncServiceFactory = ({
|
||||
};
|
||||
|
||||
const getGithubOrgSync = async ({ orgPermission }: TDeleteGithubOrgSyncDTO) => {
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
orgPermission.type,
|
||||
orgPermission.id,
|
||||
orgPermission.orgId,
|
||||
orgPermission.authMethod,
|
||||
orgPermission.orgId
|
||||
);
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
actorId: orgPermission.id,
|
||||
actor: orgPermission.type,
|
||||
orgId: orgPermission.orgId,
|
||||
actorAuthMethod: orgPermission.authMethod,
|
||||
actorOrgId: orgPermission.orgId,
|
||||
scope: OrganizationActionScope.ParentOrganization
|
||||
});
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.GithubOrgSync);
|
||||
|
||||
@@ -368,6 +375,23 @@ export const githubOrgSyncServiceFactory = ({
|
||||
})),
|
||||
tx
|
||||
);
|
||||
const memberships = await membershipGroupDAL.insertMany(
|
||||
newGroups.map((el) => ({
|
||||
actorGroupId: el.id,
|
||||
scope: AccessScope.Organization,
|
||||
scopeOrgId: orgId
|
||||
})),
|
||||
tx
|
||||
);
|
||||
|
||||
await membershipRoleDAL.insertMany(
|
||||
memberships.map((el) => ({
|
||||
membershipId: el.id,
|
||||
role: OrgMembershipRole.Member
|
||||
})),
|
||||
tx
|
||||
);
|
||||
|
||||
await userGroupMembershipDAL.insertMany(
|
||||
newGroups.map((el) => ({
|
||||
groupId: el.id,
|
||||
@@ -402,13 +426,14 @@ export const githubOrgSyncServiceFactory = ({
|
||||
};
|
||||
|
||||
const validateGithubToken = async ({ orgPermission, githubOrgAccessToken }: TValidateGithubTokenDTO) => {
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
orgPermission.type,
|
||||
orgPermission.id,
|
||||
orgPermission.orgId,
|
||||
orgPermission.authMethod,
|
||||
orgPermission.orgId
|
||||
);
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
actorId: orgPermission.id,
|
||||
actor: orgPermission.type,
|
||||
orgId: orgPermission.orgId,
|
||||
actorAuthMethod: orgPermission.authMethod,
|
||||
actorOrgId: orgPermission.orgId,
|
||||
scope: OrganizationActionScope.ParentOrganization
|
||||
});
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.GithubOrgSync);
|
||||
|
||||
@@ -489,13 +514,14 @@ export const githubOrgSyncServiceFactory = ({
|
||||
};
|
||||
|
||||
const syncAllTeams = async ({ orgPermission }: TSyncAllTeamsDTO): Promise<TSyncResult> => {
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
orgPermission.type,
|
||||
orgPermission.id,
|
||||
orgPermission.orgId,
|
||||
orgPermission.authMethod,
|
||||
orgPermission.orgId
|
||||
);
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
scope: OrganizationActionScope.ParentOrganization,
|
||||
actor: orgPermission.type,
|
||||
orgId: orgPermission.orgId,
|
||||
actorId: orgPermission.id,
|
||||
actorAuthMethod: orgPermission.authMethod,
|
||||
actorOrgId: orgPermission.orgId
|
||||
});
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(
|
||||
OrgPermissionActions.Edit,
|
||||
@@ -694,6 +720,23 @@ export const githubOrgSyncServiceFactory = ({
|
||||
tx
|
||||
);
|
||||
|
||||
const memberships = await membershipGroupDAL.insertMany(
|
||||
newGroups.map((el) => ({
|
||||
actorGroupId: el.id,
|
||||
scope: AccessScope.Organization,
|
||||
scopeOrgId: orgPermission.orgId
|
||||
})),
|
||||
tx
|
||||
);
|
||||
|
||||
await membershipRoleDAL.insertMany(
|
||||
memberships.map((el) => ({
|
||||
membershipId: el.id,
|
||||
role: OrgMembershipRole.Member
|
||||
})),
|
||||
tx
|
||||
);
|
||||
|
||||
newGroups.forEach((group) => {
|
||||
if (!existingTeamsMap[group.name]) {
|
||||
existingTeamsMap[group.name] = [];
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Knex } from "knex";
|
||||
|
||||
import { TDbClient } from "@app/db";
|
||||
import { TableName, TGroups } from "@app/db/schemas";
|
||||
import { AccessScope, TableName, TGroups } from "@app/db/schemas";
|
||||
import { DatabaseError } from "@app/lib/errors";
|
||||
import { buildFindFilter, ormify, selectAllTableCols, TFindFilter, TFindOpt } from "@app/lib/knex";
|
||||
|
||||
@@ -20,7 +20,7 @@ export const groupDALFactory = (db: TDbClient) => {
|
||||
.select(selectAllTableCols(TableName.Groups));
|
||||
|
||||
if (limit) void query.limit(limit);
|
||||
if (offset) void query.limit(offset);
|
||||
if (offset && offset > 0) void query.offset(offset);
|
||||
if (sort) {
|
||||
void query.orderBy(sort.map(([column, order, nulls]) => ({ column: column as string, order, nulls })));
|
||||
}
|
||||
@@ -36,14 +36,21 @@ export const groupDALFactory = (db: TDbClient) => {
|
||||
try {
|
||||
const docs = await (tx || db.replicaNode())(TableName.Groups)
|
||||
.where(`${TableName.Groups}.orgId`, orgId)
|
||||
.leftJoin(TableName.OrgRoles, `${TableName.Groups}.roleId`, `${TableName.OrgRoles}.id`)
|
||||
.where(`${TableName.Membership}.scopeOrgId`, orgId)
|
||||
.where(`${TableName.Membership}.scope`, AccessScope.Organization)
|
||||
.join(TableName.Membership, `${TableName.Groups}.id`, `${TableName.Membership}.actorGroupId`)
|
||||
.join(TableName.MembershipRole, `${TableName.MembershipRole}.membershipId`, `${TableName.Membership}.id`)
|
||||
.leftJoin(TableName.Role, `${TableName.MembershipRole}.customRoleId`, `${TableName.Role}.id`)
|
||||
.select(selectAllTableCols(TableName.Groups))
|
||||
// cr stands for custom role
|
||||
.select(db.ref("id").as("crId").withSchema(TableName.OrgRoles))
|
||||
.select(db.ref("name").as("crName").withSchema(TableName.OrgRoles))
|
||||
.select(db.ref("slug").as("crSlug").withSchema(TableName.OrgRoles))
|
||||
.select(db.ref("description").as("crDescription").withSchema(TableName.OrgRoles))
|
||||
.select(db.ref("permissions").as("crPermission").withSchema(TableName.OrgRoles));
|
||||
.select(db.ref("id").as("crId").withSchema(TableName.Role))
|
||||
.select(db.ref("name").as("crName").withSchema(TableName.Role))
|
||||
.select(db.ref("role").withSchema(TableName.MembershipRole))
|
||||
.select(db.ref("customRoleId").as("roleId").withSchema(TableName.MembershipRole))
|
||||
.select(db.ref("slug").as("crSlug").withSchema(TableName.Role))
|
||||
.select(db.ref("description").as("crDescription").withSchema(TableName.Role))
|
||||
.select(db.ref("permissions").as("crPermission").withSchema(TableName.Role));
|
||||
|
||||
return docs.map(({ crId, crDescription, crSlug, crPermission, crName, ...el }) => ({
|
||||
...el,
|
||||
customRole: el.roleId
|
||||
@@ -81,9 +88,11 @@ export const groupDALFactory = (db: TDbClient) => {
|
||||
}) => {
|
||||
try {
|
||||
const query = db
|
||||
.replicaNode()(TableName.OrgMembership)
|
||||
.where(`${TableName.OrgMembership}.orgId`, orgId)
|
||||
.join(TableName.Users, `${TableName.OrgMembership}.userId`, `${TableName.Users}.id`)
|
||||
.replicaNode()(TableName.Membership)
|
||||
.where(`${TableName.Membership}.scopeOrgId`, orgId)
|
||||
.where(`${TableName.Membership}.scope`, AccessScope.Organization)
|
||||
.whereNotNull(`${TableName.Membership}.actorUserId`)
|
||||
.join(TableName.Users, `${TableName.Membership}.actorUserId`, `${TableName.Users}.id`)
|
||||
.leftJoin(TableName.UserGroupMembership, (bd) => {
|
||||
bd.on(`${TableName.UserGroupMembership}.userId`, "=", `${TableName.Users}.id`).andOn(
|
||||
`${TableName.UserGroupMembership}.groupId`,
|
||||
@@ -92,7 +101,7 @@ export const groupDALFactory = (db: TDbClient) => {
|
||||
);
|
||||
})
|
||||
.select(
|
||||
db.ref("id").withSchema(TableName.OrgMembership),
|
||||
db.ref("id").withSchema(TableName.Membership),
|
||||
db.ref("groupId").withSchema(TableName.UserGroupMembership),
|
||||
db.ref("createdAt").withSchema(TableName.UserGroupMembership).as("joinedGroupAt"),
|
||||
db.ref("email").withSchema(TableName.Users),
|
||||
@@ -160,8 +169,10 @@ export const groupDALFactory = (db: TDbClient) => {
|
||||
const findGroupsByProjectId = async (projectId: string, tx?: Knex) => {
|
||||
try {
|
||||
const docs = await (tx || db.replicaNode())(TableName.Groups)
|
||||
.join(TableName.GroupProjectMembership, `${TableName.Groups}.id`, `${TableName.GroupProjectMembership}.groupId`)
|
||||
.where(`${TableName.GroupProjectMembership}.projectId`, projectId)
|
||||
.join(TableName.Membership, `${TableName.Membership}.actorGroupId`, `${TableName.Groups}.id`)
|
||||
.where(`${TableName.Membership}.scopeProjectId`, projectId)
|
||||
.where(`${TableName.Membership}.scope`, AccessScope.Project)
|
||||
.whereNotNull(`${TableName.Membership}.actorGroupId`)
|
||||
.select(selectAllTableCols(TableName.Groups));
|
||||
return docs;
|
||||
} catch (error) {
|
||||
@@ -172,11 +183,16 @@ export const groupDALFactory = (db: TDbClient) => {
|
||||
const findById = async (id: string, tx?: Knex) => {
|
||||
try {
|
||||
const doc = await (tx || db.replicaNode())(TableName.Groups)
|
||||
.leftJoin(TableName.OrgRoles, `${TableName.Groups}.roleId`, `${TableName.OrgRoles}.id`)
|
||||
.join(TableName.Membership, `${TableName.Membership}.actorGroupId`, `${TableName.Groups}.id`)
|
||||
.join(TableName.MembershipRole, `${TableName.MembershipRole}.membershipId`, `${TableName.Membership}.id`)
|
||||
.leftJoin(TableName.Role, `${TableName.MembershipRole}.customRoleId`, `${TableName.Role}.id`)
|
||||
.where(`${TableName.Groups}.id`, id)
|
||||
.where(`${TableName.Membership}.scope`, AccessScope.Organization)
|
||||
.select(
|
||||
selectAllTableCols(TableName.Groups),
|
||||
db.ref("slug").as("customRoleSlug").withSchema(TableName.OrgRoles)
|
||||
db.ref("slug").as("customRoleSlug").withSchema(TableName.Role),
|
||||
db.ref("customRoleId").as("roleId").withSchema(TableName.MembershipRole),
|
||||
db.ref("role").withSchema(TableName.MembershipRole)
|
||||
)
|
||||
.first();
|
||||
|
||||
@@ -186,12 +202,36 @@ export const groupDALFactory = (db: TDbClient) => {
|
||||
}
|
||||
};
|
||||
|
||||
const findOne = async (filter: Partial<TGroups>, tx?: Knex): Promise<TGroups | undefined> => {
|
||||
try {
|
||||
const doc = await (tx || db.replicaNode())(TableName.Groups)
|
||||
.join(TableName.Membership, `${TableName.Membership}.actorGroupId`, `${TableName.Groups}.id`)
|
||||
.join(TableName.MembershipRole, `${TableName.MembershipRole}.membershipId`, `${TableName.Membership}.id`)
|
||||
.where(`${TableName.Membership}.scope`, AccessScope.Organization)
|
||||
.where((queryBuilder) => {
|
||||
Object.entries(filter).forEach(([key, value]) => {
|
||||
void queryBuilder.where(`${TableName.Groups}.${key}`, value);
|
||||
});
|
||||
})
|
||||
.select(
|
||||
selectAllTableCols(TableName.Groups),
|
||||
db.ref("role").withSchema(TableName.MembershipRole),
|
||||
db.ref("customRoleId").as("roleId").withSchema(TableName.MembershipRole)
|
||||
)
|
||||
.first();
|
||||
return doc;
|
||||
} catch (error) {
|
||||
throw new DatabaseError({ error, name: "Find one" });
|
||||
}
|
||||
};
|
||||
|
||||
return {
|
||||
...groupOrm,
|
||||
findGroups,
|
||||
findByOrgId,
|
||||
findAllGroupPossibleMembers,
|
||||
findGroupsByProjectId,
|
||||
findById
|
||||
findById,
|
||||
findOne
|
||||
};
|
||||
};
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
import { Knex } from "knex";
|
||||
|
||||
import { ProjectVersion, SecretKeyEncoding, TableName, TUsers } from "@app/db/schemas";
|
||||
import { AccessScope, ProjectVersion, SecretKeyEncoding, TableName, TUsers } from "@app/db/schemas";
|
||||
import { crypto } from "@app/lib/crypto/cryptography";
|
||||
import { BadRequestError, ForbiddenRequestError, NotFoundError, ScimRequestError } from "@app/lib/errors";
|
||||
|
||||
@@ -16,7 +16,7 @@ const addAcceptedUsersToGroup = async ({
|
||||
group,
|
||||
userGroupMembershipDAL,
|
||||
userDAL,
|
||||
groupProjectDAL,
|
||||
membershipGroupDAL,
|
||||
projectKeyDAL,
|
||||
projectDAL,
|
||||
projectBotDAL,
|
||||
@@ -42,13 +42,15 @@ const addAcceptedUsersToGroup = async ({
|
||||
const projectIds = Array.from(
|
||||
new Set(
|
||||
(
|
||||
await groupProjectDAL.find(
|
||||
await membershipGroupDAL.find(
|
||||
{
|
||||
groupId: group.id
|
||||
actorGroupId: group.id,
|
||||
scopeOrgId: group.orgId,
|
||||
scope: AccessScope.Project
|
||||
},
|
||||
{ tx }
|
||||
)
|
||||
).map((gp) => gp.projectId)
|
||||
).map((gp) => gp.scopeProjectId as string)
|
||||
)
|
||||
);
|
||||
|
||||
@@ -167,11 +169,11 @@ export const addUsersToGroupByUserIds = async ({
|
||||
userDAL,
|
||||
userGroupMembershipDAL,
|
||||
orgDAL,
|
||||
groupProjectDAL,
|
||||
projectKeyDAL,
|
||||
projectDAL,
|
||||
projectBotDAL,
|
||||
tx: outerTx
|
||||
tx: outerTx,
|
||||
membershipGroupDAL
|
||||
}: TAddUsersToGroupByUserIds) => {
|
||||
const processAddition = async (tx: Knex) => {
|
||||
const foundMembers = await userDAL.find(
|
||||
@@ -214,15 +216,18 @@ export const addUsersToGroupByUserIds = async ({
|
||||
// check if all user(s) are part of the organization
|
||||
const existingUserOrgMemberships = await orgDAL.findMembership(
|
||||
{
|
||||
[`${TableName.OrgMembership}.orgId` as "orgId"]: group.orgId,
|
||||
[`${TableName.Membership}.scopeOrgId` as "scopeOrgId"]: group.orgId,
|
||||
scope: AccessScope.Organization,
|
||||
$in: {
|
||||
[`${TableName.OrgMembership}.userId` as "userId"]: userIds
|
||||
[`${TableName.Membership}.actorUserId` as "actorUserId"]: userIds
|
||||
}
|
||||
},
|
||||
{ tx }
|
||||
);
|
||||
|
||||
const existingUserOrgMembershipsUserIdsSet = new Set(existingUserOrgMemberships.map((u) => u.userId));
|
||||
const existingUserOrgMembershipsUserIdsSet = new Set(
|
||||
existingUserOrgMemberships.map((u) => u.actorUserId as string)
|
||||
);
|
||||
|
||||
userIds.forEach((userId) => {
|
||||
if (!existingUserOrgMembershipsUserIdsSet.has(userId))
|
||||
@@ -250,7 +255,7 @@ export const addUsersToGroupByUserIds = async ({
|
||||
group,
|
||||
userDAL,
|
||||
userGroupMembershipDAL,
|
||||
groupProjectDAL,
|
||||
membershipGroupDAL,
|
||||
projectKeyDAL,
|
||||
projectDAL,
|
||||
projectBotDAL,
|
||||
@@ -292,9 +297,9 @@ export const removeUsersFromGroupByUserIds = async ({
|
||||
userIds,
|
||||
userDAL,
|
||||
userGroupMembershipDAL,
|
||||
groupProjectDAL,
|
||||
projectKeyDAL,
|
||||
tx: outerTx
|
||||
tx: outerTx,
|
||||
membershipGroupDAL
|
||||
}: TRemoveUsersFromGroupByUserIds) => {
|
||||
const processRemoval = async (tx: Knex) => {
|
||||
const foundMembers = await userDAL.find({
|
||||
@@ -352,13 +357,15 @@ export const removeUsersFromGroupByUserIds = async ({
|
||||
const projectIds = Array.from(
|
||||
new Set(
|
||||
(
|
||||
await groupProjectDAL.find(
|
||||
await membershipGroupDAL.find(
|
||||
{
|
||||
groupId: group.id
|
||||
scope: AccessScope.Project,
|
||||
actorGroupId: group.id,
|
||||
scopeOrgId: group.orgId
|
||||
},
|
||||
{ tx }
|
||||
)
|
||||
).map((gp) => gp.projectId)
|
||||
).map((gp) => gp.scopeProjectId as string)
|
||||
)
|
||||
);
|
||||
|
||||
@@ -422,11 +429,11 @@ export const convertPendingGroupAdditionsToGroupMemberships = async ({
|
||||
userIds,
|
||||
userDAL,
|
||||
userGroupMembershipDAL,
|
||||
groupProjectDAL,
|
||||
projectKeyDAL,
|
||||
projectDAL,
|
||||
projectBotDAL,
|
||||
tx: outerTx
|
||||
tx: outerTx,
|
||||
membershipGroupDAL
|
||||
}: TConvertPendingGroupAdditionsToGroupMemberships) => {
|
||||
const processConversion = async (tx: Knex) => {
|
||||
const users = await userDAL.find(
|
||||
@@ -463,7 +470,7 @@ export const convertPendingGroupAdditionsToGroupMemberships = async ({
|
||||
group: pendingGroupAddition.group,
|
||||
userDAL,
|
||||
userGroupMembershipDAL,
|
||||
groupProjectDAL,
|
||||
membershipGroupDAL,
|
||||
projectKeyDAL,
|
||||
projectDAL,
|
||||
projectBotDAL,
|
||||
|
||||
@@ -1,11 +1,12 @@
|
||||
import { ForbiddenError } from "@casl/ability";
|
||||
import slugify from "@sindresorhus/slugify";
|
||||
|
||||
import { OrgMembershipRole, TOrgRoles } from "@app/db/schemas";
|
||||
import { AccessScope, OrganizationActionScope, OrgMembershipRole, TRoles } from "@app/db/schemas";
|
||||
import { TOidcConfigDALFactory } from "@app/ee/services/oidc/oidc-config-dal";
|
||||
import { BadRequestError, NotFoundError, PermissionBoundaryError, UnauthorizedError } from "@app/lib/errors";
|
||||
import { alphaNumericNanoId } from "@app/lib/nanoid";
|
||||
import { TGroupProjectDALFactory } from "@app/services/group-project/group-project-dal";
|
||||
import { TMembershipRoleDALFactory } from "@app/services/membership/membership-role-dal";
|
||||
import { TMembershipGroupDALFactory } from "@app/services/membership-group/membership-group-dal";
|
||||
import { TOrgDALFactory } from "@app/services/org/org-dal";
|
||||
import { TProjectDALFactory } from "@app/services/project/project-dal";
|
||||
import { TProjectBotDALFactory } from "@app/services/project-bot/project-bot-dal";
|
||||
@@ -35,8 +36,9 @@ type TGroupServiceFactoryDep = {
|
||||
TGroupDALFactory,
|
||||
"create" | "findOne" | "update" | "delete" | "findAllGroupPossibleMembers" | "findById" | "transaction"
|
||||
>;
|
||||
groupProjectDAL: Pick<TGroupProjectDALFactory, "find">;
|
||||
orgDAL: Pick<TOrgDALFactory, "findMembership" | "countAllOrgMembers">;
|
||||
membershipGroupDAL: Pick<TMembershipGroupDALFactory, "find" | "findOne" | "create">;
|
||||
membershipRoleDAL: Pick<TMembershipRoleDALFactory, "create" | "delete">;
|
||||
orgDAL: Pick<TOrgDALFactory, "findMembership" | "countAllOrgMembers" | "findById">;
|
||||
userGroupMembershipDAL: Pick<
|
||||
TUserGroupMembershipDALFactory,
|
||||
"findOne" | "delete" | "filterProjectsByUserMembership" | "transaction" | "insertMany" | "find"
|
||||
@@ -46,7 +48,7 @@ type TGroupServiceFactoryDep = {
|
||||
projectKeyDAL: Pick<TProjectKeyDALFactory, "find" | "delete" | "findLatestProjectKey" | "insertMany">;
|
||||
permissionService: Pick<
|
||||
TPermissionServiceFactory,
|
||||
"getOrgPermission" | "getOrgPermissionByRole" | "invalidateProjectPermissionCache"
|
||||
"getOrgPermission" | "getOrgPermissionByRoles" | "invalidateProjectPermissionCache"
|
||||
>;
|
||||
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
|
||||
oidcConfigDAL: Pick<TOidcConfigDALFactory, "findOne">;
|
||||
@@ -57,7 +59,6 @@ export type TGroupServiceFactory = ReturnType<typeof groupServiceFactory>;
|
||||
export const groupServiceFactory = ({
|
||||
userDAL,
|
||||
groupDAL,
|
||||
groupProjectDAL,
|
||||
orgDAL,
|
||||
userGroupMembershipDAL,
|
||||
projectDAL,
|
||||
@@ -65,18 +66,21 @@ export const groupServiceFactory = ({
|
||||
projectKeyDAL,
|
||||
permissionService,
|
||||
licenseService,
|
||||
oidcConfigDAL
|
||||
oidcConfigDAL,
|
||||
membershipGroupDAL,
|
||||
membershipRoleDAL
|
||||
}: TGroupServiceFactoryDep) => {
|
||||
const createGroup = async ({ name, slug, role, actor, actorId, actorAuthMethod, actorOrgId }: TCreateGroupDTO) => {
|
||||
if (!actorOrgId) throw new UnauthorizedError({ message: "No organization ID provided in request" });
|
||||
|
||||
const { permission, membership } = await permissionService.getOrgPermission(
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
scope: OrganizationActionScope.Any,
|
||||
actor,
|
||||
actorId,
|
||||
actorOrgId,
|
||||
orgId: actorOrgId,
|
||||
actorAuthMethod,
|
||||
actorOrgId
|
||||
);
|
||||
});
|
||||
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionGroupActions.Create, OrgPermissionSubjects.Groups);
|
||||
|
||||
const plan = await licenseService.getPlan(actorOrgId);
|
||||
@@ -85,25 +89,23 @@ export const groupServiceFactory = ({
|
||||
message: "Failed to create group due to plan restriction. Upgrade plan to create group."
|
||||
});
|
||||
|
||||
const { permission: rolePermission, role: customRole } = await permissionService.getOrgPermissionByRole(
|
||||
role,
|
||||
actorOrgId
|
||||
);
|
||||
const isCustomRole = Boolean(customRole);
|
||||
const [rolePermissionDetails] = await permissionService.getOrgPermissionByRoles([role], actorOrgId);
|
||||
const { shouldUseNewPrivilegeSystem } = await orgDAL.findById(actorOrgId);
|
||||
const isCustomRole = Boolean(rolePermissionDetails?.role);
|
||||
if (role !== OrgMembershipRole.NoAccess) {
|
||||
const permissionBoundary = validatePrivilegeChangeOperation(
|
||||
membership.shouldUseNewPrivilegeSystem,
|
||||
shouldUseNewPrivilegeSystem,
|
||||
OrgPermissionGroupActions.GrantPrivileges,
|
||||
OrgPermissionSubjects.Groups,
|
||||
permission,
|
||||
rolePermission
|
||||
rolePermissionDetails.permission
|
||||
);
|
||||
|
||||
if (!permissionBoundary.isValid)
|
||||
throw new PermissionBoundaryError({
|
||||
message: constructPermissionErrorMessage(
|
||||
"Failed to create group",
|
||||
membership.shouldUseNewPrivilegeSystem,
|
||||
shouldUseNewPrivilegeSystem,
|
||||
OrgPermissionGroupActions.GrantPrivileges,
|
||||
OrgPermissionSubjects.Groups
|
||||
),
|
||||
@@ -125,7 +127,25 @@ export const groupServiceFactory = ({
|
||||
slug: slug || slugify(`${name}-${alphaNumericNanoId(4)}`),
|
||||
orgId: actorOrgId,
|
||||
role: isCustomRole ? OrgMembershipRole.Custom : role,
|
||||
roleId: customRole?.id
|
||||
roleId: null
|
||||
},
|
||||
tx
|
||||
);
|
||||
|
||||
const membership = await membershipGroupDAL.create(
|
||||
{
|
||||
actorGroupId: newGroup.id,
|
||||
scope: AccessScope.Organization,
|
||||
scopeOrgId: actorOrgId
|
||||
},
|
||||
tx
|
||||
);
|
||||
|
||||
await membershipRoleDAL.create(
|
||||
{
|
||||
membershipId: membership.id,
|
||||
role: isCustomRole ? OrgMembershipRole.Custom : role,
|
||||
customRoleId: rolePermissionDetails?.role?.id
|
||||
},
|
||||
tx
|
||||
);
|
||||
@@ -148,13 +168,14 @@ export const groupServiceFactory = ({
|
||||
}: TUpdateGroupDTO) => {
|
||||
if (!actorOrgId) throw new UnauthorizedError({ message: "No organization ID provided in request" });
|
||||
|
||||
const { permission, membership } = await permissionService.getOrgPermission(
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
scope: OrganizationActionScope.Any,
|
||||
actor,
|
||||
actorId,
|
||||
actorOrgId,
|
||||
orgId: actorOrgId,
|
||||
actorAuthMethod,
|
||||
actorOrgId
|
||||
);
|
||||
});
|
||||
|
||||
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionGroupActions.Edit, OrgPermissionSubjects.Groups);
|
||||
|
||||
@@ -169,32 +190,31 @@ export const groupServiceFactory = ({
|
||||
throw new NotFoundError({ message: `Failed to find group with ID ${id}` });
|
||||
}
|
||||
|
||||
let customRole: TOrgRoles | undefined;
|
||||
let customRole: TRoles | undefined;
|
||||
if (role) {
|
||||
const { permission: rolePermission, role: customOrgRole } = await permissionService.getOrgPermissionByRole(
|
||||
role,
|
||||
group.orgId
|
||||
);
|
||||
const [rolePermissionDetails] = await permissionService.getOrgPermissionByRoles([role], group.orgId);
|
||||
|
||||
const { shouldUseNewPrivilegeSystem } = await orgDAL.findById(actorOrgId);
|
||||
const isCustomRole = Boolean(rolePermissionDetails?.role);
|
||||
|
||||
const isCustomRole = Boolean(customOrgRole);
|
||||
const permissionBoundary = validatePrivilegeChangeOperation(
|
||||
membership.shouldUseNewPrivilegeSystem,
|
||||
shouldUseNewPrivilegeSystem,
|
||||
OrgPermissionGroupActions.GrantPrivileges,
|
||||
OrgPermissionSubjects.Groups,
|
||||
permission,
|
||||
rolePermission
|
||||
rolePermissionDetails.permission
|
||||
);
|
||||
if (!permissionBoundary.isValid)
|
||||
throw new PermissionBoundaryError({
|
||||
message: constructPermissionErrorMessage(
|
||||
"Failed to update group",
|
||||
membership.shouldUseNewPrivilegeSystem,
|
||||
shouldUseNewPrivilegeSystem,
|
||||
OrgPermissionGroupActions.GrantPrivileges,
|
||||
OrgPermissionSubjects.Groups
|
||||
),
|
||||
details: { missingPermissions: permissionBoundary.missingPermissions }
|
||||
});
|
||||
if (isCustomRole) customRole = customOrgRole;
|
||||
if (isCustomRole) customRole = rolePermissionDetails?.role;
|
||||
}
|
||||
|
||||
const updatedGroup = await groupDAL.transaction(async (tx) => {
|
||||
@@ -208,48 +228,58 @@ export const groupServiceFactory = ({
|
||||
}
|
||||
}
|
||||
|
||||
const [updated] = await groupDAL.update(
|
||||
{
|
||||
id: group.id
|
||||
},
|
||||
{
|
||||
name,
|
||||
slug: slug ? slugify(slug) : undefined,
|
||||
...(role
|
||||
? {
|
||||
role: customRole ? OrgMembershipRole.Custom : role,
|
||||
roleId: customRole?.id ?? null
|
||||
}
|
||||
: {})
|
||||
},
|
||||
tx
|
||||
);
|
||||
let updated = group;
|
||||
|
||||
if (name || slug) {
|
||||
[updated] = await groupDAL.update(
|
||||
{
|
||||
id: group.id
|
||||
},
|
||||
{
|
||||
name,
|
||||
slug: slug ? slugify(slug) : undefined
|
||||
},
|
||||
tx
|
||||
);
|
||||
}
|
||||
|
||||
if (role) {
|
||||
const membership = await membershipGroupDAL.findOne(
|
||||
{
|
||||
scope: AccessScope.Organization,
|
||||
actorGroupId: updated.id,
|
||||
scopeOrgId: updated.orgId
|
||||
},
|
||||
tx
|
||||
);
|
||||
await membershipRoleDAL.delete({ membershipId: membership.id }, tx);
|
||||
await membershipRoleDAL.create(
|
||||
{
|
||||
membershipId: membership.id,
|
||||
role: customRole ? OrgMembershipRole.Custom : role,
|
||||
customRoleId: customRole?.id ?? null
|
||||
},
|
||||
tx
|
||||
);
|
||||
}
|
||||
|
||||
return updated;
|
||||
});
|
||||
|
||||
if (role) {
|
||||
const groupProjects = await groupProjectDAL.find({ groupId: group.id });
|
||||
await Promise.allSettled([
|
||||
...groupProjects.map((groupProject) =>
|
||||
permissionService.invalidateProjectPermissionCache(groupProject.projectId)
|
||||
)
|
||||
]);
|
||||
}
|
||||
|
||||
return updatedGroup;
|
||||
};
|
||||
|
||||
const deleteGroup = async ({ id, actor, actorId, actorAuthMethod, actorOrgId }: TDeleteGroupDTO) => {
|
||||
if (!actorOrgId) throw new UnauthorizedError({ message: "No organization ID provided in request" });
|
||||
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
scope: OrganizationActionScope.Any,
|
||||
actor,
|
||||
actorId,
|
||||
actorOrgId,
|
||||
orgId: actorOrgId,
|
||||
actorAuthMethod,
|
||||
actorOrgId
|
||||
);
|
||||
});
|
||||
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionGroupActions.Delete, OrgPermissionSubjects.Groups);
|
||||
|
||||
const plan = await licenseService.getPlan(actorOrgId);
|
||||
@@ -259,34 +289,29 @@ export const groupServiceFactory = ({
|
||||
message: "Failed to delete group due to plan restriction. Upgrade plan to delete group."
|
||||
});
|
||||
|
||||
const groupProjects = await groupProjectDAL.find({ groupId: id });
|
||||
|
||||
const [group] = await groupDAL.delete({
|
||||
id,
|
||||
orgId: actorOrgId
|
||||
});
|
||||
|
||||
await Promise.allSettled([
|
||||
...groupProjects.map((groupProject) => permissionService.invalidateProjectPermissionCache(groupProject.projectId))
|
||||
]);
|
||||
|
||||
return group;
|
||||
};
|
||||
|
||||
const getGroupById = async ({ id, actor, actorId, actorAuthMethod, actorOrgId }: TGetGroupByIdDTO) => {
|
||||
if (!actorOrgId) throw new UnauthorizedError({ message: "No organization ID provided in request" });
|
||||
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
scope: OrganizationActionScope.Any,
|
||||
actor,
|
||||
actorId,
|
||||
actorOrgId,
|
||||
orgId: actorOrgId,
|
||||
actorAuthMethod,
|
||||
actorOrgId
|
||||
);
|
||||
});
|
||||
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionGroupActions.Read, OrgPermissionSubjects.Groups);
|
||||
|
||||
const group = await groupDAL.findById(id);
|
||||
if (!group) {
|
||||
if (!group || group.orgId !== actorOrgId) {
|
||||
throw new NotFoundError({
|
||||
message: `Cannot find group with ID ${id}`
|
||||
});
|
||||
@@ -309,13 +334,14 @@ export const groupServiceFactory = ({
|
||||
}: TListGroupUsersDTO) => {
|
||||
if (!actorOrgId) throw new UnauthorizedError({ message: "No organization ID provided in request" });
|
||||
|
||||
const { permission } = await permissionService.getOrgPermission(
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
scope: OrganizationActionScope.Any,
|
||||
actor,
|
||||
actorId,
|
||||
actorOrgId,
|
||||
orgId: actorOrgId,
|
||||
actorAuthMethod,
|
||||
actorOrgId
|
||||
);
|
||||
});
|
||||
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionGroupActions.Read, OrgPermissionSubjects.Groups);
|
||||
|
||||
const group = await groupDAL.findOne({
|
||||
@@ -344,13 +370,14 @@ export const groupServiceFactory = ({
|
||||
const addUserToGroup = async ({ id, username, actor, actorId, actorAuthMethod, actorOrgId }: TAddUserToGroupDTO) => {
|
||||
if (!actorOrgId) throw new UnauthorizedError({ message: "No organization ID provided in request" });
|
||||
|
||||
const { permission, membership } = await permissionService.getOrgPermission(
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
scope: OrganizationActionScope.Any,
|
||||
actor,
|
||||
actorId,
|
||||
actorOrgId,
|
||||
orgId: actorOrgId,
|
||||
actorAuthMethod,
|
||||
actorOrgId
|
||||
);
|
||||
});
|
||||
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionGroupActions.Edit, OrgPermissionSubjects.Groups);
|
||||
|
||||
// check if group with slug exists
|
||||
@@ -376,22 +403,23 @@ export const groupServiceFactory = ({
|
||||
});
|
||||
}
|
||||
|
||||
const { permission: groupRolePermission } = await permissionService.getOrgPermissionByRole(group.role, actorOrgId);
|
||||
const [rolePermissionDetails] = await permissionService.getOrgPermissionByRoles([group.role], actorOrgId);
|
||||
const { shouldUseNewPrivilegeSystem } = await orgDAL.findById(actorOrgId);
|
||||
|
||||
// check if user has broader or equal to privileges than group
|
||||
const permissionBoundary = validatePrivilegeChangeOperation(
|
||||
membership.shouldUseNewPrivilegeSystem,
|
||||
shouldUseNewPrivilegeSystem,
|
||||
OrgPermissionGroupActions.AddMembers,
|
||||
OrgPermissionSubjects.Groups,
|
||||
permission,
|
||||
groupRolePermission
|
||||
rolePermissionDetails.permission
|
||||
);
|
||||
|
||||
if (!permissionBoundary.isValid)
|
||||
throw new PermissionBoundaryError({
|
||||
message: constructPermissionErrorMessage(
|
||||
"Failed to add user to more privileged group",
|
||||
membership.shouldUseNewPrivilegeSystem,
|
||||
shouldUseNewPrivilegeSystem,
|
||||
OrgPermissionGroupActions.AddMembers,
|
||||
OrgPermissionSubjects.Groups
|
||||
),
|
||||
@@ -410,17 +438,12 @@ export const groupServiceFactory = ({
|
||||
userDAL,
|
||||
userGroupMembershipDAL,
|
||||
orgDAL,
|
||||
groupProjectDAL,
|
||||
membershipGroupDAL,
|
||||
projectKeyDAL,
|
||||
projectDAL,
|
||||
projectBotDAL
|
||||
});
|
||||
|
||||
const groupProjects = await groupProjectDAL.find({ groupId: group.id });
|
||||
await Promise.allSettled([
|
||||
...groupProjects.map((groupProject) => permissionService.invalidateProjectPermissionCache(groupProject.projectId))
|
||||
]);
|
||||
|
||||
return users[0];
|
||||
};
|
||||
|
||||
@@ -434,13 +457,14 @@ export const groupServiceFactory = ({
|
||||
}: TRemoveUserFromGroupDTO) => {
|
||||
if (!actorOrgId) throw new UnauthorizedError({ message: "No organization ID provided in request" });
|
||||
|
||||
const { permission, membership } = await permissionService.getOrgPermission(
|
||||
const { permission } = await permissionService.getOrgPermission({
|
||||
actor,
|
||||
actorId,
|
||||
actorOrgId,
|
||||
orgId: actorOrgId,
|
||||
actorAuthMethod,
|
||||
actorOrgId
|
||||
);
|
||||
actorOrgId,
|
||||
scope: OrganizationActionScope.Any
|
||||
});
|
||||
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionGroupActions.Edit, OrgPermissionSubjects.Groups);
|
||||
|
||||
// check if group with slug exists
|
||||
@@ -466,21 +490,22 @@ export const groupServiceFactory = ({
|
||||
});
|
||||
}
|
||||
|
||||
const { permission: groupRolePermission } = await permissionService.getOrgPermissionByRole(group.role, actorOrgId);
|
||||
const [rolePermissionDetails] = await permissionService.getOrgPermissionByRoles([group.role], actorOrgId);
|
||||
const { shouldUseNewPrivilegeSystem } = await orgDAL.findById(actorOrgId);
|
||||
|
||||
// check if user has broader or equal to privileges than group
|
||||
const permissionBoundary = validatePrivilegeChangeOperation(
|
||||
membership.shouldUseNewPrivilegeSystem,
|
||||
shouldUseNewPrivilegeSystem,
|
||||
OrgPermissionGroupActions.RemoveMembers,
|
||||
OrgPermissionSubjects.Groups,
|
||||
permission,
|
||||
groupRolePermission
|
||||
rolePermissionDetails.permission
|
||||
);
|
||||
if (!permissionBoundary.isValid)
|
||||
throw new PermissionBoundaryError({
|
||||
message: constructPermissionErrorMessage(
|
||||
"Failed to delete user from more privileged group",
|
||||
membership.shouldUseNewPrivilegeSystem,
|
||||
shouldUseNewPrivilegeSystem,
|
||||
OrgPermissionGroupActions.RemoveMembers,
|
||||
OrgPermissionSubjects.Groups
|
||||
),
|
||||
@@ -498,15 +523,10 @@ export const groupServiceFactory = ({
|
||||
userIds: [user.id],
|
||||
userDAL,
|
||||
userGroupMembershipDAL,
|
||||
groupProjectDAL,
|
||||
membershipGroupDAL,
|
||||
projectKeyDAL
|
||||
});
|
||||
|
||||
const groupProjects = await groupProjectDAL.find({ groupId: group.id });
|
||||
await Promise.allSettled([
|
||||
...groupProjects.map((groupProject) => permissionService.invalidateProjectPermissionCache(groupProject.projectId))
|
||||
]);
|
||||
|
||||
return users[0];
|
||||
};
|
||||
|
||||
|
||||
@@ -3,7 +3,7 @@ import { Knex } from "knex";
|
||||
import { TGroups } from "@app/db/schemas";
|
||||
import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
|
||||
import { TGenericPermission } from "@app/lib/types";
|
||||
import { TGroupProjectDALFactory } from "@app/services/group-project/group-project-dal";
|
||||
import { TMembershipGroupDALFactory } from "@app/services/membership-group/membership-group-dal";
|
||||
import { TOrgDALFactory } from "@app/services/org/org-dal";
|
||||
import { TProjectDALFactory } from "@app/services/project/project-dal";
|
||||
import { TProjectBotDALFactory } from "@app/services/project-bot/project-bot-dal";
|
||||
@@ -63,7 +63,7 @@ export type TAddUsersToGroup = {
|
||||
group: TGroups;
|
||||
userDAL: Pick<TUserDALFactory, "findUserEncKeyByUserIdsBatch">;
|
||||
userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find" | "transaction" | "insertMany">;
|
||||
groupProjectDAL: Pick<TGroupProjectDALFactory, "find">;
|
||||
membershipGroupDAL: Pick<TMembershipGroupDALFactory, "find">;
|
||||
projectKeyDAL: Pick<TProjectKeyDALFactory, "find" | "findLatestProjectKey" | "insertMany">;
|
||||
projectDAL: Pick<TProjectDALFactory, "findProjectGhostUser" | "findById">;
|
||||
projectBotDAL: Pick<TProjectBotDALFactory, "findOne">;
|
||||
@@ -76,7 +76,7 @@ export type TAddUsersToGroupByUserIds = {
|
||||
userDAL: Pick<TUserDALFactory, "find" | "findUserEncKeyByUserIdsBatch" | "transaction">;
|
||||
userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find" | "transaction" | "insertMany">;
|
||||
orgDAL: Pick<TOrgDALFactory, "findMembership">;
|
||||
groupProjectDAL: Pick<TGroupProjectDALFactory, "find">;
|
||||
membershipGroupDAL: Pick<TMembershipGroupDALFactory, "find">;
|
||||
projectKeyDAL: Pick<TProjectKeyDALFactory, "find" | "findLatestProjectKey" | "insertMany">;
|
||||
projectDAL: Pick<TProjectDALFactory, "findProjectGhostUser" | "findById">;
|
||||
projectBotDAL: Pick<TProjectBotDALFactory, "findOne">;
|
||||
@@ -88,7 +88,7 @@ export type TRemoveUsersFromGroupByUserIds = {
|
||||
userIds: string[];
|
||||
userDAL: Pick<TUserDALFactory, "find" | "transaction">;
|
||||
userGroupMembershipDAL: Pick<TUserGroupMembershipDALFactory, "find" | "filterProjectsByUserMembership" | "delete">;
|
||||
groupProjectDAL: Pick<TGroupProjectDALFactory, "find">;
|
||||
membershipGroupDAL: Pick<TMembershipGroupDALFactory, "find">;
|
||||
projectKeyDAL: Pick<TProjectKeyDALFactory, "delete">;
|
||||
tx?: Knex;
|
||||
};
|
||||
@@ -100,7 +100,7 @@ export type TConvertPendingGroupAdditionsToGroupMemberships = {
|
||||
TUserGroupMembershipDALFactory,
|
||||
"find" | "transaction" | "insertMany" | "deletePendingUserGroupMembershipsByUserIds"
|
||||
>;
|
||||
groupProjectDAL: Pick<TGroupProjectDALFactory, "find">;
|
||||
membershipGroupDAL: Pick<TMembershipGroupDALFactory, "find">;
|
||||
projectKeyDAL: Pick<TProjectKeyDALFactory, "find" | "findLatestProjectKey" | "insertMany">;
|
||||
projectDAL: Pick<TProjectDALFactory, "findProjectGhostUser" | "findById">;
|
||||
projectBotDAL: Pick<TProjectBotDALFactory, "findOne">;
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Knex } from "knex";
|
||||
|
||||
import { TDbClient } from "@app/db";
|
||||
import { TableName, TUserEncryptionKeys } from "@app/db/schemas";
|
||||
import { AccessScope, TableName, TUserEncryptionKeys } from "@app/db/schemas";
|
||||
import { DatabaseError } from "@app/lib/errors";
|
||||
import { ormify } from "@app/lib/knex";
|
||||
|
||||
@@ -18,21 +18,19 @@ export const userGroupMembershipDALFactory = (db: TDbClient) => {
|
||||
*/
|
||||
const filterProjectsByUserMembership = async (userId: string, groupId: string, projectIds: string[], tx?: Knex) => {
|
||||
try {
|
||||
const userProjectMemberships: string[] = await (tx || db.replicaNode())(TableName.ProjectMembership)
|
||||
.where(`${TableName.ProjectMembership}.userId`, userId)
|
||||
.whereIn(`${TableName.ProjectMembership}.projectId`, projectIds)
|
||||
.pluck(`${TableName.ProjectMembership}.projectId`);
|
||||
const userProjectMemberships: string[] = await (tx || db.replicaNode())(TableName.Membership)
|
||||
.where(`${TableName.Membership}.actorUserId`, userId)
|
||||
.where(`${TableName.Membership}.scope`, AccessScope.Project)
|
||||
.whereIn(`${TableName.Membership}.scopeProjectId`, projectIds)
|
||||
.pluck(`${TableName.Membership}.scopeProjectId`);
|
||||
|
||||
const userGroupMemberships: string[] = await (tx || db.replicaNode())(TableName.UserGroupMembership)
|
||||
.where(`${TableName.UserGroupMembership}.userId`, userId)
|
||||
.whereNot(`${TableName.UserGroupMembership}.groupId`, groupId)
|
||||
.join(
|
||||
TableName.GroupProjectMembership,
|
||||
`${TableName.UserGroupMembership}.groupId`,
|
||||
`${TableName.GroupProjectMembership}.groupId`
|
||||
)
|
||||
.whereIn(`${TableName.GroupProjectMembership}.projectId`, projectIds)
|
||||
.pluck(`${TableName.GroupProjectMembership}.projectId`);
|
||||
.join(TableName.Membership, `${TableName.UserGroupMembership}.groupId`, `${TableName.Membership}.actorGroupId`)
|
||||
.where(`${TableName.Membership}.scope`, AccessScope.Project)
|
||||
.whereIn(`${TableName.Membership}.scopeProjectId`, projectIds)
|
||||
.pluck(`${TableName.Membership}.scopeProjectId`);
|
||||
|
||||
return new Set(userProjectMemberships.concat(userGroupMemberships));
|
||||
} catch (error) {
|
||||
@@ -44,13 +42,10 @@ export const userGroupMembershipDALFactory = (db: TDbClient) => {
|
||||
const findUserGroupMembershipsInProject = async (usernames: string[], projectId: string, tx?: Knex) => {
|
||||
try {
|
||||
const usernameDocs: string[] = await (tx || db.replicaNode())(TableName.UserGroupMembership)
|
||||
.join(
|
||||
TableName.GroupProjectMembership,
|
||||
`${TableName.UserGroupMembership}.groupId`,
|
||||
`${TableName.GroupProjectMembership}.groupId`
|
||||
)
|
||||
.join(TableName.Membership, `${TableName.UserGroupMembership}.groupId`, `${TableName.Membership}.actorGroupId`)
|
||||
.where(`${TableName.Membership}.scope`, AccessScope.Project)
|
||||
.join(TableName.Users, `${TableName.UserGroupMembership}.userId`, `${TableName.Users}.id`)
|
||||
.where(`${TableName.GroupProjectMembership}.projectId`, projectId)
|
||||
.where(`${TableName.Membership}.scopeProjectId`, projectId)
|
||||
.whereIn(`${TableName.Users}.username`, usernames)
|
||||
.pluck(`${TableName.Users}.id`);
|
||||
|
||||
@@ -73,24 +68,25 @@ export const userGroupMembershipDALFactory = (db: TDbClient) => {
|
||||
try {
|
||||
// get list of groups in the project with id [projectId]
|
||||
// that that are not the group with id [groupId]
|
||||
const groups: string[] = await (tx || db.replicaNode())(TableName.GroupProjectMembership)
|
||||
.where(`${TableName.GroupProjectMembership}.projectId`, projectId)
|
||||
.whereNot(`${TableName.GroupProjectMembership}.groupId`, groupId)
|
||||
.pluck(`${TableName.GroupProjectMembership}.groupId`);
|
||||
const groups: string[] = await (tx || db.replicaNode())(TableName.Membership)
|
||||
.where(`${TableName.Membership}.scopeProjectId`, projectId)
|
||||
.whereNot(`${TableName.Membership}.actorGroupId`, groupId)
|
||||
.pluck(`${TableName.Membership}.actorGroupId`);
|
||||
|
||||
// main query
|
||||
const members = await (tx || db.replicaNode())(TableName.UserGroupMembership)
|
||||
.where(`${TableName.UserGroupMembership}.groupId`, groupId)
|
||||
.where(`${TableName.UserGroupMembership}.isPending`, false)
|
||||
.join(TableName.Users, `${TableName.UserGroupMembership}.userId`, `${TableName.Users}.id`)
|
||||
.leftJoin(TableName.ProjectMembership, (bd) => {
|
||||
bd.on(`${TableName.Users}.id`, "=", `${TableName.ProjectMembership}.userId`).andOn(
|
||||
`${TableName.ProjectMembership}.projectId`,
|
||||
.leftJoin(TableName.Membership, (bd) => {
|
||||
bd.on(`${TableName.Users}.id`, "=", `${TableName.Membership}.actorUserId`).andOn(
|
||||
`${TableName.Membership}.scopeProjectId`,
|
||||
"=",
|
||||
db.raw("?", [projectId])
|
||||
);
|
||||
})
|
||||
.whereNull(`${TableName.ProjectMembership}.userId`)
|
||||
.whereNull(`${TableName.Membership}.actorUserId`)
|
||||
.where(`${TableName.Membership}.scope`, AccessScope.Project)
|
||||
.leftJoin<TUserEncryptionKeys>(
|
||||
TableName.UserEncryptionKey,
|
||||
`${TableName.UserEncryptionKey}.userId`,
|
||||
@@ -166,15 +162,17 @@ export const userGroupMembershipDALFactory = (db: TDbClient) => {
|
||||
const docs = await db
|
||||
.replicaNode()(TableName.UserGroupMembership)
|
||||
.join(TableName.Groups, `${TableName.UserGroupMembership}.groupId`, `${TableName.Groups}.id`)
|
||||
.join(TableName.OrgMembership, `${TableName.UserGroupMembership}.userId`, `${TableName.OrgMembership}.userId`)
|
||||
.join(TableName.Membership, `${TableName.UserGroupMembership}.userId`, `${TableName.Membership}.actorUserId`)
|
||||
.join(TableName.Users, `${TableName.UserGroupMembership}.userId`, `${TableName.Users}.id`)
|
||||
.where(`${TableName.UserGroupMembership}.userId`, userId)
|
||||
.where(`${TableName.Membership}.scope`, AccessScope.Organization)
|
||||
.where(`${TableName.Membership}.scopeOrgId`, orgId)
|
||||
.where(`${TableName.Groups}.orgId`, orgId)
|
||||
.select(
|
||||
db.ref("id").withSchema(TableName.UserGroupMembership),
|
||||
db.ref("groupId").withSchema(TableName.UserGroupMembership),
|
||||
db.ref("name").withSchema(TableName.Groups).as("groupName"),
|
||||
db.ref("id").withSchema(TableName.OrgMembership).as("orgMembershipId"),
|
||||
db.ref("id").withSchema(TableName.Membership).as("orgMembershipId"),
|
||||
db.ref("firstName").withSchema(TableName.Users).as("firstName"),
|
||||
db.ref("lastName").withSchema(TableName.Users).as("lastName"),
|
||||
db.ref("slug").withSchema(TableName.Groups).as("groupSlug")
|
||||
@@ -191,15 +189,17 @@ export const userGroupMembershipDALFactory = (db: TDbClient) => {
|
||||
const docs = await db
|
||||
.replicaNode()(TableName.UserGroupMembership)
|
||||
.join(TableName.Groups, `${TableName.UserGroupMembership}.groupId`, `${TableName.Groups}.id`)
|
||||
.join(TableName.OrgMembership, `${TableName.UserGroupMembership}.userId`, `${TableName.OrgMembership}.userId`)
|
||||
.join(TableName.Membership, `${TableName.UserGroupMembership}.userId`, `${TableName.Membership}.actorUserId`)
|
||||
.join(TableName.Users, `${TableName.UserGroupMembership}.userId`, `${TableName.Users}.id`)
|
||||
.where(`${TableName.Groups}.id`, groupId)
|
||||
.where(`${TableName.Membership}.scope`, AccessScope.Organization)
|
||||
.where(`${TableName.Membership}.scopeOrgId`, orgId)
|
||||
.where(`${TableName.Groups}.orgId`, orgId)
|
||||
.select(
|
||||
db.ref("id").withSchema(TableName.UserGroupMembership),
|
||||
db.ref("groupId").withSchema(TableName.UserGroupMembership),
|
||||
db.ref("name").withSchema(TableName.Groups).as("groupName"),
|
||||
db.ref("id").withSchema(TableName.OrgMembership).as("orgMembershipId"),
|
||||
db.ref("id").withSchema(TableName.Membership).as("orgMembershipId"),
|
||||
db.ref("firstName").withSchema(TableName.Users).as("firstName"),
|
||||
db.ref("lastName").withSchema(TableName.Users).as("lastName")
|
||||
);
|
||||
|
||||
@@ -1,8 +1,14 @@
|
||||
import * as pkcs11js from "pkcs11js";
|
||||
|
||||
import { TEnvConfig } from "@app/lib/config/env";
|
||||
import { BadRequestError } from "@app/lib/errors";
|
||||
import { logger } from "@app/lib/logger";
|
||||
import { KMS_ROOT_CONFIG_UUID } from "@app/services/kms/kms-fns";
|
||||
import { TKmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";
|
||||
import { RootKeyEncryptionStrategy } from "@app/services/kms/kms-types";
|
||||
|
||||
import { TLicenseServiceFactory } from "../license/license-service";
|
||||
import { THsmServiceFactory } from "./hsm-service";
|
||||
import { HsmModule } from "./hsm-types";
|
||||
|
||||
export const initializeHsmModule = (envConfig: Pick<TEnvConfig, "isHsmConfigured" | "HSM_LIB_PATH">) => {
|
||||
@@ -25,8 +31,9 @@ export const initializeHsmModule = (envConfig: Pick<TEnvConfig, "isHsmConfigured
|
||||
|
||||
logger.info("PKCS#11 module initialized");
|
||||
} catch (error) {
|
||||
if (error instanceof pkcs11js.Pkcs11Error && error.code === pkcs11js.CKR_CRYPTOKI_ALREADY_INITIALIZED) {
|
||||
if ((error as { message?: string })?.message === "CKR_CRYPTOKI_ALREADY_INITIALIZED") {
|
||||
logger.info("Skipping HSM initialization because it's already initialized.");
|
||||
isInitialized = true;
|
||||
} else {
|
||||
logger.error(error, "Failed to initialize PKCS#11 module");
|
||||
throw error;
|
||||
@@ -58,3 +65,36 @@ export const initializeHsmModule = (envConfig: Pick<TEnvConfig, "isHsmConfigured
|
||||
getModule
|
||||
};
|
||||
};
|
||||
|
||||
export const isHsmActiveAndEnabled = async ({
|
||||
hsmService,
|
||||
kmsRootConfigDAL,
|
||||
licenseService
|
||||
}: {
|
||||
hsmService: Pick<THsmServiceFactory, "isActive">;
|
||||
kmsRootConfigDAL: Pick<TKmsRootConfigDALFactory, "findById">;
|
||||
licenseService?: Pick<TLicenseServiceFactory, "onPremFeatures">;
|
||||
}) => {
|
||||
const isHsmConfigured = await hsmService.isActive();
|
||||
|
||||
// null if the root kms config does not exist
|
||||
let rootKmsConfigEncryptionStrategy: RootKeyEncryptionStrategy | null = null;
|
||||
|
||||
const rootKmsConfig = await kmsRootConfigDAL.findById(KMS_ROOT_CONFIG_UUID).catch(() => null);
|
||||
|
||||
rootKmsConfigEncryptionStrategy = (rootKmsConfig?.encryptionStrategy || null) as RootKeyEncryptionStrategy | null;
|
||||
if (
|
||||
rootKmsConfigEncryptionStrategy === RootKeyEncryptionStrategy.HSM &&
|
||||
licenseService &&
|
||||
!licenseService.onPremFeatures.hsm
|
||||
) {
|
||||
throw new BadRequestError({
|
||||
message: "Your license does not include HSM integration. Please upgrade to the Enterprise plan to use HSM."
|
||||
});
|
||||
}
|
||||
|
||||
return {
|
||||
rootKmsConfigEncryptionStrategy,
|
||||
isHsmConfigured
|
||||
};
|
||||
};
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user