mirror of
https://github.com/Infisical/infisical.git
synced 2025-07-02 16:55:02 +00:00
Compare commits
195 Commits
docs/ident
...
daniel/rub
Author | SHA1 | Date | |
---|---|---|---|
1e5d567ef7 | |||
d09c320150 | |||
229599b8de | |||
7dd9337b1c | |||
f9eaee4dbc | |||
cd3a64f3e7 | |||
121254f98d | |||
1591c1dbac | |||
3c59d288c4 | |||
632b775d7f | |||
d66da3d770 | |||
da43f405c4 | |||
d5c0abbc3b | |||
7a642e7634 | |||
de686acc23 | |||
b359f4278e | |||
29d76c1deb | |||
6ba1012f5b | |||
4abb3ef348 | |||
73e764474d | |||
7eb5689b4c | |||
5d945f432d | |||
1066710c4f | |||
b64d4e57c4 | |||
bd860e6c5a | |||
37137b8c68 | |||
8b10cf863d | |||
eb45bed7d9 | |||
1ee65205a0 | |||
f41272d4df | |||
8bf4df9f27 | |||
037a8f2ebb | |||
14bc436283 | |||
a108c7dde1 | |||
54ccd73d2a | |||
729ca7b6d6 | |||
754db67f11 | |||
f97756a07b | |||
22df51ab8e | |||
bff8f55ea2 | |||
2f17f5e7df | |||
72d2247bf2 | |||
4ecd4c0337 | |||
538613dd40 | |||
4c5c24f689 | |||
dead16a98a | |||
224368b172 | |||
3731459e99 | |||
dc055c11ab | |||
22878a035b | |||
2f2c9d4508 | |||
774017adbe | |||
f9d1d9c89f | |||
eb82fc0d9a | |||
e45585a909 | |||
6f0484f074 | |||
4ba529f22d | |||
5360fb033a | |||
27e14bcafe | |||
bc5003ae4c | |||
f544b39597 | |||
8381f52f1e | |||
aa96a833d7 | |||
53c64b759c | |||
74f2224c6b | |||
ecb5342a55 | |||
bcb657b81e | |||
ebe6b08cab | |||
43b14d0091 | |||
7127f6d1e1 | |||
20387cff35 | |||
997d7f22fc | |||
e1ecad2331 | |||
ce26a06129 | |||
7622cac07e | |||
a101602e0a | |||
ca63a7baa7 | |||
ff4f15c437 | |||
d6c2715852 | |||
fc386c0cbc | |||
263a88379f | |||
4b718b679a | |||
498b1109c9 | |||
b70bf4cadb | |||
d301f74feb | |||
454826fbb6 | |||
f464d7a096 | |||
cae9ace1ca | |||
8a5a295a01 | |||
95a4661787 | |||
7e9c846ba3 | |||
aed310b9ee | |||
c331af5345 | |||
d4dd684f32 | |||
1f6c33bdb8 | |||
a538e37a62 | |||
f3f87cfd84 | |||
2c57bd94fb | |||
869fcd6541 | |||
7b3e116bf8 | |||
0a95f6dc1d | |||
d19c856e9b | |||
ada0033bd0 | |||
6818c8730f | |||
8542ec8c3e | |||
c141b916d3 | |||
b09dddec1c | |||
1ae375188b | |||
22b954b657 | |||
9efeb8926f | |||
389bbfcade | |||
0b8427a004 | |||
8a470772e3 | |||
853f3c40bc | |||
fed44f328d | |||
a1d00f2c41 | |||
1d6d424c91 | |||
c39ea130b1 | |||
95a68f2c2d | |||
db7c0c45f6 | |||
82bca03162 | |||
043c04778f | |||
560cd81a1c | |||
df3a87fabf | |||
6eae98c1d4 | |||
6ceeccf583 | |||
9b0b14b847 | |||
78f4c0f002 | |||
6cff2f0437 | |||
6cefb180d6 | |||
59a44155c5 | |||
d0ad9c6b17 | |||
58a406b114 | |||
8a85695dc5 | |||
7ed8feee6f | |||
de67c0ad9f | |||
b8d11d31a6 | |||
d630ceaffe | |||
a89e60f296 | |||
a5d9abf1c8 | |||
d97dea2573 | |||
bc58f6b988 | |||
ed8e3f34fb | |||
91315c88c3 | |||
9267f881d6 | |||
c2ddb7e2fe | |||
5514508482 | |||
5921dcaa51 | |||
c90ecd336c | |||
d8b1da3ddd | |||
58e86382fe | |||
b2c62c4193 | |||
2080c4419e | |||
b582a4a06d | |||
a5c6a864de | |||
5082c1ba3b | |||
cceb08b1b5 | |||
4c34e58945 | |||
72de1901a1 | |||
65fefcdd87 | |||
8e753eda72 | |||
7137c94fa2 | |||
52ea7dfa61 | |||
093925ed0e | |||
356afd18c4 | |||
4491f2d8f1 | |||
4a401957c7 | |||
539785acae | |||
3c63346d3a | |||
0c673f6cca | |||
10f4cbf11f | |||
a6a8c32326 | |||
99a474dba7 | |||
e439f4e5aa | |||
ae2ecf1540 | |||
10214ea5dc | |||
918cd414a8 | |||
f9a125acee | |||
ef5bcac925 | |||
6cbeb29b4e | |||
fbe344c0df | |||
5821f65a63 | |||
93af7573ac | |||
cddda1148e | |||
9c37eeeda6 | |||
eadf5bef77 | |||
c501c85eb8 | |||
5d4c7c2cbf | |||
08f0bf9c67 | |||
654dd97793 | |||
2e7baf8c89 | |||
7ca7a95070 | |||
71c49c8b90 | |||
9832915eba | |||
b98c8629e5 |
1062
backend/package-lock.json
generated
1062
backend/package-lock.json
generated
File diff suppressed because it is too large
Load Diff
@ -106,6 +106,7 @@
|
|||||||
},
|
},
|
||||||
"dependencies": {
|
"dependencies": {
|
||||||
"@aws-sdk/client-iam": "^3.525.0",
|
"@aws-sdk/client-iam": "^3.525.0",
|
||||||
|
"@aws-sdk/client-kms": "^3.609.0",
|
||||||
"@aws-sdk/client-secrets-manager": "^3.504.0",
|
"@aws-sdk/client-secrets-manager": "^3.504.0",
|
||||||
"@aws-sdk/client-sts": "^3.600.0",
|
"@aws-sdk/client-sts": "^3.600.0",
|
||||||
"@casl/ability": "^6.5.0",
|
"@casl/ability": "^6.5.0",
|
||||||
|
2
backend/src/@types/fastify.d.ts
vendored
2
backend/src/@types/fastify.d.ts
vendored
@ -9,6 +9,7 @@ import { TAuditLogStreamServiceFactory } from "@app/ee/services/audit-log-stream
|
|||||||
import { TCertificateAuthorityCrlServiceFactory } from "@app/ee/services/certificate-authority-crl/certificate-authority-crl-service";
|
import { TCertificateAuthorityCrlServiceFactory } from "@app/ee/services/certificate-authority-crl/certificate-authority-crl-service";
|
||||||
import { TDynamicSecretServiceFactory } from "@app/ee/services/dynamic-secret/dynamic-secret-service";
|
import { TDynamicSecretServiceFactory } from "@app/ee/services/dynamic-secret/dynamic-secret-service";
|
||||||
import { TDynamicSecretLeaseServiceFactory } from "@app/ee/services/dynamic-secret-lease/dynamic-secret-lease-service";
|
import { TDynamicSecretLeaseServiceFactory } from "@app/ee/services/dynamic-secret-lease/dynamic-secret-lease-service";
|
||||||
|
import { TExternalKmsServiceFactory } from "@app/ee/services/external-kms/external-kms-service";
|
||||||
import { TGroupServiceFactory } from "@app/ee/services/group/group-service";
|
import { TGroupServiceFactory } from "@app/ee/services/group/group-service";
|
||||||
import { TIdentityProjectAdditionalPrivilegeServiceFactory } from "@app/ee/services/identity-project-additional-privilege/identity-project-additional-privilege-service";
|
import { TIdentityProjectAdditionalPrivilegeServiceFactory } from "@app/ee/services/identity-project-additional-privilege/identity-project-additional-privilege-service";
|
||||||
import { TLdapConfigServiceFactory } from "@app/ee/services/ldap-config/ldap-config-service";
|
import { TLdapConfigServiceFactory } from "@app/ee/services/ldap-config/ldap-config-service";
|
||||||
@ -163,6 +164,7 @@ declare module "fastify" {
|
|||||||
secretSharing: TSecretSharingServiceFactory;
|
secretSharing: TSecretSharingServiceFactory;
|
||||||
rateLimit: TRateLimitServiceFactory;
|
rateLimit: TRateLimitServiceFactory;
|
||||||
userEngagement: TUserEngagementServiceFactory;
|
userEngagement: TUserEngagementServiceFactory;
|
||||||
|
externalKms: TExternalKmsServiceFactory;
|
||||||
};
|
};
|
||||||
// this is exclusive use for middlewares in which we need to inject data
|
// this is exclusive use for middlewares in which we need to inject data
|
||||||
// everywhere else access using service layer
|
// everywhere else access using service layer
|
||||||
|
8
backend/src/@types/knex.d.ts
vendored
8
backend/src/@types/knex.d.ts
vendored
@ -59,6 +59,9 @@ import {
|
|||||||
TDynamicSecrets,
|
TDynamicSecrets,
|
||||||
TDynamicSecretsInsert,
|
TDynamicSecretsInsert,
|
||||||
TDynamicSecretsUpdate,
|
TDynamicSecretsUpdate,
|
||||||
|
TExternalKms,
|
||||||
|
TExternalKmsInsert,
|
||||||
|
TExternalKmsUpdate,
|
||||||
TGitAppInstallSessions,
|
TGitAppInstallSessions,
|
||||||
TGitAppInstallSessionsInsert,
|
TGitAppInstallSessionsInsert,
|
||||||
TGitAppInstallSessionsUpdate,
|
TGitAppInstallSessionsUpdate,
|
||||||
@ -125,6 +128,9 @@ import {
|
|||||||
TIntegrations,
|
TIntegrations,
|
||||||
TIntegrationsInsert,
|
TIntegrationsInsert,
|
||||||
TIntegrationsUpdate,
|
TIntegrationsUpdate,
|
||||||
|
TInternalKms,
|
||||||
|
TInternalKmsInsert,
|
||||||
|
TInternalKmsUpdate,
|
||||||
TKmsKeys,
|
TKmsKeys,
|
||||||
TKmsKeysInsert,
|
TKmsKeysInsert,
|
||||||
TKmsKeysUpdate,
|
TKmsKeysUpdate,
|
||||||
@ -656,6 +662,8 @@ declare module "knex/types/tables" {
|
|||||||
TKmsRootConfigInsert,
|
TKmsRootConfigInsert,
|
||||||
TKmsRootConfigUpdate
|
TKmsRootConfigUpdate
|
||||||
>;
|
>;
|
||||||
|
[TableName.InternalKms]: KnexOriginal.CompositeTableType<TInternalKms, TInternalKmsInsert, TInternalKmsUpdate>;
|
||||||
|
[TableName.ExternalKms]: KnexOriginal.CompositeTableType<TExternalKms, TExternalKmsInsert, TExternalKmsUpdate>;
|
||||||
[TableName.KmsKey]: KnexOriginal.CompositeTableType<TKmsKeys, TKmsKeysInsert, TKmsKeysUpdate>;
|
[TableName.KmsKey]: KnexOriginal.CompositeTableType<TKmsKeys, TKmsKeysInsert, TKmsKeysUpdate>;
|
||||||
[TableName.KmsKeyVersion]: KnexOriginal.CompositeTableType<
|
[TableName.KmsKeyVersion]: KnexOriginal.CompositeTableType<
|
||||||
TKmsKeyVersions,
|
TKmsKeyVersions,
|
||||||
|
256
backend/src/db/migrations/20240708100026_external-kms.ts
Normal file
256
backend/src/db/migrations/20240708100026_external-kms.ts
Normal file
@ -0,0 +1,256 @@
|
|||||||
|
import slugify from "@sindresorhus/slugify";
|
||||||
|
import { Knex } from "knex";
|
||||||
|
|
||||||
|
import { alphaNumericNanoId } from "@app/lib/nanoid";
|
||||||
|
|
||||||
|
import { TableName } from "../schemas";
|
||||||
|
|
||||||
|
const createInternalKmsTableAndBackfillData = async (knex: Knex) => {
|
||||||
|
const doesOldKmsKeyTableExist = await knex.schema.hasTable(TableName.KmsKey);
|
||||||
|
const doesInternalKmsTableExist = await knex.schema.hasTable(TableName.InternalKms);
|
||||||
|
|
||||||
|
// building the internal kms table by filling from old kms table
|
||||||
|
if (doesOldKmsKeyTableExist && !doesInternalKmsTableExist) {
|
||||||
|
await knex.schema.createTable(TableName.InternalKms, (tb) => {
|
||||||
|
tb.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
|
||||||
|
tb.binary("encryptedKey").notNullable();
|
||||||
|
tb.string("encryptionAlgorithm").notNullable();
|
||||||
|
tb.integer("version").defaultTo(1).notNullable();
|
||||||
|
tb.uuid("kmsKeyId").unique().notNullable();
|
||||||
|
tb.foreign("kmsKeyId").references("id").inTable(TableName.KmsKey).onDelete("CASCADE");
|
||||||
|
});
|
||||||
|
|
||||||
|
// copy the old kms and backfill
|
||||||
|
const oldKmsKey = await knex(TableName.KmsKey).select("version", "encryptedKey", "encryptionAlgorithm", "id");
|
||||||
|
if (oldKmsKey.length) {
|
||||||
|
await knex(TableName.InternalKms).insert(
|
||||||
|
oldKmsKey.map((el) => ({
|
||||||
|
encryptionAlgorithm: el.encryptionAlgorithm,
|
||||||
|
encryptedKey: el.encryptedKey,
|
||||||
|
kmsKeyId: el.id,
|
||||||
|
version: el.version
|
||||||
|
}))
|
||||||
|
);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const renameKmsKeyVersionTableAsInternalKmsKeyVersion = async (knex: Knex) => {
|
||||||
|
const doesOldKmsKeyVersionTableExist = await knex.schema.hasTable(TableName.KmsKeyVersion);
|
||||||
|
const doesNewKmsKeyVersionTableExist = await knex.schema.hasTable(TableName.InternalKmsKeyVersion);
|
||||||
|
|
||||||
|
if (doesOldKmsKeyVersionTableExist && !doesNewKmsKeyVersionTableExist) {
|
||||||
|
// because we haven't started using versioning for kms thus no data exist
|
||||||
|
await knex.schema.renameTable(TableName.KmsKeyVersion, TableName.InternalKmsKeyVersion);
|
||||||
|
const hasKmsKeyIdColumn = await knex.schema.hasColumn(TableName.InternalKmsKeyVersion, "kmsKeyId");
|
||||||
|
const hasInternalKmsIdColumn = await knex.schema.hasColumn(TableName.InternalKmsKeyVersion, "internalKmsId");
|
||||||
|
|
||||||
|
await knex.schema.alterTable(TableName.InternalKmsKeyVersion, (tb) => {
|
||||||
|
if (hasKmsKeyIdColumn) tb.dropColumn("kmsKeyId");
|
||||||
|
if (!hasInternalKmsIdColumn) {
|
||||||
|
tb.uuid("internalKmsId").notNullable();
|
||||||
|
tb.foreign("internalKmsId").references("id").inTable(TableName.InternalKms).onDelete("CASCADE");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const createExternalKmsKeyTable = async (knex: Knex) => {
|
||||||
|
const doesExternalKmsServiceExist = await knex.schema.hasTable(TableName.ExternalKms);
|
||||||
|
if (!doesExternalKmsServiceExist) {
|
||||||
|
await knex.schema.createTable(TableName.ExternalKms, (tb) => {
|
||||||
|
tb.uuid("id", { primaryKey: true }).defaultTo(knex.fn.uuid());
|
||||||
|
tb.string("provider").notNullable();
|
||||||
|
tb.binary("encryptedProviderInputs").notNullable();
|
||||||
|
tb.string("status");
|
||||||
|
tb.string("statusDetails");
|
||||||
|
tb.uuid("kmsKeyId").unique().notNullable();
|
||||||
|
tb.foreign("kmsKeyId").references("id").inTable(TableName.KmsKey).onDelete("CASCADE");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const removeNonRequiredFieldsFromKmsKeyTableAndBackfillRequiredData = async (knex: Knex) => {
|
||||||
|
const doesOldKmsKeyTableExist = await knex.schema.hasTable(TableName.KmsKey);
|
||||||
|
|
||||||
|
// building the internal kms table by filling from old kms table
|
||||||
|
if (doesOldKmsKeyTableExist) {
|
||||||
|
const hasSlugColumn = await knex.schema.hasColumn(TableName.KmsKey, "slug");
|
||||||
|
const hasEncryptedKeyColumn = await knex.schema.hasColumn(TableName.KmsKey, "encryptedKey");
|
||||||
|
const hasEncryptionAlgorithmColumn = await knex.schema.hasColumn(TableName.KmsKey, "encryptionAlgorithm");
|
||||||
|
const hasVersionColumn = await knex.schema.hasColumn(TableName.KmsKey, "version");
|
||||||
|
const hasTimestamps = await knex.schema.hasColumn(TableName.KmsKey, "createdAt");
|
||||||
|
const hasProjectId = await knex.schema.hasColumn(TableName.KmsKey, "projectId");
|
||||||
|
const hasOrgId = await knex.schema.hasColumn(TableName.KmsKey, "orgId");
|
||||||
|
|
||||||
|
await knex.schema.alterTable(TableName.KmsKey, (tb) => {
|
||||||
|
if (!hasSlugColumn) tb.string("slug", 32);
|
||||||
|
if (hasEncryptedKeyColumn) tb.dropColumn("encryptedKey");
|
||||||
|
if (hasEncryptionAlgorithmColumn) tb.dropColumn("encryptionAlgorithm");
|
||||||
|
if (hasVersionColumn) tb.dropColumn("version");
|
||||||
|
if (!hasTimestamps) tb.timestamps(true, true, true);
|
||||||
|
});
|
||||||
|
|
||||||
|
// backfill all org id in kms key because its gonna be changed to non nullable
|
||||||
|
if (hasProjectId && hasOrgId) {
|
||||||
|
await knex(TableName.KmsKey)
|
||||||
|
.whereNull("orgId")
|
||||||
|
.update({
|
||||||
|
// eslint-disable-next-line
|
||||||
|
// @ts-ignore because generate schema happens after this
|
||||||
|
orgId: knex(TableName.Project)
|
||||||
|
.select("orgId")
|
||||||
|
.where("id", knex.raw("??", [`${TableName.KmsKey}.projectId`]))
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// backfill slugs in kms
|
||||||
|
const missingSlugs = await knex(TableName.KmsKey).whereNull("slug").select("id");
|
||||||
|
if (missingSlugs.length) {
|
||||||
|
await knex(TableName.KmsKey)
|
||||||
|
// eslint-disable-next-line
|
||||||
|
// @ts-ignore because generate schema happens after this
|
||||||
|
.insert(missingSlugs.map(({ id }) => ({ id, slug: slugify(alphaNumericNanoId(8).toLowerCase()) })))
|
||||||
|
.onConflict("id")
|
||||||
|
.merge();
|
||||||
|
}
|
||||||
|
|
||||||
|
await knex.schema.alterTable(TableName.KmsKey, (tb) => {
|
||||||
|
if (hasOrgId) tb.uuid("orgId").notNullable().alter();
|
||||||
|
tb.string("slug", 32).notNullable().alter();
|
||||||
|
if (hasProjectId) tb.dropColumn("projectId");
|
||||||
|
if (hasOrgId) tb.unique(["orgId", "slug"]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
/*
|
||||||
|
* The goal for this migration is split the existing kms key into three table
|
||||||
|
* the kms-key table would be a container table that contains
|
||||||
|
* the internal kms key table and external kms table
|
||||||
|
*/
|
||||||
|
export async function up(knex: Knex): Promise<void> {
|
||||||
|
await createInternalKmsTableAndBackfillData(knex);
|
||||||
|
await renameKmsKeyVersionTableAsInternalKmsKeyVersion(knex);
|
||||||
|
await removeNonRequiredFieldsFromKmsKeyTableAndBackfillRequiredData(knex);
|
||||||
|
await createExternalKmsKeyTable(knex);
|
||||||
|
|
||||||
|
const doesOrgKmsKeyExist = await knex.schema.hasColumn(TableName.Organization, "kmsDefaultKeyId");
|
||||||
|
if (!doesOrgKmsKeyExist) {
|
||||||
|
await knex.schema.alterTable(TableName.Organization, (tb) => {
|
||||||
|
tb.uuid("kmsDefaultKeyId").nullable();
|
||||||
|
tb.foreign("kmsDefaultKeyId").references("id").inTable(TableName.KmsKey);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const doesProjectKmsSecretManagerKeyExist = await knex.schema.hasColumn(TableName.Project, "kmsSecretManagerKeyId");
|
||||||
|
if (!doesProjectKmsSecretManagerKeyExist) {
|
||||||
|
await knex.schema.alterTable(TableName.Project, (tb) => {
|
||||||
|
tb.uuid("kmsSecretManagerKeyId").nullable();
|
||||||
|
tb.foreign("kmsSecretManagerKeyId").references("id").inTable(TableName.KmsKey);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
const renameInternalKmsKeyVersionBackToKmsKeyVersion = async (knex: Knex) => {
|
||||||
|
const doesInternalKmsKeyVersionTableExist = await knex.schema.hasTable(TableName.InternalKmsKeyVersion);
|
||||||
|
const doesKmsKeyVersionTableExist = await knex.schema.hasTable(TableName.KmsKeyVersion);
|
||||||
|
if (doesInternalKmsKeyVersionTableExist && !doesKmsKeyVersionTableExist) {
|
||||||
|
// because we haven't started using versioning for kms thus no data exist
|
||||||
|
await knex.schema.renameTable(TableName.InternalKmsKeyVersion, TableName.KmsKeyVersion);
|
||||||
|
const hasInternalKmsIdColumn = await knex.schema.hasColumn(TableName.KmsKeyVersion, "internalKmsId");
|
||||||
|
const hasKmsKeyIdColumn = await knex.schema.hasColumn(TableName.KmsKeyVersion, "kmsKeyId");
|
||||||
|
|
||||||
|
await knex.schema.alterTable(TableName.KmsKeyVersion, (tb) => {
|
||||||
|
if (hasInternalKmsIdColumn) tb.dropColumn("internalKmsId");
|
||||||
|
if (!hasKmsKeyIdColumn) {
|
||||||
|
tb.uuid("kmsKeyId").notNullable();
|
||||||
|
tb.foreign("kmsKeyId").references("id").inTable(TableName.KmsKey).onDelete("CASCADE");
|
||||||
|
}
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const bringBackKmsKeyFields = async (knex: Knex) => {
|
||||||
|
const doesOldKmsKeyTableExist = await knex.schema.hasTable(TableName.KmsKey);
|
||||||
|
const doesInternalKmsTableExist = await knex.schema.hasTable(TableName.InternalKms);
|
||||||
|
if (doesOldKmsKeyTableExist && doesInternalKmsTableExist) {
|
||||||
|
const hasSlug = await knex.schema.hasColumn(TableName.KmsKey, "slug");
|
||||||
|
const hasEncryptedKeyColumn = await knex.schema.hasColumn(TableName.KmsKey, "encryptedKey");
|
||||||
|
const hasEncryptionAlgorithmColumn = await knex.schema.hasColumn(TableName.KmsKey, "encryptionAlgorithm");
|
||||||
|
const hasVersionColumn = await knex.schema.hasColumn(TableName.KmsKey, "version");
|
||||||
|
const hasNullableOrgId = await knex.schema.hasColumn(TableName.KmsKey, "orgId");
|
||||||
|
const hasProjectIdColumn = await knex.schema.hasColumn(TableName.KmsKey, "projectId");
|
||||||
|
|
||||||
|
await knex.schema.alterTable(TableName.KmsKey, (tb) => {
|
||||||
|
if (!hasEncryptedKeyColumn) tb.binary("encryptedKey");
|
||||||
|
if (!hasEncryptionAlgorithmColumn) tb.string("encryptionAlgorithm");
|
||||||
|
if (!hasVersionColumn) tb.integer("version").defaultTo(1);
|
||||||
|
if (hasNullableOrgId) tb.uuid("orgId").nullable().alter();
|
||||||
|
if (!hasProjectIdColumn) {
|
||||||
|
tb.string("projectId");
|
||||||
|
tb.foreign("projectId").references("id").inTable(TableName.Project).onDelete("CASCADE");
|
||||||
|
}
|
||||||
|
if (hasSlug) tb.dropColumn("slug");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const backfillKmsKeyFromInternalKmsTable = async (knex: Knex) => {
|
||||||
|
const doesOldKmsKeyTableExist = await knex.schema.hasTable(TableName.KmsKey);
|
||||||
|
const doesInternalKmsTableExist = await knex.schema.hasTable(TableName.InternalKms);
|
||||||
|
if (doesInternalKmsTableExist && doesOldKmsKeyTableExist) {
|
||||||
|
// backfill kms key with internal kms data
|
||||||
|
await knex(TableName.KmsKey).update({
|
||||||
|
// eslint-disable-next-line
|
||||||
|
// @ts-ignore because generate schema happens after this
|
||||||
|
encryptedKey: knex(TableName.InternalKms)
|
||||||
|
.select("encryptedKey")
|
||||||
|
.where("kmsKeyId", knex.raw("??", [`${TableName.KmsKey}.id`])),
|
||||||
|
// eslint-disable-next-line
|
||||||
|
// @ts-ignore because generate schema happens after this
|
||||||
|
encryptionAlgorithm: knex(TableName.InternalKms)
|
||||||
|
.select("encryptionAlgorithm")
|
||||||
|
.where("kmsKeyId", knex.raw("??", [`${TableName.KmsKey}.id`])),
|
||||||
|
// eslint-disable-next-line
|
||||||
|
// @ts-ignore because generate schema happens after this
|
||||||
|
projectId: knex(TableName.Project)
|
||||||
|
.select("id")
|
||||||
|
.where("kmsCertificateKeyId", knex.raw("??", [`${TableName.KmsKey}.id`]))
|
||||||
|
});
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
export async function down(knex: Knex): Promise<void> {
|
||||||
|
const doesOrgKmsKeyExist = await knex.schema.hasColumn(TableName.Organization, "kmsDefaultKeyId");
|
||||||
|
if (doesOrgKmsKeyExist) {
|
||||||
|
await knex.schema.alterTable(TableName.Organization, (tb) => {
|
||||||
|
tb.dropColumn("kmsDefaultKeyId");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const doesProjectKmsSecretManagerKeyExist = await knex.schema.hasColumn(TableName.Project, "kmsSecretManagerKeyId");
|
||||||
|
if (doesProjectKmsSecretManagerKeyExist) {
|
||||||
|
await knex.schema.alterTable(TableName.Project, (tb) => {
|
||||||
|
tb.dropColumn("kmsSecretManagerKeyId");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
await renameInternalKmsKeyVersionBackToKmsKeyVersion(knex);
|
||||||
|
await bringBackKmsKeyFields(knex);
|
||||||
|
await backfillKmsKeyFromInternalKmsTable(knex);
|
||||||
|
|
||||||
|
const doesOldKmsKeyTableExist = await knex.schema.hasTable(TableName.KmsKey);
|
||||||
|
if (doesOldKmsKeyTableExist) {
|
||||||
|
await knex.schema.alterTable(TableName.KmsKey, (tb) => {
|
||||||
|
tb.binary("encryptedKey").notNullable().alter();
|
||||||
|
tb.string("encryptionAlgorithm").notNullable().alter();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
const doesInternalKmsTableExist = await knex.schema.hasTable(TableName.InternalKms);
|
||||||
|
if (doesInternalKmsTableExist) await knex.schema.dropTable(TableName.InternalKms);
|
||||||
|
|
||||||
|
const doesExternalKmsServiceExist = await knex.schema.hasTable(TableName.ExternalKms);
|
||||||
|
if (doesExternalKmsServiceExist) await knex.schema.dropTable(TableName.ExternalKms);
|
||||||
|
}
|
@ -0,0 +1,25 @@
|
|||||||
|
import { Knex } from "knex";
|
||||||
|
|
||||||
|
import { TableName } from "../schemas";
|
||||||
|
|
||||||
|
export async function up(knex: Knex): Promise<void> {
|
||||||
|
if (await knex.schema.hasTable(TableName.OrgMembership)) {
|
||||||
|
const doesUserIdExist = await knex.schema.hasColumn(TableName.OrgMembership, "userId");
|
||||||
|
const doesOrgIdExist = await knex.schema.hasColumn(TableName.OrgMembership, "orgId");
|
||||||
|
await knex.schema.alterTable(TableName.OrgMembership, (t) => {
|
||||||
|
t.boolean("isActive").notNullable().defaultTo(true);
|
||||||
|
if (doesUserIdExist && doesOrgIdExist) t.index(["userId", "orgId"]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function down(knex: Knex): Promise<void> {
|
||||||
|
if (await knex.schema.hasTable(TableName.OrgMembership)) {
|
||||||
|
const doesUserIdExist = await knex.schema.hasColumn(TableName.OrgMembership, "userId");
|
||||||
|
const doesOrgIdExist = await knex.schema.hasColumn(TableName.OrgMembership, "orgId");
|
||||||
|
await knex.schema.alterTable(TableName.OrgMembership, (t) => {
|
||||||
|
t.dropColumn("isActive");
|
||||||
|
if (doesUserIdExist && doesOrgIdExist) t.dropIndex(["userId", "orgId"]);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,23 @@
|
|||||||
|
import { Knex } from "knex";
|
||||||
|
|
||||||
|
import { EnforcementLevel } from "@app/lib/types";
|
||||||
|
|
||||||
|
import { TableName } from "../schemas";
|
||||||
|
|
||||||
|
export async function up(knex: Knex): Promise<void> {
|
||||||
|
const hasColumn = await knex.schema.hasColumn(TableName.SecretApprovalPolicy, "enforcementLevel");
|
||||||
|
if (!hasColumn) {
|
||||||
|
await knex.schema.table(TableName.SecretApprovalPolicy, (table) => {
|
||||||
|
table.string("enforcementLevel", 10).notNullable().defaultTo(EnforcementLevel.Hard);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function down(knex: Knex): Promise<void> {
|
||||||
|
const hasColumn = await knex.schema.hasColumn(TableName.SecretApprovalPolicy, "enforcementLevel");
|
||||||
|
if (hasColumn) {
|
||||||
|
await knex.schema.table(TableName.SecretApprovalPolicy, (table) => {
|
||||||
|
table.dropColumn("enforcementLevel");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,23 @@
|
|||||||
|
import { Knex } from "knex";
|
||||||
|
|
||||||
|
import { EnforcementLevel } from "@app/lib/types";
|
||||||
|
|
||||||
|
import { TableName } from "../schemas";
|
||||||
|
|
||||||
|
export async function up(knex: Knex): Promise<void> {
|
||||||
|
const hasColumn = await knex.schema.hasColumn(TableName.AccessApprovalPolicy, "enforcementLevel");
|
||||||
|
if (!hasColumn) {
|
||||||
|
await knex.schema.table(TableName.AccessApprovalPolicy, (table) => {
|
||||||
|
table.string("enforcementLevel", 10).notNullable().defaultTo(EnforcementLevel.Hard);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function down(knex: Knex): Promise<void> {
|
||||||
|
const hasColumn = await knex.schema.hasColumn(TableName.AccessApprovalPolicy, "enforcementLevel");
|
||||||
|
if (hasColumn) {
|
||||||
|
await knex.schema.table(TableName.AccessApprovalPolicy, (table) => {
|
||||||
|
table.dropColumn("enforcementLevel");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,23 @@
|
|||||||
|
import { Knex } from "knex";
|
||||||
|
|
||||||
|
import { SecretSharingAccessType } from "@app/lib/types";
|
||||||
|
|
||||||
|
import { TableName } from "../schemas";
|
||||||
|
|
||||||
|
export async function up(knex: Knex): Promise<void> {
|
||||||
|
const hasColumn = await knex.schema.hasColumn(TableName.SecretSharing, "accessType");
|
||||||
|
if (!hasColumn) {
|
||||||
|
await knex.schema.table(TableName.SecretSharing, (table) => {
|
||||||
|
table.string("accessType").notNullable().defaultTo(SecretSharingAccessType.Anyone);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function down(knex: Knex): Promise<void> {
|
||||||
|
const hasColumn = await knex.schema.hasColumn(TableName.SecretSharing, "accessType");
|
||||||
|
if (hasColumn) {
|
||||||
|
await knex.schema.table(TableName.SecretSharing, (table) => {
|
||||||
|
table.dropColumn("accessType");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
@ -0,0 +1,21 @@
|
|||||||
|
import { Knex } from "knex";
|
||||||
|
|
||||||
|
import { TableName } from "../schemas";
|
||||||
|
|
||||||
|
export async function up(knex: Knex): Promise<void> {
|
||||||
|
const hasColumn = await knex.schema.hasColumn(TableName.SecretApprovalRequest, "bypassReason");
|
||||||
|
if (!hasColumn) {
|
||||||
|
await knex.schema.table(TableName.SecretApprovalRequest, (table) => {
|
||||||
|
table.string("bypassReason").nullable();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export async function down(knex: Knex): Promise<void> {
|
||||||
|
const hasColumn = await knex.schema.hasColumn(TableName.SecretApprovalRequest, "bypassReason");
|
||||||
|
if (hasColumn) {
|
||||||
|
await knex.schema.table(TableName.SecretApprovalRequest, (table) => {
|
||||||
|
table.dropColumn("bypassReason");
|
||||||
|
});
|
||||||
|
}
|
||||||
|
}
|
@ -5,6 +5,8 @@
|
|||||||
|
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
|
import { EnforcementLevel } from "@app/lib/types";
|
||||||
|
|
||||||
import { TImmutableDBKeys } from "./models";
|
import { TImmutableDBKeys } from "./models";
|
||||||
|
|
||||||
export const AccessApprovalPoliciesSchema = z.object({
|
export const AccessApprovalPoliciesSchema = z.object({
|
||||||
@ -14,7 +16,8 @@ export const AccessApprovalPoliciesSchema = z.object({
|
|||||||
secretPath: z.string().nullable().optional(),
|
secretPath: z.string().nullable().optional(),
|
||||||
envId: z.string().uuid(),
|
envId: z.string().uuid(),
|
||||||
createdAt: z.date(),
|
createdAt: z.date(),
|
||||||
updatedAt: z.date()
|
updatedAt: z.date(),
|
||||||
|
enforcementLevel: z.nativeEnum(EnforcementLevel).default(EnforcementLevel.Hard)
|
||||||
});
|
});
|
||||||
|
|
||||||
export type TAccessApprovalPolicies = z.infer<typeof AccessApprovalPoliciesSchema>;
|
export type TAccessApprovalPolicies = z.infer<typeof AccessApprovalPoliciesSchema>;
|
||||||
|
23
backend/src/db/schemas/external-kms.ts
Normal file
23
backend/src/db/schemas/external-kms.ts
Normal file
@ -0,0 +1,23 @@
|
|||||||
|
// 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 ExternalKmsSchema = z.object({
|
||||||
|
id: z.string().uuid(),
|
||||||
|
provider: z.string(),
|
||||||
|
encryptedProviderInputs: zodBuffer,
|
||||||
|
status: z.string().nullable().optional(),
|
||||||
|
statusDetails: z.string().nullable().optional(),
|
||||||
|
kmsKeyId: z.string().uuid()
|
||||||
|
});
|
||||||
|
|
||||||
|
export type TExternalKms = z.infer<typeof ExternalKmsSchema>;
|
||||||
|
export type TExternalKmsInsert = Omit<z.input<typeof ExternalKmsSchema>, TImmutableDBKeys>;
|
||||||
|
export type TExternalKmsUpdate = Partial<Omit<z.input<typeof ExternalKmsSchema>, TImmutableDBKeys>>;
|
@ -17,6 +17,7 @@ export * from "./certificate-secrets";
|
|||||||
export * from "./certificates";
|
export * from "./certificates";
|
||||||
export * from "./dynamic-secret-leases";
|
export * from "./dynamic-secret-leases";
|
||||||
export * from "./dynamic-secrets";
|
export * from "./dynamic-secrets";
|
||||||
|
export * from "./external-kms";
|
||||||
export * from "./git-app-install-sessions";
|
export * from "./git-app-install-sessions";
|
||||||
export * from "./git-app-org";
|
export * from "./git-app-org";
|
||||||
export * from "./group-project-membership-roles";
|
export * from "./group-project-membership-roles";
|
||||||
@ -39,6 +40,7 @@ export * from "./identity-universal-auths";
|
|||||||
export * from "./incident-contacts";
|
export * from "./incident-contacts";
|
||||||
export * from "./integration-auths";
|
export * from "./integration-auths";
|
||||||
export * from "./integrations";
|
export * from "./integrations";
|
||||||
|
export * from "./internal-kms";
|
||||||
export * from "./kms-key-versions";
|
export * from "./kms-key-versions";
|
||||||
export * from "./kms-keys";
|
export * from "./kms-keys";
|
||||||
export * from "./kms-root-config";
|
export * from "./kms-root-config";
|
||||||
|
21
backend/src/db/schemas/internal-kms-key-version.ts
Normal file
21
backend/src/db/schemas/internal-kms-key-version.ts
Normal file
@ -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 { zodBuffer } from "@app/lib/zod";
|
||||||
|
|
||||||
|
import { TImmutableDBKeys } from "./models";
|
||||||
|
|
||||||
|
export const InternalKmsKeyVersionSchema = z.object({
|
||||||
|
id: z.string().uuid(),
|
||||||
|
encryptedKey: zodBuffer,
|
||||||
|
version: z.number(),
|
||||||
|
internalKmsId: z.string().uuid()
|
||||||
|
});
|
||||||
|
|
||||||
|
export type TInternalKmsKeyVersion = z.infer<typeof InternalKmsKeyVersionSchema>;
|
||||||
|
export type TInternalKmsKeyVersionInsert = Omit<z.input<typeof InternalKmsKeyVersionSchema>, TImmutableDBKeys>;
|
||||||
|
export type TInternalKmsKeyVersionUpdate = Partial<Omit<z.input<typeof InternalKmsKeyVersionSchema>, TImmutableDBKeys>>;
|
22
backend/src/db/schemas/internal-kms.ts
Normal file
22
backend/src/db/schemas/internal-kms.ts
Normal file
@ -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 { zodBuffer } from "@app/lib/zod";
|
||||||
|
|
||||||
|
import { TImmutableDBKeys } from "./models";
|
||||||
|
|
||||||
|
export const InternalKmsSchema = z.object({
|
||||||
|
id: z.string().uuid(),
|
||||||
|
encryptedKey: zodBuffer,
|
||||||
|
encryptionAlgorithm: z.string(),
|
||||||
|
version: z.number().default(1),
|
||||||
|
kmsKeyId: z.string().uuid()
|
||||||
|
});
|
||||||
|
|
||||||
|
export type TInternalKms = z.infer<typeof InternalKmsSchema>;
|
||||||
|
export type TInternalKmsInsert = Omit<z.input<typeof InternalKmsSchema>, TImmutableDBKeys>;
|
||||||
|
export type TInternalKmsUpdate = Partial<Omit<z.input<typeof InternalKmsSchema>, TImmutableDBKeys>>;
|
@ -5,20 +5,17 @@
|
|||||||
|
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
import { zodBuffer } from "@app/lib/zod";
|
|
||||||
|
|
||||||
import { TImmutableDBKeys } from "./models";
|
import { TImmutableDBKeys } from "./models";
|
||||||
|
|
||||||
export const KmsKeysSchema = z.object({
|
export const KmsKeysSchema = z.object({
|
||||||
id: z.string().uuid(),
|
id: z.string().uuid(),
|
||||||
encryptedKey: zodBuffer,
|
|
||||||
encryptionAlgorithm: z.string(),
|
|
||||||
version: z.number().default(1),
|
|
||||||
description: z.string().nullable().optional(),
|
description: z.string().nullable().optional(),
|
||||||
isDisabled: z.boolean().default(false).nullable().optional(),
|
isDisabled: z.boolean().default(false).nullable().optional(),
|
||||||
isReserved: z.boolean().default(true).nullable().optional(),
|
isReserved: z.boolean().default(true).nullable().optional(),
|
||||||
projectId: z.string().nullable().optional(),
|
orgId: z.string().uuid(),
|
||||||
orgId: z.string().uuid().nullable().optional()
|
createdAt: z.date(),
|
||||||
|
updatedAt: z.date(),
|
||||||
|
slug: z.string()
|
||||||
});
|
});
|
||||||
|
|
||||||
export type TKmsKeys = z.infer<typeof KmsKeysSchema>;
|
export type TKmsKeys = z.infer<typeof KmsKeysSchema>;
|
||||||
|
@ -96,6 +96,10 @@ export enum TableName {
|
|||||||
// KMS Service
|
// KMS Service
|
||||||
KmsServerRootConfig = "kms_root_config",
|
KmsServerRootConfig = "kms_root_config",
|
||||||
KmsKey = "kms_keys",
|
KmsKey = "kms_keys",
|
||||||
|
ExternalKms = "external_kms",
|
||||||
|
InternalKms = "internal_kms",
|
||||||
|
InternalKmsKeyVersion = "internal_kms_key_version",
|
||||||
|
// @depreciated
|
||||||
KmsKeyVersion = "kms_key_versions"
|
KmsKeyVersion = "kms_key_versions"
|
||||||
}
|
}
|
||||||
|
|
||||||
|
@ -17,7 +17,8 @@ export const OrgMembershipsSchema = z.object({
|
|||||||
userId: z.string().uuid().nullable().optional(),
|
userId: z.string().uuid().nullable().optional(),
|
||||||
orgId: z.string().uuid(),
|
orgId: z.string().uuid(),
|
||||||
roleId: z.string().uuid().nullable().optional(),
|
roleId: z.string().uuid().nullable().optional(),
|
||||||
projectFavorites: z.string().array().nullable().optional()
|
projectFavorites: z.string().array().nullable().optional(),
|
||||||
|
isActive: z.boolean()
|
||||||
});
|
});
|
||||||
|
|
||||||
export type TOrgMemberships = z.infer<typeof OrgMembershipsSchema>;
|
export type TOrgMemberships = z.infer<typeof OrgMembershipsSchema>;
|
||||||
|
@ -15,7 +15,8 @@ export const OrganizationsSchema = z.object({
|
|||||||
createdAt: z.date(),
|
createdAt: z.date(),
|
||||||
updatedAt: z.date(),
|
updatedAt: z.date(),
|
||||||
authEnforced: z.boolean().default(false).nullable().optional(),
|
authEnforced: z.boolean().default(false).nullable().optional(),
|
||||||
scimEnabled: z.boolean().default(false).nullable().optional()
|
scimEnabled: z.boolean().default(false).nullable().optional(),
|
||||||
|
kmsDefaultKeyId: z.string().uuid().nullable().optional()
|
||||||
});
|
});
|
||||||
|
|
||||||
export type TOrganizations = z.infer<typeof OrganizationsSchema>;
|
export type TOrganizations = z.infer<typeof OrganizationsSchema>;
|
||||||
|
@ -19,7 +19,8 @@ export const ProjectsSchema = z.object({
|
|||||||
upgradeStatus: z.string().nullable().optional(),
|
upgradeStatus: z.string().nullable().optional(),
|
||||||
pitVersionLimit: z.number().default(10),
|
pitVersionLimit: z.number().default(10),
|
||||||
kmsCertificateKeyId: z.string().uuid().nullable().optional(),
|
kmsCertificateKeyId: z.string().uuid().nullable().optional(),
|
||||||
auditLogsRetentionDays: z.number().nullable().optional()
|
auditLogsRetentionDays: z.number().nullable().optional(),
|
||||||
|
kmsSecretManagerKeyId: z.string().uuid().nullable().optional()
|
||||||
});
|
});
|
||||||
|
|
||||||
export type TProjects = z.infer<typeof ProjectsSchema>;
|
export type TProjects = z.infer<typeof ProjectsSchema>;
|
||||||
|
@ -14,7 +14,8 @@ export const SecretApprovalPoliciesSchema = z.object({
|
|||||||
approvals: z.number().default(1),
|
approvals: z.number().default(1),
|
||||||
envId: z.string().uuid(),
|
envId: z.string().uuid(),
|
||||||
createdAt: z.date(),
|
createdAt: z.date(),
|
||||||
updatedAt: z.date()
|
updatedAt: z.date(),
|
||||||
|
enforcementLevel: z.string().default("hard")
|
||||||
});
|
});
|
||||||
|
|
||||||
export type TSecretApprovalPolicies = z.infer<typeof SecretApprovalPoliciesSchema>;
|
export type TSecretApprovalPolicies = z.infer<typeof SecretApprovalPoliciesSchema>;
|
||||||
|
@ -15,6 +15,7 @@ export const SecretApprovalRequestsSchema = z.object({
|
|||||||
conflicts: z.unknown().nullable().optional(),
|
conflicts: z.unknown().nullable().optional(),
|
||||||
slug: z.string(),
|
slug: z.string(),
|
||||||
folderId: z.string().uuid(),
|
folderId: z.string().uuid(),
|
||||||
|
bypassReason: z.string().nullable().optional(),
|
||||||
createdAt: z.date(),
|
createdAt: z.date(),
|
||||||
updatedAt: z.date(),
|
updatedAt: z.date(),
|
||||||
isReplicated: z.boolean().nullable().optional(),
|
isReplicated: z.boolean().nullable().optional(),
|
||||||
|
@ -5,6 +5,8 @@
|
|||||||
|
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
|
import { SecretSharingAccessType } from "@app/lib/types";
|
||||||
|
|
||||||
import { TImmutableDBKeys } from "./models";
|
import { TImmutableDBKeys } from "./models";
|
||||||
|
|
||||||
export const SecretSharingSchema = z.object({
|
export const SecretSharingSchema = z.object({
|
||||||
@ -16,6 +18,7 @@ export const SecretSharingSchema = z.object({
|
|||||||
expiresAt: z.date(),
|
expiresAt: z.date(),
|
||||||
userId: z.string().uuid().nullable().optional(),
|
userId: z.string().uuid().nullable().optional(),
|
||||||
orgId: z.string().uuid().nullable().optional(),
|
orgId: z.string().uuid().nullable().optional(),
|
||||||
|
accessType: z.nativeEnum(SecretSharingAccessType).default(SecretSharingAccessType.Organization),
|
||||||
createdAt: z.date(),
|
createdAt: z.date(),
|
||||||
updatedAt: z.date(),
|
updatedAt: z.date(),
|
||||||
expiresAfterViews: z.number().nullable().optional()
|
expiresAfterViews: z.number().nullable().optional()
|
||||||
|
@ -29,7 +29,8 @@ export async function seed(knex: Knex): Promise<void> {
|
|||||||
role: OrgMembershipRole.Admin,
|
role: OrgMembershipRole.Admin,
|
||||||
orgId: org.id,
|
orgId: org.id,
|
||||||
status: OrgMembershipStatus.Accepted,
|
status: OrgMembershipStatus.Accepted,
|
||||||
userId: user.id
|
userId: user.id,
|
||||||
|
isActive: true
|
||||||
}
|
}
|
||||||
]);
|
]);
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
import { nanoid } from "nanoid";
|
import { nanoid } from "nanoid";
|
||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
|
import { EnforcementLevel } from "@app/lib/types";
|
||||||
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
||||||
import { sapPubSchema } from "@app/server/routes/sanitizedSchemas";
|
import { sapPubSchema } from "@app/server/routes/sanitizedSchemas";
|
||||||
import { AuthMode } from "@app/services/auth/auth-type";
|
import { AuthMode } from "@app/services/auth/auth-type";
|
||||||
@ -17,7 +18,8 @@ export const registerAccessApprovalPolicyRouter = async (server: FastifyZodProvi
|
|||||||
secretPath: z.string().trim().default("/"),
|
secretPath: z.string().trim().default("/"),
|
||||||
environment: z.string(),
|
environment: z.string(),
|
||||||
approvers: z.string().array().min(1),
|
approvers: z.string().array().min(1),
|
||||||
approvals: z.number().min(1).default(1)
|
approvals: z.number().min(1).default(1),
|
||||||
|
enforcementLevel: z.nativeEnum(EnforcementLevel).default(EnforcementLevel.Hard)
|
||||||
})
|
})
|
||||||
.refine((data) => data.approvals <= data.approvers.length, {
|
.refine((data) => data.approvals <= data.approvers.length, {
|
||||||
path: ["approvals"],
|
path: ["approvals"],
|
||||||
@ -38,7 +40,8 @@ export const registerAccessApprovalPolicyRouter = async (server: FastifyZodProvi
|
|||||||
actorOrgId: req.permission.orgId,
|
actorOrgId: req.permission.orgId,
|
||||||
...req.body,
|
...req.body,
|
||||||
projectSlug: req.body.projectSlug,
|
projectSlug: req.body.projectSlug,
|
||||||
name: req.body.name ?? `${req.body.environment}-${nanoid(3)}`
|
name: req.body.name ?? `${req.body.environment}-${nanoid(3)}`,
|
||||||
|
enforcementLevel: req.body.enforcementLevel
|
||||||
});
|
});
|
||||||
return { approval };
|
return { approval };
|
||||||
}
|
}
|
||||||
@ -115,7 +118,8 @@ export const registerAccessApprovalPolicyRouter = async (server: FastifyZodProvi
|
|||||||
.optional()
|
.optional()
|
||||||
.transform((val) => (val === "" ? "/" : val)),
|
.transform((val) => (val === "" ? "/" : val)),
|
||||||
approvers: z.string().array().min(1),
|
approvers: z.string().array().min(1),
|
||||||
approvals: z.number().min(1).default(1)
|
approvals: z.number().min(1).default(1),
|
||||||
|
enforcementLevel: z.nativeEnum(EnforcementLevel).default(EnforcementLevel.Hard)
|
||||||
})
|
})
|
||||||
.refine((data) => data.approvals <= data.approvers.length, {
|
.refine((data) => data.approvals <= data.approvers.length, {
|
||||||
path: ["approvals"],
|
path: ["approvals"],
|
||||||
|
@ -99,7 +99,8 @@ export const registerAccessApprovalRequestRouter = async (server: FastifyZodProv
|
|||||||
approvals: z.number(),
|
approvals: z.number(),
|
||||||
approvers: z.string().array(),
|
approvers: z.string().array(),
|
||||||
secretPath: z.string().nullish(),
|
secretPath: z.string().nullish(),
|
||||||
envId: z.string()
|
envId: z.string(),
|
||||||
|
enforcementLevel: z.string()
|
||||||
}),
|
}),
|
||||||
reviewers: z
|
reviewers: z
|
||||||
.object({
|
.object({
|
||||||
|
190
backend/src/ee/routes/v1/external-kms-router.ts
Normal file
190
backend/src/ee/routes/v1/external-kms-router.ts
Normal file
@ -0,0 +1,190 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
import { ExternalKmsSchema, KmsKeysSchema } from "@app/db/schemas";
|
||||||
|
import {
|
||||||
|
ExternalKmsAwsSchema,
|
||||||
|
ExternalKmsInputSchema,
|
||||||
|
ExternalKmsInputUpdateSchema
|
||||||
|
} from "@app/ee/services/external-kms/providers/model";
|
||||||
|
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 sanitizedExternalSchema = KmsKeysSchema.extend({
|
||||||
|
external: ExternalKmsSchema.pick({
|
||||||
|
id: true,
|
||||||
|
status: true,
|
||||||
|
statusDetails: true,
|
||||||
|
provider: true
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
const sanitizedExternalSchemaForGetById = KmsKeysSchema.extend({
|
||||||
|
external: ExternalKmsSchema.pick({
|
||||||
|
id: true,
|
||||||
|
status: true,
|
||||||
|
statusDetails: true,
|
||||||
|
provider: true
|
||||||
|
}).extend({
|
||||||
|
providerInput: ExternalKmsAwsSchema
|
||||||
|
})
|
||||||
|
});
|
||||||
|
|
||||||
|
export const registerExternalKmsRouter = async (server: FastifyZodProvider) => {
|
||||||
|
server.route({
|
||||||
|
method: "POST",
|
||||||
|
url: "/",
|
||||||
|
config: {
|
||||||
|
rateLimit: writeLimit
|
||||||
|
},
|
||||||
|
schema: {
|
||||||
|
body: z.object({
|
||||||
|
slug: z.string().min(1).trim().toLowerCase().optional(),
|
||||||
|
description: z.string().min(1).trim().optional(),
|
||||||
|
provider: ExternalKmsInputSchema
|
||||||
|
}),
|
||||||
|
response: {
|
||||||
|
200: z.object({
|
||||||
|
externalKms: sanitizedExternalSchema
|
||||||
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||||
|
handler: async (req) => {
|
||||||
|
const externalKms = await server.services.externalKms.create({
|
||||||
|
actor: req.permission.type,
|
||||||
|
actorId: req.permission.id,
|
||||||
|
actorAuthMethod: req.permission.authMethod,
|
||||||
|
actorOrgId: req.permission.orgId,
|
||||||
|
slug: req.body.slug,
|
||||||
|
provider: req.body.provider,
|
||||||
|
description: req.body.description
|
||||||
|
});
|
||||||
|
return { externalKms };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
server.route({
|
||||||
|
method: "PATCH",
|
||||||
|
url: "/:id",
|
||||||
|
config: {
|
||||||
|
rateLimit: writeLimit
|
||||||
|
},
|
||||||
|
schema: {
|
||||||
|
params: z.object({
|
||||||
|
id: z.string().trim().min(1)
|
||||||
|
}),
|
||||||
|
body: z.object({
|
||||||
|
slug: z.string().min(1).trim().toLowerCase().optional(),
|
||||||
|
description: z.string().min(1).trim().optional(),
|
||||||
|
provider: ExternalKmsInputUpdateSchema
|
||||||
|
}),
|
||||||
|
response: {
|
||||||
|
200: z.object({
|
||||||
|
externalKms: sanitizedExternalSchema
|
||||||
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||||
|
handler: async (req) => {
|
||||||
|
const externalKms = await server.services.externalKms.updateById({
|
||||||
|
actor: req.permission.type,
|
||||||
|
actorId: req.permission.id,
|
||||||
|
actorAuthMethod: req.permission.authMethod,
|
||||||
|
actorOrgId: req.permission.orgId,
|
||||||
|
slug: req.body.slug,
|
||||||
|
provider: req.body.provider,
|
||||||
|
description: req.body.description,
|
||||||
|
id: req.params.id
|
||||||
|
});
|
||||||
|
return { externalKms };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
server.route({
|
||||||
|
method: "DELETE",
|
||||||
|
url: "/:id",
|
||||||
|
config: {
|
||||||
|
rateLimit: writeLimit
|
||||||
|
},
|
||||||
|
schema: {
|
||||||
|
params: z.object({
|
||||||
|
id: z.string().trim().min(1)
|
||||||
|
}),
|
||||||
|
response: {
|
||||||
|
200: z.object({
|
||||||
|
externalKms: sanitizedExternalSchema
|
||||||
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||||
|
handler: async (req) => {
|
||||||
|
const externalKms = await server.services.externalKms.deleteById({
|
||||||
|
actor: req.permission.type,
|
||||||
|
actorId: req.permission.id,
|
||||||
|
actorAuthMethod: req.permission.authMethod,
|
||||||
|
actorOrgId: req.permission.orgId,
|
||||||
|
id: req.params.id
|
||||||
|
});
|
||||||
|
return { externalKms };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
server.route({
|
||||||
|
method: "GET",
|
||||||
|
url: "/:id",
|
||||||
|
config: {
|
||||||
|
rateLimit: readLimit
|
||||||
|
},
|
||||||
|
schema: {
|
||||||
|
params: z.object({
|
||||||
|
id: z.string().trim().min(1)
|
||||||
|
}),
|
||||||
|
response: {
|
||||||
|
200: z.object({
|
||||||
|
externalKms: sanitizedExternalSchemaForGetById
|
||||||
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||||
|
handler: async (req) => {
|
||||||
|
const externalKms = await server.services.externalKms.findById({
|
||||||
|
actor: req.permission.type,
|
||||||
|
actorId: req.permission.id,
|
||||||
|
actorAuthMethod: req.permission.authMethod,
|
||||||
|
actorOrgId: req.permission.orgId,
|
||||||
|
id: req.params.id
|
||||||
|
});
|
||||||
|
return { externalKms };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
server.route({
|
||||||
|
method: "GET",
|
||||||
|
url: "/slug/:slug",
|
||||||
|
config: {
|
||||||
|
rateLimit: readLimit
|
||||||
|
},
|
||||||
|
schema: {
|
||||||
|
params: z.object({
|
||||||
|
slug: z.string().trim().min(1)
|
||||||
|
}),
|
||||||
|
response: {
|
||||||
|
200: z.object({
|
||||||
|
externalKms: sanitizedExternalSchemaForGetById
|
||||||
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||||
|
handler: async (req) => {
|
||||||
|
const externalKms = await server.services.externalKms.findBySlug({
|
||||||
|
actor: req.permission.type,
|
||||||
|
actorId: req.permission.id,
|
||||||
|
actorAuthMethod: req.permission.authMethod,
|
||||||
|
actorOrgId: req.permission.orgId,
|
||||||
|
slug: req.params.slug
|
||||||
|
});
|
||||||
|
return { externalKms };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
};
|
@ -52,6 +52,36 @@ export const registerOrgRoleRouter = async (server: FastifyZodProvider) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
server.route({
|
||||||
|
method: "GET",
|
||||||
|
url: "/:organizationId/roles/:roleId",
|
||||||
|
config: {
|
||||||
|
rateLimit: readLimit
|
||||||
|
},
|
||||||
|
schema: {
|
||||||
|
params: z.object({
|
||||||
|
organizationId: z.string().trim(),
|
||||||
|
roleId: z.string().trim()
|
||||||
|
}),
|
||||||
|
response: {
|
||||||
|
200: z.object({
|
||||||
|
role: OrgRolesSchema
|
||||||
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
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 };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
server.route({
|
server.route({
|
||||||
method: "PATCH",
|
method: "PATCH",
|
||||||
url: "/:organizationId/roles/:roleId",
|
url: "/:organizationId/roles/:roleId",
|
||||||
@ -69,7 +99,7 @@ export const registerOrgRoleRouter = async (server: FastifyZodProvider) => {
|
|||||||
.trim()
|
.trim()
|
||||||
.optional()
|
.optional()
|
||||||
.refine(
|
.refine(
|
||||||
(val) => typeof val === "undefined" || Object.keys(OrgMembershipRole).includes(val),
|
(val) => typeof val !== "undefined" && !Object.keys(OrgMembershipRole).includes(val),
|
||||||
"Please choose a different slug, the slug you have entered is reserved."
|
"Please choose a different slug, the slug you have entered is reserved."
|
||||||
)
|
)
|
||||||
.refine((val) => typeof val === "undefined" || slugify(val) === val, {
|
.refine((val) => typeof val === "undefined" || slugify(val) === val, {
|
||||||
|
@ -186,7 +186,13 @@ export const registerScimRouter = async (server: FastifyZodProvider) => {
|
|||||||
})
|
})
|
||||||
),
|
),
|
||||||
displayName: z.string().trim(),
|
displayName: z.string().trim(),
|
||||||
active: z.boolean()
|
active: z.boolean(),
|
||||||
|
groups: z.array(
|
||||||
|
z.object({
|
||||||
|
value: z.string().trim(),
|
||||||
|
display: z.string().trim()
|
||||||
|
})
|
||||||
|
)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
@ -344,7 +350,12 @@ export const registerScimRouter = async (server: FastifyZodProvider) => {
|
|||||||
schemas: z.array(z.string()),
|
schemas: z.array(z.string()),
|
||||||
id: z.string().trim(),
|
id: z.string().trim(),
|
||||||
displayName: z.string().trim(),
|
displayName: z.string().trim(),
|
||||||
members: z.array(z.any()).length(0),
|
members: z.array(
|
||||||
|
z.object({
|
||||||
|
value: z.string(),
|
||||||
|
display: z.string()
|
||||||
|
})
|
||||||
|
),
|
||||||
meta: z.object({
|
meta: z.object({
|
||||||
resourceType: z.string().trim()
|
resourceType: z.string().trim()
|
||||||
})
|
})
|
||||||
@ -417,7 +428,7 @@ export const registerScimRouter = async (server: FastifyZodProvider) => {
|
|||||||
displayName: z.string().trim(),
|
displayName: z.string().trim(),
|
||||||
members: z.array(
|
members: z.array(
|
||||||
z.object({
|
z.object({
|
||||||
value: z.string(), // infisical orgMembershipId
|
value: z.string(),
|
||||||
display: z.string()
|
display: z.string()
|
||||||
})
|
})
|
||||||
)
|
)
|
||||||
@ -475,10 +486,13 @@ export const registerScimRouter = async (server: FastifyZodProvider) => {
|
|||||||
}),
|
}),
|
||||||
z.object({
|
z.object({
|
||||||
op: z.literal("add"),
|
op: z.literal("add"),
|
||||||
value: z.object({
|
path: z.string().trim(),
|
||||||
|
value: z.array(
|
||||||
|
z.object({
|
||||||
value: z.string().trim(),
|
value: z.string().trim(),
|
||||||
display: z.string().trim().optional()
|
display: z.string().trim().optional()
|
||||||
})
|
})
|
||||||
|
)
|
||||||
})
|
})
|
||||||
])
|
])
|
||||||
)
|
)
|
||||||
@ -569,7 +583,13 @@ export const registerScimRouter = async (server: FastifyZodProvider) => {
|
|||||||
})
|
})
|
||||||
),
|
),
|
||||||
displayName: z.string().trim(),
|
displayName: z.string().trim(),
|
||||||
active: z.boolean()
|
active: z.boolean(),
|
||||||
|
groups: z.array(
|
||||||
|
z.object({
|
||||||
|
value: z.string().trim(),
|
||||||
|
display: z.string().trim()
|
||||||
|
})
|
||||||
|
)
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
|
@ -2,6 +2,7 @@ import { nanoid } from "nanoid";
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
import { removeTrailingSlash } from "@app/lib/fn";
|
import { removeTrailingSlash } from "@app/lib/fn";
|
||||||
|
import { EnforcementLevel } from "@app/lib/types";
|
||||||
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
|
import { readLimit, writeLimit } from "@app/server/config/rateLimiter";
|
||||||
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
||||||
import { sapPubSchema } from "@app/server/routes/sanitizedSchemas";
|
import { sapPubSchema } from "@app/server/routes/sanitizedSchemas";
|
||||||
@ -24,11 +25,13 @@ export const registerSecretApprovalPolicyRouter = async (server: FastifyZodProvi
|
|||||||
.string()
|
.string()
|
||||||
.optional()
|
.optional()
|
||||||
.nullable()
|
.nullable()
|
||||||
|
.default("/")
|
||||||
.transform((val) => (val ? removeTrailingSlash(val) : val)),
|
.transform((val) => (val ? removeTrailingSlash(val) : val)),
|
||||||
approverUserIds: z.string().array().min(1),
|
approvers: z.string().array().min(1),
|
||||||
approvals: z.number().min(1).default(1)
|
approvals: z.number().min(1).default(1),
|
||||||
|
enforcementLevel: z.nativeEnum(EnforcementLevel).default(EnforcementLevel.Hard)
|
||||||
})
|
})
|
||||||
.refine((data) => data.approvals <= data.approverUserIds.length, {
|
.refine((data) => data.approvals <= data.approvers.length, {
|
||||||
path: ["approvals"],
|
path: ["approvals"],
|
||||||
message: "The number of approvals should be lower than the number of approvers."
|
message: "The number of approvals should be lower than the number of approvers."
|
||||||
}),
|
}),
|
||||||
@ -47,7 +50,8 @@ export const registerSecretApprovalPolicyRouter = async (server: FastifyZodProvi
|
|||||||
actorOrgId: req.permission.orgId,
|
actorOrgId: req.permission.orgId,
|
||||||
projectId: req.body.workspaceId,
|
projectId: req.body.workspaceId,
|
||||||
...req.body,
|
...req.body,
|
||||||
name: req.body.name ?? `${req.body.environment}-${nanoid(3)}`
|
name: req.body.name ?? `${req.body.environment}-${nanoid(3)}`,
|
||||||
|
enforcementLevel: req.body.enforcementLevel
|
||||||
});
|
});
|
||||||
return { approval };
|
return { approval };
|
||||||
}
|
}
|
||||||
@ -66,15 +70,17 @@ export const registerSecretApprovalPolicyRouter = async (server: FastifyZodProvi
|
|||||||
body: z
|
body: z
|
||||||
.object({
|
.object({
|
||||||
name: z.string().optional(),
|
name: z.string().optional(),
|
||||||
approverUserIds: z.string().array().min(1),
|
approvers: z.string().array().min(1),
|
||||||
approvals: z.number().min(1).default(1),
|
approvals: z.number().min(1).default(1),
|
||||||
secretPath: z
|
secretPath: z
|
||||||
.string()
|
.string()
|
||||||
.optional()
|
.optional()
|
||||||
.nullable()
|
.nullable()
|
||||||
.transform((val) => (val ? removeTrailingSlash(val) : val))
|
.transform((val) => (val ? removeTrailingSlash(val) : val))
|
||||||
|
.transform((val) => (val === "" ? "/" : val)),
|
||||||
|
enforcementLevel: z.nativeEnum(EnforcementLevel).optional()
|
||||||
})
|
})
|
||||||
.refine((data) => data.approvals <= data.approverUserIds.length, {
|
.refine((data) => data.approvals <= data.approvers.length, {
|
||||||
path: ["approvals"],
|
path: ["approvals"],
|
||||||
message: "The number of approvals should be lower than the number of approvers."
|
message: "The number of approvals should be lower than the number of approvers."
|
||||||
}),
|
}),
|
||||||
|
@ -49,7 +49,8 @@ export const registerSecretApprovalRequestRouter = async (server: FastifyZodProv
|
|||||||
name: z.string(),
|
name: z.string(),
|
||||||
approvals: z.number(),
|
approvals: z.number(),
|
||||||
approvers: z.string().array(),
|
approvers: z.string().array(),
|
||||||
secretPath: z.string().optional().nullable()
|
secretPath: z.string().optional().nullable(),
|
||||||
|
enforcementLevel: z.string()
|
||||||
}),
|
}),
|
||||||
committerUser: approvalRequestUser,
|
committerUser: approvalRequestUser,
|
||||||
commits: z.object({ op: z.string(), secretId: z.string().nullable().optional() }).array(),
|
commits: z.object({ op: z.string(), secretId: z.string().nullable().optional() }).array(),
|
||||||
@ -116,6 +117,9 @@ export const registerSecretApprovalRequestRouter = async (server: FastifyZodProv
|
|||||||
params: z.object({
|
params: z.object({
|
||||||
id: z.string()
|
id: z.string()
|
||||||
}),
|
}),
|
||||||
|
body: z.object({
|
||||||
|
bypassReason: z.string().optional()
|
||||||
|
}),
|
||||||
response: {
|
response: {
|
||||||
200: z.object({
|
200: z.object({
|
||||||
approval: SecretApprovalRequestsSchema
|
approval: SecretApprovalRequestsSchema
|
||||||
@ -129,7 +133,8 @@ export const registerSecretApprovalRequestRouter = async (server: FastifyZodProv
|
|||||||
actor: req.permission.type,
|
actor: req.permission.type,
|
||||||
actorAuthMethod: req.permission.authMethod,
|
actorAuthMethod: req.permission.authMethod,
|
||||||
actorOrgId: req.permission.orgId,
|
actorOrgId: req.permission.orgId,
|
||||||
approvalId: req.params.id
|
approvalId: req.params.id,
|
||||||
|
bypassReason: req.body.bypassReason
|
||||||
});
|
});
|
||||||
return { approval };
|
return { approval };
|
||||||
}
|
}
|
||||||
@ -248,7 +253,8 @@ export const registerSecretApprovalRequestRouter = async (server: FastifyZodProv
|
|||||||
name: z.string(),
|
name: z.string(),
|
||||||
approvals: z.number(),
|
approvals: z.number(),
|
||||||
approvers: approvalRequestUser.array(),
|
approvers: approvalRequestUser.array(),
|
||||||
secretPath: z.string().optional().nullable()
|
secretPath: z.string().optional().nullable(),
|
||||||
|
enforcementLevel: z.string()
|
||||||
}),
|
}),
|
||||||
environment: z.string(),
|
environment: z.string(),
|
||||||
statusChangedByUser: approvalRequestUser.optional(),
|
statusChangedByUser: approvalRequestUser.optional(),
|
||||||
|
@ -47,7 +47,8 @@ export const accessApprovalPolicyServiceFactory = ({
|
|||||||
approvals,
|
approvals,
|
||||||
approvers,
|
approvers,
|
||||||
projectSlug,
|
projectSlug,
|
||||||
environment
|
environment,
|
||||||
|
enforcementLevel
|
||||||
}: TCreateAccessApprovalPolicy) => {
|
}: TCreateAccessApprovalPolicy) => {
|
||||||
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
|
const project = await projectDAL.findProjectBySlug(projectSlug, actorOrgId);
|
||||||
if (!project) throw new BadRequestError({ message: "Project not found" });
|
if (!project) throw new BadRequestError({ message: "Project not found" });
|
||||||
@ -94,7 +95,8 @@ export const accessApprovalPolicyServiceFactory = ({
|
|||||||
envId: env.id,
|
envId: env.id,
|
||||||
approvals,
|
approvals,
|
||||||
secretPath,
|
secretPath,
|
||||||
name
|
name,
|
||||||
|
enforcementLevel
|
||||||
},
|
},
|
||||||
tx
|
tx
|
||||||
);
|
);
|
||||||
@ -143,7 +145,8 @@ export const accessApprovalPolicyServiceFactory = ({
|
|||||||
actor,
|
actor,
|
||||||
actorOrgId,
|
actorOrgId,
|
||||||
actorAuthMethod,
|
actorAuthMethod,
|
||||||
approvals
|
approvals,
|
||||||
|
enforcementLevel
|
||||||
}: TUpdateAccessApprovalPolicy) => {
|
}: TUpdateAccessApprovalPolicy) => {
|
||||||
const accessApprovalPolicy = await accessApprovalPolicyDAL.findById(policyId);
|
const accessApprovalPolicy = await accessApprovalPolicyDAL.findById(policyId);
|
||||||
if (!accessApprovalPolicy) throw new BadRequestError({ message: "Secret approval policy not found" });
|
if (!accessApprovalPolicy) throw new BadRequestError({ message: "Secret approval policy not found" });
|
||||||
@ -163,7 +166,8 @@ export const accessApprovalPolicyServiceFactory = ({
|
|||||||
{
|
{
|
||||||
approvals,
|
approvals,
|
||||||
secretPath,
|
secretPath,
|
||||||
name
|
name,
|
||||||
|
enforcementLevel
|
||||||
},
|
},
|
||||||
tx
|
tx
|
||||||
);
|
);
|
||||||
|
@ -1,4 +1,4 @@
|
|||||||
import { TProjectPermission } from "@app/lib/types";
|
import { EnforcementLevel, TProjectPermission } from "@app/lib/types";
|
||||||
import { ActorAuthMethod } from "@app/services/auth/auth-type";
|
import { ActorAuthMethod } from "@app/services/auth/auth-type";
|
||||||
|
|
||||||
import { TPermissionServiceFactory } from "../permission/permission-service";
|
import { TPermissionServiceFactory } from "../permission/permission-service";
|
||||||
@ -20,6 +20,7 @@ export type TCreateAccessApprovalPolicy = {
|
|||||||
approvers: string[];
|
approvers: string[];
|
||||||
projectSlug: string;
|
projectSlug: string;
|
||||||
name: string;
|
name: string;
|
||||||
|
enforcementLevel: EnforcementLevel;
|
||||||
} & Omit<TProjectPermission, "projectId">;
|
} & Omit<TProjectPermission, "projectId">;
|
||||||
|
|
||||||
export type TUpdateAccessApprovalPolicy = {
|
export type TUpdateAccessApprovalPolicy = {
|
||||||
@ -28,6 +29,7 @@ export type TUpdateAccessApprovalPolicy = {
|
|||||||
approvers?: string[];
|
approvers?: string[];
|
||||||
secretPath?: string;
|
secretPath?: string;
|
||||||
name?: string;
|
name?: string;
|
||||||
|
enforcementLevel?: EnforcementLevel;
|
||||||
} & Omit<TProjectPermission, "projectId">;
|
} & Omit<TProjectPermission, "projectId">;
|
||||||
|
|
||||||
export type TDeleteAccessApprovalPolicy = {
|
export type TDeleteAccessApprovalPolicy = {
|
||||||
|
@ -48,6 +48,7 @@ export const accessApprovalRequestDALFactory = (db: TDbClient) => {
|
|||||||
db.ref("name").withSchema(TableName.AccessApprovalPolicy).as("policyName"),
|
db.ref("name").withSchema(TableName.AccessApprovalPolicy).as("policyName"),
|
||||||
db.ref("approvals").withSchema(TableName.AccessApprovalPolicy).as("policyApprovals"),
|
db.ref("approvals").withSchema(TableName.AccessApprovalPolicy).as("policyApprovals"),
|
||||||
db.ref("secretPath").withSchema(TableName.AccessApprovalPolicy).as("policySecretPath"),
|
db.ref("secretPath").withSchema(TableName.AccessApprovalPolicy).as("policySecretPath"),
|
||||||
|
db.ref("enforcementLevel").withSchema(TableName.AccessApprovalPolicy).as("policyEnforcementLevel"),
|
||||||
db.ref("envId").withSchema(TableName.AccessApprovalPolicy).as("policyEnvId")
|
db.ref("envId").withSchema(TableName.AccessApprovalPolicy).as("policyEnvId")
|
||||||
)
|
)
|
||||||
|
|
||||||
@ -98,6 +99,7 @@ export const accessApprovalRequestDALFactory = (db: TDbClient) => {
|
|||||||
name: doc.policyName,
|
name: doc.policyName,
|
||||||
approvals: doc.policyApprovals,
|
approvals: doc.policyApprovals,
|
||||||
secretPath: doc.policySecretPath,
|
secretPath: doc.policySecretPath,
|
||||||
|
enforcementLevel: doc.policyEnforcementLevel,
|
||||||
envId: doc.policyEnvId
|
envId: doc.policyEnvId
|
||||||
},
|
},
|
||||||
privilege: doc.privilegeId
|
privilege: doc.privilegeId
|
||||||
@ -165,6 +167,7 @@ export const accessApprovalRequestDALFactory = (db: TDbClient) => {
|
|||||||
tx.ref("projectId").withSchema(TableName.Environment),
|
tx.ref("projectId").withSchema(TableName.Environment),
|
||||||
tx.ref("slug").withSchema(TableName.Environment).as("environment"),
|
tx.ref("slug").withSchema(TableName.Environment).as("environment"),
|
||||||
tx.ref("secretPath").withSchema(TableName.AccessApprovalPolicy).as("policySecretPath"),
|
tx.ref("secretPath").withSchema(TableName.AccessApprovalPolicy).as("policySecretPath"),
|
||||||
|
tx.ref("enforcementLevel").withSchema(TableName.AccessApprovalPolicy).as("policyEnforcementLevel"),
|
||||||
tx.ref("approvals").withSchema(TableName.AccessApprovalPolicy).as("policyApprovals"),
|
tx.ref("approvals").withSchema(TableName.AccessApprovalPolicy).as("policyApprovals"),
|
||||||
tx.ref("approverId").withSchema(TableName.AccessApprovalPolicyApprover)
|
tx.ref("approverId").withSchema(TableName.AccessApprovalPolicyApprover)
|
||||||
);
|
);
|
||||||
@ -184,7 +187,8 @@ export const accessApprovalRequestDALFactory = (db: TDbClient) => {
|
|||||||
id: el.policyId,
|
id: el.policyId,
|
||||||
name: el.policyName,
|
name: el.policyName,
|
||||||
approvals: el.policyApprovals,
|
approvals: el.policyApprovals,
|
||||||
secretPath: el.policySecretPath
|
secretPath: el.policySecretPath,
|
||||||
|
enforcementLevel: el.policyEnforcementLevel
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
childrenMapper: [
|
childrenMapper: [
|
||||||
|
@ -106,6 +106,7 @@ export enum EventType {
|
|||||||
CREATE_ENVIRONMENT = "create-environment",
|
CREATE_ENVIRONMENT = "create-environment",
|
||||||
UPDATE_ENVIRONMENT = "update-environment",
|
UPDATE_ENVIRONMENT = "update-environment",
|
||||||
DELETE_ENVIRONMENT = "delete-environment",
|
DELETE_ENVIRONMENT = "delete-environment",
|
||||||
|
GET_ENVIRONMENT = "get-environment",
|
||||||
ADD_WORKSPACE_MEMBER = "add-workspace-member",
|
ADD_WORKSPACE_MEMBER = "add-workspace-member",
|
||||||
ADD_BATCH_WORKSPACE_MEMBER = "add-workspace-members",
|
ADD_BATCH_WORKSPACE_MEMBER = "add-workspace-members",
|
||||||
REMOVE_WORKSPACE_MEMBER = "remove-workspace-member",
|
REMOVE_WORKSPACE_MEMBER = "remove-workspace-member",
|
||||||
@ -831,6 +832,13 @@ interface CreateEnvironmentEvent {
|
|||||||
};
|
};
|
||||||
}
|
}
|
||||||
|
|
||||||
|
interface GetEnvironmentEvent {
|
||||||
|
type: EventType.GET_ENVIRONMENT;
|
||||||
|
metadata: {
|
||||||
|
id: string;
|
||||||
|
};
|
||||||
|
}
|
||||||
|
|
||||||
interface UpdateEnvironmentEvent {
|
interface UpdateEnvironmentEvent {
|
||||||
type: EventType.UPDATE_ENVIRONMENT;
|
type: EventType.UPDATE_ENVIRONMENT;
|
||||||
metadata: {
|
metadata: {
|
||||||
@ -1230,6 +1238,7 @@ export type Event =
|
|||||||
| UpdateIdentityOidcAuthEvent
|
| UpdateIdentityOidcAuthEvent
|
||||||
| GetIdentityOidcAuthEvent
|
| GetIdentityOidcAuthEvent
|
||||||
| CreateEnvironmentEvent
|
| CreateEnvironmentEvent
|
||||||
|
| GetEnvironmentEvent
|
||||||
| UpdateEnvironmentEvent
|
| UpdateEnvironmentEvent
|
||||||
| DeleteEnvironmentEvent
|
| DeleteEnvironmentEvent
|
||||||
| AddWorkspaceMemberEvent
|
| AddWorkspaceMemberEvent
|
||||||
|
@ -17,7 +17,7 @@ type TCertificateAuthorityCrlServiceFactoryDep = {
|
|||||||
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById">;
|
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById">;
|
||||||
certificateAuthorityCrlDAL: Pick<TCertificateAuthorityCrlDALFactory, "findOne">;
|
certificateAuthorityCrlDAL: Pick<TCertificateAuthorityCrlDALFactory, "findOne">;
|
||||||
projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;
|
projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;
|
||||||
kmsService: Pick<TKmsServiceFactory, "decrypt" | "generateKmsKey">;
|
kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "generateKmsKey">;
|
||||||
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
|
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
|
||||||
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
|
licenseService: Pick<TLicenseServiceFactory, "getPlan">;
|
||||||
};
|
};
|
||||||
@ -68,11 +68,11 @@ export const certificateAuthorityCrlServiceFactory = ({
|
|||||||
kmsService
|
kmsService
|
||||||
});
|
});
|
||||||
|
|
||||||
const decryptedCrl = await kmsService.decrypt({
|
const kmsDecryptor = await kmsService.decryptWithKmsKey({
|
||||||
kmsId: keyId,
|
kmsId: keyId
|
||||||
cipherTextBlob: caCrl.encryptedCrl
|
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const decryptedCrl = kmsDecryptor({ cipherTextBlob: caCrl.encryptedCrl });
|
||||||
const crl = new x509.X509Crl(decryptedCrl);
|
const crl = new x509.X509Crl(decryptedCrl);
|
||||||
|
|
||||||
const base64crl = crl.toString("base64");
|
const base64crl = crl.toString("base64");
|
||||||
|
47
backend/src/ee/services/external-kms/external-kms-dal.ts
Normal file
47
backend/src/ee/services/external-kms/external-kms-dal.ts
Normal file
@ -0,0 +1,47 @@
|
|||||||
|
import { Knex } from "knex";
|
||||||
|
|
||||||
|
import { TDbClient } from "@app/db";
|
||||||
|
import { TableName, TKmsKeys } from "@app/db/schemas";
|
||||||
|
import { DatabaseError } from "@app/lib/errors";
|
||||||
|
import { ormify, selectAllTableCols } from "@app/lib/knex";
|
||||||
|
|
||||||
|
export type TExternalKmsDALFactory = ReturnType<typeof externalKmsDALFactory>;
|
||||||
|
|
||||||
|
export const externalKmsDALFactory = (db: TDbClient) => {
|
||||||
|
const externalKmsOrm = ormify(db, TableName.ExternalKms);
|
||||||
|
|
||||||
|
const find = async (filter: Partial<TKmsKeys>, tx?: Knex) => {
|
||||||
|
try {
|
||||||
|
const result = await (tx || db.replicaNode())(TableName.ExternalKms)
|
||||||
|
.join(TableName.KmsKey, `${TableName.KmsKey}.id`, `${TableName.ExternalKms}.kmsKeyId`)
|
||||||
|
.where(filter)
|
||||||
|
.select(selectAllTableCols(TableName.KmsKey))
|
||||||
|
.select(
|
||||||
|
db.ref("id").withSchema(TableName.ExternalKms).as("externalKmsId"),
|
||||||
|
db.ref("provider").withSchema(TableName.ExternalKms).as("externalKmsProvider"),
|
||||||
|
db.ref("encryptedProviderInputs").withSchema(TableName.ExternalKms).as("externalKmsEncryptedProviderInput"),
|
||||||
|
db.ref("status").withSchema(TableName.ExternalKms).as("externalKmsStatus"),
|
||||||
|
db.ref("statusDetails").withSchema(TableName.ExternalKms).as("externalKmsStatusDetails")
|
||||||
|
);
|
||||||
|
|
||||||
|
return result.map((el) => ({
|
||||||
|
id: el.id,
|
||||||
|
description: el.description,
|
||||||
|
isDisabled: el.isDisabled,
|
||||||
|
isReserved: el.isReserved,
|
||||||
|
orgId: el.orgId,
|
||||||
|
slug: el.slug,
|
||||||
|
externalKms: {
|
||||||
|
id: el.externalKmsId,
|
||||||
|
provider: el.externalKmsProvider,
|
||||||
|
status: el.externalKmsStatus,
|
||||||
|
statusDetails: el.externalKmsStatusDetails
|
||||||
|
}
|
||||||
|
}));
|
||||||
|
} catch (error) {
|
||||||
|
throw new DatabaseError({ error, name: "Find" });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return { ...externalKmsOrm, find };
|
||||||
|
};
|
309
backend/src/ee/services/external-kms/external-kms-service.ts
Normal file
309
backend/src/ee/services/external-kms/external-kms-service.ts
Normal file
@ -0,0 +1,309 @@
|
|||||||
|
import { ForbiddenError } from "@casl/ability";
|
||||||
|
import slugify from "@sindresorhus/slugify";
|
||||||
|
|
||||||
|
import { BadRequestError } from "@app/lib/errors";
|
||||||
|
import { alphaNumericNanoId } from "@app/lib/nanoid";
|
||||||
|
import { TKmsKeyDALFactory } from "@app/services/kms/kms-key-dal";
|
||||||
|
import { TKmsServiceFactory } from "@app/services/kms/kms-service";
|
||||||
|
|
||||||
|
import { OrgPermissionActions, OrgPermissionSubjects } from "../permission/org-permission";
|
||||||
|
import { TPermissionServiceFactory } from "../permission/permission-service";
|
||||||
|
import { TExternalKmsDALFactory } from "./external-kms-dal";
|
||||||
|
import {
|
||||||
|
TCreateExternalKmsDTO,
|
||||||
|
TDeleteExternalKmsDTO,
|
||||||
|
TGetExternalKmsByIdDTO,
|
||||||
|
TGetExternalKmsBySlugDTO,
|
||||||
|
TListExternalKmsDTO,
|
||||||
|
TUpdateExternalKmsDTO
|
||||||
|
} from "./external-kms-types";
|
||||||
|
import { AwsKmsProviderFactory } from "./providers/aws-kms";
|
||||||
|
import { ExternalKmsAwsSchema, KmsProviders } from "./providers/model";
|
||||||
|
|
||||||
|
type TExternalKmsServiceFactoryDep = {
|
||||||
|
externalKmsDAL: TExternalKmsDALFactory;
|
||||||
|
kmsService: Pick<TKmsServiceFactory, "getOrgKmsKeyId" | "encryptWithKmsKey" | "decryptWithKmsKey">;
|
||||||
|
kmsDAL: Pick<TKmsKeyDALFactory, "create" | "updateById" | "findById" | "deleteById" | "findOne">;
|
||||||
|
permissionService: Pick<TPermissionServiceFactory, "getOrgPermission">;
|
||||||
|
};
|
||||||
|
|
||||||
|
export type TExternalKmsServiceFactory = ReturnType<typeof externalKmsServiceFactory>;
|
||||||
|
|
||||||
|
export const externalKmsServiceFactory = ({
|
||||||
|
externalKmsDAL,
|
||||||
|
permissionService,
|
||||||
|
kmsService,
|
||||||
|
kmsDAL
|
||||||
|
}: TExternalKmsServiceFactoryDep) => {
|
||||||
|
const create = async ({
|
||||||
|
provider,
|
||||||
|
description,
|
||||||
|
actor,
|
||||||
|
slug,
|
||||||
|
actorId,
|
||||||
|
actorOrgId,
|
||||||
|
actorAuthMethod
|
||||||
|
}: TCreateExternalKmsDTO) => {
|
||||||
|
const { permission } = await permissionService.getOrgPermission(
|
||||||
|
actor,
|
||||||
|
actorId,
|
||||||
|
actorOrgId,
|
||||||
|
actorAuthMethod,
|
||||||
|
actorOrgId
|
||||||
|
);
|
||||||
|
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.Settings);
|
||||||
|
const kmsSlug = slug ? slugify(slug) : slugify(alphaNumericNanoId(8).toLowerCase());
|
||||||
|
|
||||||
|
let sanitizedProviderInput = "";
|
||||||
|
switch (provider.type) {
|
||||||
|
case KmsProviders.Aws:
|
||||||
|
{
|
||||||
|
const externalKms = await AwsKmsProviderFactory({ inputs: provider.inputs });
|
||||||
|
await externalKms.validateConnection();
|
||||||
|
// if missing kms key this generate a new kms key id and returns new provider input
|
||||||
|
const newProviderInput = await externalKms.generateInputKmsKey();
|
||||||
|
sanitizedProviderInput = JSON.stringify(newProviderInput);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
throw new BadRequestError({ message: "external kms provided is invalid" });
|
||||||
|
}
|
||||||
|
|
||||||
|
const orgKmsKeyId = await kmsService.getOrgKmsKeyId(actorOrgId);
|
||||||
|
const kmsEncryptor = await kmsService.encryptWithKmsKey({
|
||||||
|
kmsId: orgKmsKeyId
|
||||||
|
});
|
||||||
|
const { cipherTextBlob: encryptedProviderInputs } = kmsEncryptor({
|
||||||
|
plainText: Buffer.from(sanitizedProviderInput, "utf8")
|
||||||
|
});
|
||||||
|
|
||||||
|
const externalKms = await externalKmsDAL.transaction(async (tx) => {
|
||||||
|
const kms = await kmsDAL.create(
|
||||||
|
{
|
||||||
|
isReserved: false,
|
||||||
|
description,
|
||||||
|
slug: kmsSlug,
|
||||||
|
orgId: actorOrgId
|
||||||
|
},
|
||||||
|
tx
|
||||||
|
);
|
||||||
|
const externalKmsCfg = await externalKmsDAL.create(
|
||||||
|
{
|
||||||
|
provider: provider.type,
|
||||||
|
encryptedProviderInputs,
|
||||||
|
kmsKeyId: kms.id
|
||||||
|
},
|
||||||
|
tx
|
||||||
|
);
|
||||||
|
return { ...kms, external: externalKmsCfg };
|
||||||
|
});
|
||||||
|
|
||||||
|
return externalKms;
|
||||||
|
};
|
||||||
|
|
||||||
|
const updateById = async ({
|
||||||
|
provider,
|
||||||
|
description,
|
||||||
|
actor,
|
||||||
|
id: kmsId,
|
||||||
|
slug,
|
||||||
|
actorId,
|
||||||
|
actorOrgId,
|
||||||
|
actorAuthMethod
|
||||||
|
}: TUpdateExternalKmsDTO) => {
|
||||||
|
const kmsDoc = await kmsDAL.findById(kmsId);
|
||||||
|
const { permission } = await permissionService.getOrgPermission(
|
||||||
|
actor,
|
||||||
|
actorId,
|
||||||
|
kmsDoc.orgId,
|
||||||
|
actorAuthMethod,
|
||||||
|
actorOrgId
|
||||||
|
);
|
||||||
|
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.Settings);
|
||||||
|
const kmsSlug = slug ? slugify(slug) : undefined;
|
||||||
|
|
||||||
|
const externalKmsDoc = await externalKmsDAL.findOne({ kmsKeyId: kmsDoc.id });
|
||||||
|
if (!externalKmsDoc) throw new BadRequestError({ message: "External kms not found" });
|
||||||
|
|
||||||
|
const orgDefaultKmsId = await kmsService.getOrgKmsKeyId(kmsDoc.orgId);
|
||||||
|
let sanitizedProviderInput = "";
|
||||||
|
if (provider) {
|
||||||
|
const kmsDecryptor = await kmsService.decryptWithKmsKey({
|
||||||
|
kmsId: orgDefaultKmsId
|
||||||
|
});
|
||||||
|
const decryptedProviderInputBlob = kmsDecryptor({
|
||||||
|
cipherTextBlob: externalKmsDoc.encryptedProviderInputs
|
||||||
|
});
|
||||||
|
|
||||||
|
switch (provider.type) {
|
||||||
|
case KmsProviders.Aws:
|
||||||
|
{
|
||||||
|
const decryptedProviderInput = await ExternalKmsAwsSchema.parseAsync(
|
||||||
|
JSON.parse(decryptedProviderInputBlob.toString("utf8"))
|
||||||
|
);
|
||||||
|
const updatedProviderInput = { ...decryptedProviderInput, ...provider.inputs };
|
||||||
|
const externalKms = await AwsKmsProviderFactory({ inputs: updatedProviderInput });
|
||||||
|
await externalKms.validateConnection();
|
||||||
|
sanitizedProviderInput = JSON.stringify(updatedProviderInput);
|
||||||
|
}
|
||||||
|
break;
|
||||||
|
default:
|
||||||
|
throw new BadRequestError({ message: "external kms provided is invalid" });
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let encryptedProviderInputs: Buffer | undefined;
|
||||||
|
if (sanitizedProviderInput) {
|
||||||
|
const kmsEncryptor = await kmsService.encryptWithKmsKey({
|
||||||
|
kmsId: orgDefaultKmsId
|
||||||
|
});
|
||||||
|
const { cipherTextBlob } = kmsEncryptor({
|
||||||
|
plainText: Buffer.from(sanitizedProviderInput, "utf8")
|
||||||
|
});
|
||||||
|
encryptedProviderInputs = cipherTextBlob;
|
||||||
|
}
|
||||||
|
|
||||||
|
const externalKms = await externalKmsDAL.transaction(async (tx) => {
|
||||||
|
const kms = await kmsDAL.updateById(
|
||||||
|
kmsDoc.id,
|
||||||
|
{
|
||||||
|
description,
|
||||||
|
slug: kmsSlug
|
||||||
|
},
|
||||||
|
tx
|
||||||
|
);
|
||||||
|
if (encryptedProviderInputs) {
|
||||||
|
const externalKmsCfg = await externalKmsDAL.updateById(
|
||||||
|
externalKmsDoc.id,
|
||||||
|
{
|
||||||
|
encryptedProviderInputs
|
||||||
|
},
|
||||||
|
tx
|
||||||
|
);
|
||||||
|
return { ...kms, external: externalKmsCfg };
|
||||||
|
}
|
||||||
|
return { ...kms, external: externalKmsDoc };
|
||||||
|
});
|
||||||
|
|
||||||
|
return externalKms;
|
||||||
|
};
|
||||||
|
|
||||||
|
const deleteById = async ({ actor, id: kmsId, actorId, actorOrgId, actorAuthMethod }: TDeleteExternalKmsDTO) => {
|
||||||
|
const kmsDoc = await kmsDAL.findById(kmsId);
|
||||||
|
const { permission } = await permissionService.getOrgPermission(
|
||||||
|
actor,
|
||||||
|
actorId,
|
||||||
|
kmsDoc.orgId,
|
||||||
|
actorAuthMethod,
|
||||||
|
actorOrgId
|
||||||
|
);
|
||||||
|
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.Settings);
|
||||||
|
|
||||||
|
const externalKmsDoc = await externalKmsDAL.findOne({ kmsKeyId: kmsDoc.id });
|
||||||
|
if (!externalKmsDoc) throw new BadRequestError({ message: "External kms not found" });
|
||||||
|
|
||||||
|
const externalKms = await externalKmsDAL.transaction(async (tx) => {
|
||||||
|
const kms = await kmsDAL.deleteById(kmsDoc.id, tx);
|
||||||
|
return { ...kms, external: externalKmsDoc };
|
||||||
|
});
|
||||||
|
|
||||||
|
return externalKms;
|
||||||
|
};
|
||||||
|
|
||||||
|
const list = async ({ actor, actorId, actorOrgId, actorAuthMethod }: TListExternalKmsDTO) => {
|
||||||
|
const { permission } = await permissionService.getOrgPermission(
|
||||||
|
actor,
|
||||||
|
actorId,
|
||||||
|
actorOrgId,
|
||||||
|
actorAuthMethod,
|
||||||
|
actorOrgId
|
||||||
|
);
|
||||||
|
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.Settings);
|
||||||
|
|
||||||
|
const externalKmsDocs = await externalKmsDAL.find({ orgId: actorOrgId });
|
||||||
|
|
||||||
|
return externalKmsDocs;
|
||||||
|
};
|
||||||
|
|
||||||
|
const findById = async ({ actor, actorId, actorOrgId, actorAuthMethod, id: kmsId }: TGetExternalKmsByIdDTO) => {
|
||||||
|
const kmsDoc = await kmsDAL.findById(kmsId);
|
||||||
|
const { permission } = await permissionService.getOrgPermission(
|
||||||
|
actor,
|
||||||
|
actorId,
|
||||||
|
kmsDoc.orgId,
|
||||||
|
actorAuthMethod,
|
||||||
|
actorOrgId
|
||||||
|
);
|
||||||
|
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.Settings);
|
||||||
|
|
||||||
|
const externalKmsDoc = await externalKmsDAL.findOne({ kmsKeyId: kmsDoc.id });
|
||||||
|
if (!externalKmsDoc) throw new BadRequestError({ message: "External kms not found" });
|
||||||
|
|
||||||
|
const orgDefaultKmsId = await kmsService.getOrgKmsKeyId(kmsDoc.orgId);
|
||||||
|
const kmsDecryptor = await kmsService.decryptWithKmsKey({
|
||||||
|
kmsId: orgDefaultKmsId
|
||||||
|
});
|
||||||
|
const decryptedProviderInputBlob = kmsDecryptor({
|
||||||
|
cipherTextBlob: externalKmsDoc.encryptedProviderInputs
|
||||||
|
});
|
||||||
|
switch (externalKmsDoc.provider) {
|
||||||
|
case KmsProviders.Aws: {
|
||||||
|
const decryptedProviderInput = await ExternalKmsAwsSchema.parseAsync(
|
||||||
|
JSON.parse(decryptedProviderInputBlob.toString("utf8"))
|
||||||
|
);
|
||||||
|
return { ...kmsDoc, external: { ...externalKmsDoc, providerInput: decryptedProviderInput } };
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
throw new BadRequestError({ message: "external kms provided is invalid" });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const findBySlug = async ({
|
||||||
|
actor,
|
||||||
|
actorId,
|
||||||
|
actorOrgId,
|
||||||
|
actorAuthMethod,
|
||||||
|
slug: kmsSlug
|
||||||
|
}: TGetExternalKmsBySlugDTO) => {
|
||||||
|
const kmsDoc = await kmsDAL.findOne({ slug: kmsSlug, orgId: actorOrgId });
|
||||||
|
const { permission } = await permissionService.getOrgPermission(
|
||||||
|
actor,
|
||||||
|
actorId,
|
||||||
|
kmsDoc.orgId,
|
||||||
|
actorAuthMethod,
|
||||||
|
actorOrgId
|
||||||
|
);
|
||||||
|
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.Settings);
|
||||||
|
|
||||||
|
const externalKmsDoc = await externalKmsDAL.findOne({ kmsKeyId: kmsDoc.id });
|
||||||
|
if (!externalKmsDoc) throw new BadRequestError({ message: "External kms not found" });
|
||||||
|
|
||||||
|
const orgDefaultKmsId = await kmsService.getOrgKmsKeyId(kmsDoc.orgId);
|
||||||
|
const kmsDecryptor = await kmsService.decryptWithKmsKey({
|
||||||
|
kmsId: orgDefaultKmsId
|
||||||
|
});
|
||||||
|
const decryptedProviderInputBlob = kmsDecryptor({
|
||||||
|
cipherTextBlob: externalKmsDoc.encryptedProviderInputs
|
||||||
|
});
|
||||||
|
|
||||||
|
switch (externalKmsDoc.provider) {
|
||||||
|
case KmsProviders.Aws: {
|
||||||
|
const decryptedProviderInput = await ExternalKmsAwsSchema.parseAsync(
|
||||||
|
JSON.parse(decryptedProviderInputBlob.toString("utf8"))
|
||||||
|
);
|
||||||
|
return { ...kmsDoc, external: { ...externalKmsDoc, providerInput: decryptedProviderInput } };
|
||||||
|
}
|
||||||
|
default:
|
||||||
|
throw new BadRequestError({ message: "external kms provided is invalid" });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
create,
|
||||||
|
updateById,
|
||||||
|
deleteById,
|
||||||
|
list,
|
||||||
|
findById,
|
||||||
|
findBySlug
|
||||||
|
};
|
||||||
|
};
|
30
backend/src/ee/services/external-kms/external-kms-types.ts
Normal file
30
backend/src/ee/services/external-kms/external-kms-types.ts
Normal file
@ -0,0 +1,30 @@
|
|||||||
|
import { TOrgPermission } from "@app/lib/types";
|
||||||
|
|
||||||
|
import { TExternalKmsInputSchema, TExternalKmsInputUpdateSchema } from "./providers/model";
|
||||||
|
|
||||||
|
export type TCreateExternalKmsDTO = {
|
||||||
|
slug?: string;
|
||||||
|
description?: string;
|
||||||
|
provider: TExternalKmsInputSchema;
|
||||||
|
} & Omit<TOrgPermission, "orgId">;
|
||||||
|
|
||||||
|
export type TUpdateExternalKmsDTO = {
|
||||||
|
id: string;
|
||||||
|
slug?: string;
|
||||||
|
description?: string;
|
||||||
|
provider?: TExternalKmsInputUpdateSchema;
|
||||||
|
} & Omit<TOrgPermission, "orgId">;
|
||||||
|
|
||||||
|
export type TDeleteExternalKmsDTO = {
|
||||||
|
id: string;
|
||||||
|
} & Omit<TOrgPermission, "orgId">;
|
||||||
|
|
||||||
|
export type TListExternalKmsDTO = Omit<TOrgPermission, "orgId">;
|
||||||
|
|
||||||
|
export type TGetExternalKmsByIdDTO = {
|
||||||
|
id: string;
|
||||||
|
} & Omit<TOrgPermission, "orgId">;
|
||||||
|
|
||||||
|
export type TGetExternalKmsBySlugDTO = {
|
||||||
|
slug: string;
|
||||||
|
} & Omit<TOrgPermission, "orgId">;
|
102
backend/src/ee/services/external-kms/providers/aws-kms.ts
Normal file
102
backend/src/ee/services/external-kms/providers/aws-kms.ts
Normal file
@ -0,0 +1,102 @@
|
|||||||
|
import { CreateKeyCommand, DecryptCommand, DescribeKeyCommand, EncryptCommand, KMSClient } from "@aws-sdk/client-kms";
|
||||||
|
import { AssumeRoleCommand, STSClient } from "@aws-sdk/client-sts";
|
||||||
|
import { randomUUID } from "crypto";
|
||||||
|
|
||||||
|
import { ExternalKmsAwsSchema, KmsAwsCredentialType, TExternalKmsAwsSchema, TExternalKmsProviderFns } from "./model";
|
||||||
|
|
||||||
|
const getAwsKmsClient = async (providerInputs: TExternalKmsAwsSchema) => {
|
||||||
|
if (providerInputs.credential.type === KmsAwsCredentialType.AssumeRole) {
|
||||||
|
const awsCredential = providerInputs.credential.data;
|
||||||
|
const stsClient = new STSClient({
|
||||||
|
region: providerInputs.awsRegion
|
||||||
|
});
|
||||||
|
const command = new AssumeRoleCommand({
|
||||||
|
RoleArn: awsCredential.assumeRoleArn,
|
||||||
|
RoleSessionName: `infisical-kms-${randomUUID()}`,
|
||||||
|
DurationSeconds: 900, // 15mins
|
||||||
|
ExternalId: awsCredential.externalId
|
||||||
|
});
|
||||||
|
const response = await stsClient.send(command);
|
||||||
|
if (!response.Credentials?.AccessKeyId || !response.Credentials?.SecretAccessKey)
|
||||||
|
throw new Error("Failed to assume role");
|
||||||
|
|
||||||
|
const kmsClient = new KMSClient({
|
||||||
|
region: providerInputs.awsRegion,
|
||||||
|
credentials: {
|
||||||
|
accessKeyId: response.Credentials.AccessKeyId,
|
||||||
|
secretAccessKey: response.Credentials.SecretAccessKey,
|
||||||
|
sessionToken: response.Credentials.SessionToken,
|
||||||
|
expiration: response.Credentials.Expiration
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return kmsClient;
|
||||||
|
}
|
||||||
|
const awsCredential = providerInputs.credential.data;
|
||||||
|
const kmsClient = new KMSClient({
|
||||||
|
region: providerInputs.awsRegion,
|
||||||
|
credentials: {
|
||||||
|
accessKeyId: awsCredential.accessKey,
|
||||||
|
secretAccessKey: awsCredential.secretKey
|
||||||
|
}
|
||||||
|
});
|
||||||
|
return kmsClient;
|
||||||
|
};
|
||||||
|
|
||||||
|
type AwsKmsProviderArgs = {
|
||||||
|
inputs: unknown;
|
||||||
|
};
|
||||||
|
type TAwsKmsProviderFactoryReturn = TExternalKmsProviderFns & {
|
||||||
|
generateInputKmsKey: () => Promise<TExternalKmsAwsSchema>;
|
||||||
|
};
|
||||||
|
|
||||||
|
export const AwsKmsProviderFactory = async ({ inputs }: AwsKmsProviderArgs): Promise<TAwsKmsProviderFactoryReturn> => {
|
||||||
|
const providerInputs = await ExternalKmsAwsSchema.parseAsync(inputs);
|
||||||
|
const awsClient = await getAwsKmsClient(providerInputs);
|
||||||
|
|
||||||
|
const generateInputKmsKey = async () => {
|
||||||
|
if (providerInputs.kmsKeyId) return providerInputs;
|
||||||
|
|
||||||
|
const command = new CreateKeyCommand({ Tags: [{ TagKey: "author", TagValue: "infisical" }] });
|
||||||
|
const kmsKey = await awsClient.send(command);
|
||||||
|
if (!kmsKey.KeyMetadata?.KeyId) throw new Error("Failed to generate kms key");
|
||||||
|
|
||||||
|
return { ...providerInputs, kmsKeyId: kmsKey.KeyMetadata?.KeyId };
|
||||||
|
};
|
||||||
|
|
||||||
|
const validateConnection = async () => {
|
||||||
|
const command = new DescribeKeyCommand({
|
||||||
|
KeyId: providerInputs.kmsKeyId
|
||||||
|
});
|
||||||
|
const isConnected = await awsClient.send(command).then(() => true);
|
||||||
|
return isConnected;
|
||||||
|
};
|
||||||
|
|
||||||
|
const encrypt = async (data: Buffer) => {
|
||||||
|
const command = new EncryptCommand({
|
||||||
|
KeyId: providerInputs.kmsKeyId,
|
||||||
|
Plaintext: data
|
||||||
|
});
|
||||||
|
const encryptionCommand = await awsClient.send(command);
|
||||||
|
if (!encryptionCommand.CiphertextBlob) throw new Error("encryption failed");
|
||||||
|
|
||||||
|
return { encryptedBlob: Buffer.from(encryptionCommand.CiphertextBlob) };
|
||||||
|
};
|
||||||
|
|
||||||
|
const decrypt = async (encryptedBlob: Buffer) => {
|
||||||
|
const command = new DecryptCommand({
|
||||||
|
KeyId: providerInputs.kmsKeyId,
|
||||||
|
CiphertextBlob: encryptedBlob
|
||||||
|
});
|
||||||
|
const decryptionCommand = await awsClient.send(command);
|
||||||
|
if (!decryptionCommand.Plaintext) throw new Error("decryption failed");
|
||||||
|
|
||||||
|
return { data: Buffer.from(decryptionCommand.Plaintext) };
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
generateInputKmsKey,
|
||||||
|
validateConnection,
|
||||||
|
encrypt,
|
||||||
|
decrypt
|
||||||
|
};
|
||||||
|
};
|
61
backend/src/ee/services/external-kms/providers/model.ts
Normal file
61
backend/src/ee/services/external-kms/providers/model.ts
Normal file
@ -0,0 +1,61 @@
|
|||||||
|
import { z } from "zod";
|
||||||
|
|
||||||
|
export enum KmsProviders {
|
||||||
|
Aws = "aws"
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum KmsAwsCredentialType {
|
||||||
|
AssumeRole = "assume-role",
|
||||||
|
AccessKey = "access-key"
|
||||||
|
}
|
||||||
|
|
||||||
|
export const ExternalKmsAwsSchema = z.object({
|
||||||
|
credential: z
|
||||||
|
.discriminatedUnion("type", [
|
||||||
|
z.object({
|
||||||
|
type: z.literal(KmsAwsCredentialType.AccessKey),
|
||||||
|
data: z.object({
|
||||||
|
accessKey: z.string().trim().min(1).describe("AWS user account access key"),
|
||||||
|
secretKey: z.string().trim().min(1).describe("AWS user account secret key")
|
||||||
|
})
|
||||||
|
}),
|
||||||
|
z.object({
|
||||||
|
type: z.literal(KmsAwsCredentialType.AssumeRole),
|
||||||
|
data: z.object({
|
||||||
|
assumeRoleArn: z.string().trim().min(1).describe("AWS user role to be assumed by infisical"),
|
||||||
|
externalId: z
|
||||||
|
.string()
|
||||||
|
.trim()
|
||||||
|
.min(1)
|
||||||
|
.optional()
|
||||||
|
.describe("AWS assume role external id for furthur security in authentication")
|
||||||
|
})
|
||||||
|
})
|
||||||
|
])
|
||||||
|
.describe("AWS credential information to connect"),
|
||||||
|
awsRegion: z.string().min(1).trim().describe("AWS region to connect"),
|
||||||
|
kmsKeyId: z
|
||||||
|
.string()
|
||||||
|
.trim()
|
||||||
|
.optional()
|
||||||
|
.describe("A pre existing AWS KMS key id to be used for encryption. If not provided a kms key will be generated.")
|
||||||
|
});
|
||||||
|
export type TExternalKmsAwsSchema = z.infer<typeof ExternalKmsAwsSchema>;
|
||||||
|
|
||||||
|
// The root schema of the JSON
|
||||||
|
export const ExternalKmsInputSchema = z.discriminatedUnion("type", [
|
||||||
|
z.object({ type: z.literal(KmsProviders.Aws), inputs: ExternalKmsAwsSchema })
|
||||||
|
]);
|
||||||
|
export type TExternalKmsInputSchema = z.infer<typeof ExternalKmsInputSchema>;
|
||||||
|
|
||||||
|
export const ExternalKmsInputUpdateSchema = z.discriminatedUnion("type", [
|
||||||
|
z.object({ type: z.literal(KmsProviders.Aws), inputs: ExternalKmsAwsSchema.partial() })
|
||||||
|
]);
|
||||||
|
export type TExternalKmsInputUpdateSchema = z.infer<typeof ExternalKmsInputUpdateSchema>;
|
||||||
|
|
||||||
|
// generic function shared by all provider
|
||||||
|
export type TExternalKmsProviderFns = {
|
||||||
|
validateConnection: () => Promise<boolean>;
|
||||||
|
encrypt: (data: Buffer) => Promise<{ encryptedBlob: Buffer }>;
|
||||||
|
decrypt: (encryptedBlob: Buffer) => Promise<{ data: Buffer }>;
|
||||||
|
};
|
@ -162,11 +162,60 @@ export const userGroupMembershipDALFactory = (db: TDbClient) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const findGroupMembershipsByUserIdInOrg = async (userId: string, orgId: string) => {
|
||||||
|
try {
|
||||||
|
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.Users, `${TableName.UserGroupMembership}.userId`, `${TableName.Users}.id`)
|
||||||
|
.where(`${TableName.UserGroupMembership}.userId`, userId)
|
||||||
|
.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("firstName").withSchema(TableName.Users).as("firstName"),
|
||||||
|
db.ref("lastName").withSchema(TableName.Users).as("lastName")
|
||||||
|
);
|
||||||
|
|
||||||
|
return docs;
|
||||||
|
} catch (error) {
|
||||||
|
throw new DatabaseError({ error, name: "Find group memberships by user id in org" });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
const findGroupMembershipsByGroupIdInOrg = async (groupId: string, orgId: string) => {
|
||||||
|
try {
|
||||||
|
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.Users, `${TableName.UserGroupMembership}.userId`, `${TableName.Users}.id`)
|
||||||
|
.where(`${TableName.Groups}.id`, groupId)
|
||||||
|
.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("firstName").withSchema(TableName.Users).as("firstName"),
|
||||||
|
db.ref("lastName").withSchema(TableName.Users).as("lastName")
|
||||||
|
);
|
||||||
|
return docs;
|
||||||
|
} catch (error) {
|
||||||
|
throw new DatabaseError({ error, name: "Find group memberships by group id in org" });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...userGroupMembershipOrm,
|
...userGroupMembershipOrm,
|
||||||
filterProjectsByUserMembership,
|
filterProjectsByUserMembership,
|
||||||
findUserGroupMembershipsInProject,
|
findUserGroupMembershipsInProject,
|
||||||
findGroupMembersNotInProject,
|
findGroupMembersNotInProject,
|
||||||
deletePendingUserGroupMembershipsByUserIds
|
deletePendingUserGroupMembershipsByUserIds,
|
||||||
|
findGroupMembershipsByUserIdInOrg,
|
||||||
|
findGroupMembershipsByGroupIdInOrg
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
@ -449,7 +449,8 @@ export const ldapConfigServiceFactory = ({
|
|||||||
userId: userAlias.userId,
|
userId: userAlias.userId,
|
||||||
orgId,
|
orgId,
|
||||||
role: OrgMembershipRole.Member,
|
role: OrgMembershipRole.Member,
|
||||||
status: OrgMembershipStatus.Accepted
|
status: OrgMembershipStatus.Accepted,
|
||||||
|
isActive: true
|
||||||
},
|
},
|
||||||
tx
|
tx
|
||||||
);
|
);
|
||||||
@ -534,7 +535,8 @@ export const ldapConfigServiceFactory = ({
|
|||||||
inviteEmail: email,
|
inviteEmail: email,
|
||||||
orgId,
|
orgId,
|
||||||
role: OrgMembershipRole.Member,
|
role: OrgMembershipRole.Member,
|
||||||
status: newUser.isAccepted ? OrgMembershipStatus.Accepted : OrgMembershipStatus.Invited // if user is fully completed, then set status to accepted, otherwise set it to invited so we can update it later
|
status: newUser.isAccepted ? OrgMembershipStatus.Accepted : OrgMembershipStatus.Invited, // if user is fully completed, then set status to accepted, otherwise set it to invited so we can update it later
|
||||||
|
isActive: true
|
||||||
},
|
},
|
||||||
tx
|
tx
|
||||||
);
|
);
|
||||||
|
@ -38,7 +38,8 @@ export const getDefaultOnPremFeatures = (): TFeatureSet => ({
|
|||||||
has_used_trial: true,
|
has_used_trial: true,
|
||||||
secretApproval: false,
|
secretApproval: false,
|
||||||
secretRotation: true,
|
secretRotation: true,
|
||||||
caCrl: false
|
caCrl: false,
|
||||||
|
instanceUserManagement: false
|
||||||
});
|
});
|
||||||
|
|
||||||
export const setupLicenceRequestWithStore = (baseURL: string, refreshUrl: string, licenseKey: string) => {
|
export const setupLicenceRequestWithStore = (baseURL: string, refreshUrl: string, licenseKey: string) => {
|
||||||
|
@ -218,6 +218,8 @@ export const licenseServiceFactory = ({
|
|||||||
} else if (instanceType === InstanceType.EnterpriseOnPrem) {
|
} else if (instanceType === InstanceType.EnterpriseOnPrem) {
|
||||||
const usedSeats = await licenseDAL.countOfOrgMembers(null, tx);
|
const usedSeats = await licenseDAL.countOfOrgMembers(null, tx);
|
||||||
const usedIdentitySeats = await licenseDAL.countOrgUsersAndIdentities(null, tx);
|
const usedIdentitySeats = await licenseDAL.countOrgUsersAndIdentities(null, tx);
|
||||||
|
onPremFeatures.membersUsed = usedSeats;
|
||||||
|
onPremFeatures.identitiesUsed = usedIdentitySeats;
|
||||||
await licenseServerOnPremApi.request.patch(`/api/license/v1/license`, {
|
await licenseServerOnPremApi.request.patch(`/api/license/v1/license`, {
|
||||||
usedSeats,
|
usedSeats,
|
||||||
usedIdentitySeats
|
usedIdentitySeats
|
||||||
|
@ -30,9 +30,9 @@ export type TFeatureSet = {
|
|||||||
workspacesUsed: 0;
|
workspacesUsed: 0;
|
||||||
dynamicSecret: false;
|
dynamicSecret: false;
|
||||||
memberLimit: null;
|
memberLimit: null;
|
||||||
membersUsed: 0;
|
membersUsed: number;
|
||||||
identityLimit: null;
|
identityLimit: null;
|
||||||
identitiesUsed: 0;
|
identitiesUsed: number;
|
||||||
environmentLimit: null;
|
environmentLimit: null;
|
||||||
environmentsUsed: 0;
|
environmentsUsed: 0;
|
||||||
secretVersioning: true;
|
secretVersioning: true;
|
||||||
@ -56,6 +56,7 @@ export type TFeatureSet = {
|
|||||||
secretApproval: false;
|
secretApproval: false;
|
||||||
secretRotation: true;
|
secretRotation: true;
|
||||||
caCrl: false;
|
caCrl: false;
|
||||||
|
instanceUserManagement: false;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type TOrgPlansTableDTO = {
|
export type TOrgPlansTableDTO = {
|
||||||
|
@ -193,7 +193,8 @@ export const oidcConfigServiceFactory = ({
|
|||||||
inviteEmail: email,
|
inviteEmail: email,
|
||||||
orgId,
|
orgId,
|
||||||
role: OrgMembershipRole.Member,
|
role: OrgMembershipRole.Member,
|
||||||
status: foundUser.isAccepted ? OrgMembershipStatus.Accepted : OrgMembershipStatus.Invited // if user is fully completed, then set status to accepted, otherwise set it to invited so we can update it later
|
status: foundUser.isAccepted ? OrgMembershipStatus.Accepted : OrgMembershipStatus.Invited, // if user is fully completed, then set status to accepted, otherwise set it to invited so we can update it later
|
||||||
|
isActive: true
|
||||||
},
|
},
|
||||||
tx
|
tx
|
||||||
);
|
);
|
||||||
@ -266,7 +267,8 @@ export const oidcConfigServiceFactory = ({
|
|||||||
inviteEmail: email,
|
inviteEmail: email,
|
||||||
orgId,
|
orgId,
|
||||||
role: OrgMembershipRole.Member,
|
role: OrgMembershipRole.Member,
|
||||||
status: newUser.isAccepted ? OrgMembershipStatus.Accepted : OrgMembershipStatus.Invited // if user is fully completed, then set status to accepted, otherwise set it to invited so we can update it later
|
status: newUser.isAccepted ? OrgMembershipStatus.Accepted : OrgMembershipStatus.Invited, // if user is fully completed, then set status to accepted, otherwise set it to invited so we can update it later
|
||||||
|
isActive: true
|
||||||
},
|
},
|
||||||
tx
|
tx
|
||||||
);
|
);
|
||||||
|
@ -109,6 +109,9 @@ export const permissionServiceFactory = ({
|
|||||||
authMethod: ActorAuthMethod,
|
authMethod: ActorAuthMethod,
|
||||||
userOrgId?: string
|
userOrgId?: string
|
||||||
) => {
|
) => {
|
||||||
|
// when token is scoped, ensure the passed org id is same as user org id
|
||||||
|
if (userOrgId && userOrgId !== orgId)
|
||||||
|
throw new BadRequestError({ message: "Invalid user token. Scoped to different organization." });
|
||||||
const membership = await permissionDAL.getOrgPermission(userId, orgId);
|
const membership = await permissionDAL.getOrgPermission(userId, orgId);
|
||||||
if (!membership) throw new UnauthorizedError({ name: "User not in org" });
|
if (!membership) throw new UnauthorizedError({ name: "User not in org" });
|
||||||
if (membership.role === OrgMembershipRole.Custom && !membership.permissions) {
|
if (membership.role === OrgMembershipRole.Custom && !membership.permissions) {
|
||||||
|
@ -370,7 +370,8 @@ export const samlConfigServiceFactory = ({
|
|||||||
inviteEmail: email,
|
inviteEmail: email,
|
||||||
orgId,
|
orgId,
|
||||||
role: OrgMembershipRole.Member,
|
role: OrgMembershipRole.Member,
|
||||||
status: foundUser.isAccepted ? OrgMembershipStatus.Accepted : OrgMembershipStatus.Invited // if user is fully completed, then set status to accepted, otherwise set it to invited so we can update it later
|
status: foundUser.isAccepted ? OrgMembershipStatus.Accepted : OrgMembershipStatus.Invited, // if user is fully completed, then set status to accepted, otherwise set it to invited so we can update it later
|
||||||
|
isActive: true
|
||||||
},
|
},
|
||||||
tx
|
tx
|
||||||
);
|
);
|
||||||
@ -457,7 +458,8 @@ export const samlConfigServiceFactory = ({
|
|||||||
inviteEmail: email,
|
inviteEmail: email,
|
||||||
orgId,
|
orgId,
|
||||||
role: OrgMembershipRole.Member,
|
role: OrgMembershipRole.Member,
|
||||||
status: newUser.isAccepted ? OrgMembershipStatus.Accepted : OrgMembershipStatus.Invited // if user is fully completed, then set status to accepted, otherwise set it to invited so we can update it later
|
status: newUser.isAccepted ? OrgMembershipStatus.Accepted : OrgMembershipStatus.Invited, // if user is fully completed, then set status to accepted, otherwise set it to invited so we can update it later
|
||||||
|
isActive: true
|
||||||
},
|
},
|
||||||
tx
|
tx
|
||||||
);
|
);
|
||||||
|
@ -32,12 +32,19 @@ export const parseScimFilter = (filterToParse: string | undefined) => {
|
|||||||
return { [attributeName]: parsedValue.replace(/"/g, "") };
|
return { [attributeName]: parsedValue.replace(/"/g, "") };
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export function extractScimValueFromPath(path: string): string | null {
|
||||||
|
const regex = /members\[value eq "([^"]+)"\]/;
|
||||||
|
const match = path.match(regex);
|
||||||
|
return match ? match[1] : null;
|
||||||
|
}
|
||||||
|
|
||||||
export const buildScimUser = ({
|
export const buildScimUser = ({
|
||||||
orgMembershipId,
|
orgMembershipId,
|
||||||
username,
|
username,
|
||||||
email,
|
email,
|
||||||
firstName,
|
firstName,
|
||||||
lastName,
|
lastName,
|
||||||
|
groups = [],
|
||||||
active
|
active
|
||||||
}: {
|
}: {
|
||||||
orgMembershipId: string;
|
orgMembershipId: string;
|
||||||
@ -45,6 +52,10 @@ export const buildScimUser = ({
|
|||||||
email?: string | null;
|
email?: string | null;
|
||||||
firstName: string;
|
firstName: string;
|
||||||
lastName: string;
|
lastName: string;
|
||||||
|
groups?: {
|
||||||
|
value: string;
|
||||||
|
display: string;
|
||||||
|
}[];
|
||||||
active: boolean;
|
active: boolean;
|
||||||
}): TScimUser => {
|
}): TScimUser => {
|
||||||
const scimUser = {
|
const scimUser = {
|
||||||
@ -67,7 +78,7 @@ export const buildScimUser = ({
|
|||||||
]
|
]
|
||||||
: [],
|
: [],
|
||||||
active,
|
active,
|
||||||
groups: [],
|
groups,
|
||||||
meta: {
|
meta: {
|
||||||
resourceType: "User",
|
resourceType: "User",
|
||||||
location: null
|
location: null
|
||||||
|
@ -2,13 +2,14 @@ import { ForbiddenError } from "@casl/ability";
|
|||||||
import slugify from "@sindresorhus/slugify";
|
import slugify from "@sindresorhus/slugify";
|
||||||
import jwt from "jsonwebtoken";
|
import jwt from "jsonwebtoken";
|
||||||
|
|
||||||
import { OrgMembershipRole, OrgMembershipStatus, TableName, TGroups, TOrgMemberships, TUsers } from "@app/db/schemas";
|
import { OrgMembershipRole, OrgMembershipStatus, TableName, TOrgMemberships, TUsers } from "@app/db/schemas";
|
||||||
import { TGroupDALFactory } from "@app/ee/services/group/group-dal";
|
import { TGroupDALFactory } from "@app/ee/services/group/group-dal";
|
||||||
import { addUsersToGroupByUserIds, removeUsersFromGroupByUserIds } from "@app/ee/services/group/group-fns";
|
import { addUsersToGroupByUserIds, removeUsersFromGroupByUserIds } from "@app/ee/services/group/group-fns";
|
||||||
import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
|
import { TUserGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
|
||||||
import { TScimDALFactory } from "@app/ee/services/scim/scim-dal";
|
import { TScimDALFactory } from "@app/ee/services/scim/scim-dal";
|
||||||
import { getConfig } from "@app/lib/config/env";
|
import { getConfig } from "@app/lib/config/env";
|
||||||
import { BadRequestError, ScimRequestError, UnauthorizedError } from "@app/lib/errors";
|
import { BadRequestError, ScimRequestError, UnauthorizedError } from "@app/lib/errors";
|
||||||
|
import { logger } from "@app/lib/logger";
|
||||||
import { alphaNumericNanoId } from "@app/lib/nanoid";
|
import { alphaNumericNanoId } from "@app/lib/nanoid";
|
||||||
import { TOrgPermission } from "@app/lib/types";
|
import { TOrgPermission } from "@app/lib/types";
|
||||||
import { AuthTokenType } from "@app/services/auth/auth-type";
|
import { AuthTokenType } from "@app/services/auth/auth-type";
|
||||||
@ -30,7 +31,14 @@ import { UserAliasType } from "@app/services/user-alias/user-alias-types";
|
|||||||
import { TLicenseServiceFactory } from "../license/license-service";
|
import { TLicenseServiceFactory } from "../license/license-service";
|
||||||
import { OrgPermissionActions, OrgPermissionSubjects } from "../permission/org-permission";
|
import { OrgPermissionActions, OrgPermissionSubjects } from "../permission/org-permission";
|
||||||
import { TPermissionServiceFactory } from "../permission/permission-service";
|
import { TPermissionServiceFactory } from "../permission/permission-service";
|
||||||
import { buildScimGroup, buildScimGroupList, buildScimUser, buildScimUserList, parseScimFilter } from "./scim-fns";
|
import {
|
||||||
|
buildScimGroup,
|
||||||
|
buildScimGroupList,
|
||||||
|
buildScimUser,
|
||||||
|
buildScimUserList,
|
||||||
|
extractScimValueFromPath,
|
||||||
|
parseScimFilter
|
||||||
|
} from "./scim-fns";
|
||||||
import {
|
import {
|
||||||
TCreateScimGroupDTO,
|
TCreateScimGroupDTO,
|
||||||
TCreateScimTokenDTO,
|
TCreateScimTokenDTO,
|
||||||
@ -44,6 +52,7 @@ import {
|
|||||||
TListScimUsers,
|
TListScimUsers,
|
||||||
TListScimUsersDTO,
|
TListScimUsersDTO,
|
||||||
TReplaceScimUserDTO,
|
TReplaceScimUserDTO,
|
||||||
|
TScimGroup,
|
||||||
TScimTokenJwtPayload,
|
TScimTokenJwtPayload,
|
||||||
TUpdateScimGroupNamePatchDTO,
|
TUpdateScimGroupNamePatchDTO,
|
||||||
TUpdateScimGroupNamePutDTO,
|
TUpdateScimGroupNamePutDTO,
|
||||||
@ -61,17 +70,23 @@ type TScimServiceFactoryDep = {
|
|||||||
TOrgDALFactory,
|
TOrgDALFactory,
|
||||||
"createMembership" | "findById" | "findMembership" | "deleteMembershipById" | "transaction" | "updateMembershipById"
|
"createMembership" | "findById" | "findMembership" | "deleteMembershipById" | "transaction" | "updateMembershipById"
|
||||||
>;
|
>;
|
||||||
orgMembershipDAL: Pick<TOrgMembershipDALFactory, "find" | "findOne" | "create" | "updateById">;
|
orgMembershipDAL: Pick<TOrgMembershipDALFactory, "find" | "findOne" | "create" | "updateById" | "findById">;
|
||||||
projectDAL: Pick<TProjectDALFactory, "find" | "findProjectGhostUser">;
|
projectDAL: Pick<TProjectDALFactory, "find" | "findProjectGhostUser">;
|
||||||
projectMembershipDAL: Pick<TProjectMembershipDALFactory, "find" | "delete" | "findProjectMembershipsByUserId">;
|
projectMembershipDAL: Pick<TProjectMembershipDALFactory, "find" | "delete" | "findProjectMembershipsByUserId">;
|
||||||
groupDAL: Pick<
|
groupDAL: Pick<
|
||||||
TGroupDALFactory,
|
TGroupDALFactory,
|
||||||
"create" | "findOne" | "findAllGroupMembers" | "update" | "delete" | "findGroups" | "transaction"
|
"create" | "findOne" | "findAllGroupMembers" | "delete" | "findGroups" | "transaction" | "updateById" | "update"
|
||||||
>;
|
>;
|
||||||
groupProjectDAL: Pick<TGroupProjectDALFactory, "find">;
|
groupProjectDAL: Pick<TGroupProjectDALFactory, "find">;
|
||||||
userGroupMembershipDAL: Pick<
|
userGroupMembershipDAL: Pick<
|
||||||
TUserGroupMembershipDALFactory,
|
TUserGroupMembershipDALFactory,
|
||||||
"find" | "transaction" | "insertMany" | "filterProjectsByUserMembership" | "delete"
|
| "find"
|
||||||
|
| "transaction"
|
||||||
|
| "insertMany"
|
||||||
|
| "filterProjectsByUserMembership"
|
||||||
|
| "delete"
|
||||||
|
| "findGroupMembershipsByUserIdInOrg"
|
||||||
|
| "findGroupMembershipsByGroupIdInOrg"
|
||||||
>;
|
>;
|
||||||
projectKeyDAL: Pick<TProjectKeyDALFactory, "find" | "findLatestProjectKey" | "insertMany" | "delete">;
|
projectKeyDAL: Pick<TProjectKeyDALFactory, "find" | "findLatestProjectKey" | "insertMany" | "delete">;
|
||||||
projectBotDAL: Pick<TProjectBotDALFactory, "findOne">;
|
projectBotDAL: Pick<TProjectBotDALFactory, "findOne">;
|
||||||
@ -197,14 +212,14 @@ export const scimServiceFactory = ({
|
|||||||
findOpts
|
findOpts
|
||||||
);
|
);
|
||||||
|
|
||||||
const scimUsers = users.map(({ id, externalId, username, firstName, lastName, email }) =>
|
const scimUsers = users.map(({ id, externalId, username, firstName, lastName, email, isActive }) =>
|
||||||
buildScimUser({
|
buildScimUser({
|
||||||
orgMembershipId: id ?? "",
|
orgMembershipId: id ?? "",
|
||||||
username: externalId ?? username,
|
username: externalId ?? username,
|
||||||
firstName: firstName ?? "",
|
firstName: firstName ?? "",
|
||||||
lastName: lastName ?? "",
|
lastName: lastName ?? "",
|
||||||
email,
|
email,
|
||||||
active: true
|
active: isActive
|
||||||
})
|
})
|
||||||
);
|
);
|
||||||
|
|
||||||
@ -240,13 +255,22 @@ export const scimServiceFactory = ({
|
|||||||
status: 403
|
status: 403
|
||||||
});
|
});
|
||||||
|
|
||||||
|
const groupMembershipsInOrg = await userGroupMembershipDAL.findGroupMembershipsByUserIdInOrg(
|
||||||
|
membership.userId,
|
||||||
|
orgId
|
||||||
|
);
|
||||||
|
|
||||||
return buildScimUser({
|
return buildScimUser({
|
||||||
orgMembershipId: membership.id,
|
orgMembershipId: membership.id,
|
||||||
username: membership.externalId ?? membership.username,
|
username: membership.externalId ?? membership.username,
|
||||||
email: membership.email ?? "",
|
email: membership.email ?? "",
|
||||||
firstName: membership.firstName as string,
|
firstName: membership.firstName as string,
|
||||||
lastName: membership.lastName as string,
|
lastName: membership.lastName as string,
|
||||||
active: true
|
active: membership.isActive,
|
||||||
|
groups: groupMembershipsInOrg.map((group) => ({
|
||||||
|
value: group.groupId,
|
||||||
|
display: group.groupName
|
||||||
|
}))
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -296,7 +320,8 @@ export const scimServiceFactory = ({
|
|||||||
inviteEmail: email,
|
inviteEmail: email,
|
||||||
orgId,
|
orgId,
|
||||||
role: OrgMembershipRole.Member,
|
role: OrgMembershipRole.Member,
|
||||||
status: user.isAccepted ? OrgMembershipStatus.Accepted : OrgMembershipStatus.Invited // if user is fully completed, then set status to accepted, otherwise set it to invited so we can update it later
|
status: user.isAccepted ? OrgMembershipStatus.Accepted : OrgMembershipStatus.Invited, // if user is fully completed, then set status to accepted, otherwise set it to invited so we can update it later
|
||||||
|
isActive: true
|
||||||
},
|
},
|
||||||
tx
|
tx
|
||||||
);
|
);
|
||||||
@ -364,7 +389,8 @@ export const scimServiceFactory = ({
|
|||||||
inviteEmail: email,
|
inviteEmail: email,
|
||||||
orgId,
|
orgId,
|
||||||
role: OrgMembershipRole.Member,
|
role: OrgMembershipRole.Member,
|
||||||
status: user.isAccepted ? OrgMembershipStatus.Accepted : OrgMembershipStatus.Invited // if user is fully completed, then set status to accepted, otherwise set it to invited so we can update it later
|
status: user.isAccepted ? OrgMembershipStatus.Accepted : OrgMembershipStatus.Invited, // if user is fully completed, then set status to accepted, otherwise set it to invited so we can update it later
|
||||||
|
isActive: true
|
||||||
},
|
},
|
||||||
tx
|
tx
|
||||||
);
|
);
|
||||||
@ -401,7 +427,7 @@ export const scimServiceFactory = ({
|
|||||||
firstName: createdUser.firstName as string,
|
firstName: createdUser.firstName as string,
|
||||||
lastName: createdUser.lastName as string,
|
lastName: createdUser.lastName as string,
|
||||||
email: createdUser.email ?? "",
|
email: createdUser.email ?? "",
|
||||||
active: true
|
active: createdOrgMembership.isActive
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -445,14 +471,8 @@ export const scimServiceFactory = ({
|
|||||||
});
|
});
|
||||||
|
|
||||||
if (!active) {
|
if (!active) {
|
||||||
await deleteOrgMembershipFn({
|
await orgMembershipDAL.updateById(membership.id, {
|
||||||
orgMembershipId: membership.id,
|
isActive: false
|
||||||
orgId: membership.orgId,
|
|
||||||
orgDAL,
|
|
||||||
projectMembershipDAL,
|
|
||||||
projectKeyDAL,
|
|
||||||
userAliasDAL,
|
|
||||||
licenseService
|
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -491,17 +511,14 @@ export const scimServiceFactory = ({
|
|||||||
status: 403
|
status: 403
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!active) {
|
await orgMembershipDAL.updateById(membership.id, {
|
||||||
await deleteOrgMembershipFn({
|
isActive: active
|
||||||
orgMembershipId: membership.id,
|
|
||||||
orgId: membership.orgId,
|
|
||||||
orgDAL,
|
|
||||||
projectMembershipDAL,
|
|
||||||
projectKeyDAL,
|
|
||||||
userAliasDAL,
|
|
||||||
licenseService
|
|
||||||
});
|
});
|
||||||
}
|
|
||||||
|
const groupMembershipsInOrg = await userGroupMembershipDAL.findGroupMembershipsByUserIdInOrg(
|
||||||
|
membership.userId,
|
||||||
|
orgId
|
||||||
|
);
|
||||||
|
|
||||||
return buildScimUser({
|
return buildScimUser({
|
||||||
orgMembershipId: membership.id,
|
orgMembershipId: membership.id,
|
||||||
@ -509,7 +526,11 @@ export const scimServiceFactory = ({
|
|||||||
email: membership.email,
|
email: membership.email,
|
||||||
firstName: membership.firstName as string,
|
firstName: membership.firstName as string,
|
||||||
lastName: membership.lastName as string,
|
lastName: membership.lastName as string,
|
||||||
active
|
active,
|
||||||
|
groups: groupMembershipsInOrg.map((group) => ({
|
||||||
|
value: group.groupId,
|
||||||
|
display: group.groupName
|
||||||
|
}))
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -577,13 +598,20 @@ export const scimServiceFactory = ({
|
|||||||
}
|
}
|
||||||
);
|
);
|
||||||
|
|
||||||
const scimGroups = groups.map((group) =>
|
const scimGroups: TScimGroup[] = [];
|
||||||
buildScimGroup({
|
|
||||||
|
for await (const group of groups) {
|
||||||
|
const members = await userGroupMembershipDAL.findGroupMembershipsByGroupIdInOrg(group.id, orgId);
|
||||||
|
const scimGroup = buildScimGroup({
|
||||||
groupId: group.id,
|
groupId: group.id,
|
||||||
name: group.name,
|
name: group.name,
|
||||||
members: [] // does this need to be populated?
|
members: members.map((member) => ({
|
||||||
})
|
value: member.orgMembershipId,
|
||||||
);
|
display: `${member.firstName ?? ""} ${member.lastName ?? ""}`
|
||||||
|
}))
|
||||||
|
});
|
||||||
|
scimGroups.push(scimGroup);
|
||||||
|
}
|
||||||
|
|
||||||
return buildScimGroupList({
|
return buildScimGroupList({
|
||||||
scimGroups,
|
scimGroups,
|
||||||
@ -817,7 +845,6 @@ export const scimServiceFactory = ({
|
|||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
// TODO: add support for add/remove op
|
|
||||||
const updateScimGroupNamePatch = async ({ groupId, orgId, operations }: TUpdateScimGroupNamePatchDTO) => {
|
const updateScimGroupNamePatch = async ({ groupId, orgId, operations }: TUpdateScimGroupNamePatchDTO) => {
|
||||||
const plan = await licenseService.getPlan(orgId);
|
const plan = await licenseService.getPlan(orgId);
|
||||||
if (!plan.groups)
|
if (!plan.groups)
|
||||||
@ -840,27 +867,64 @@ export const scimServiceFactory = ({
|
|||||||
status: 403
|
status: 403
|
||||||
});
|
});
|
||||||
|
|
||||||
let group: TGroups | undefined;
|
let group = await groupDAL.findOne({
|
||||||
|
id: groupId,
|
||||||
|
orgId
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!group) {
|
||||||
|
throw new ScimRequestError({
|
||||||
|
detail: "Group Not Found",
|
||||||
|
status: 404
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
for await (const operation of operations) {
|
for await (const operation of operations) {
|
||||||
switch (operation.op) {
|
switch (operation.op) {
|
||||||
case "replace": {
|
case "replace": {
|
||||||
await groupDAL.update(
|
group = await groupDAL.updateById(group.id, {
|
||||||
{
|
|
||||||
id: groupId,
|
|
||||||
orgId
|
|
||||||
},
|
|
||||||
{
|
|
||||||
name: operation.value.displayName
|
name: operation.value.displayName
|
||||||
}
|
});
|
||||||
);
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case "add": {
|
case "add": {
|
||||||
// TODO
|
try {
|
||||||
|
const orgMemberships = await orgMembershipDAL.find({
|
||||||
|
$in: {
|
||||||
|
id: operation.value.map((member) => member.value)
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
await addUsersToGroupByUserIds({
|
||||||
|
group,
|
||||||
|
userIds: orgMemberships.map((membership) => membership.userId as string),
|
||||||
|
userDAL,
|
||||||
|
userGroupMembershipDAL,
|
||||||
|
orgDAL,
|
||||||
|
groupProjectDAL,
|
||||||
|
projectKeyDAL,
|
||||||
|
projectDAL,
|
||||||
|
projectBotDAL
|
||||||
|
});
|
||||||
|
} catch {
|
||||||
|
logger.info("Repeat SCIM user-group add operation");
|
||||||
|
}
|
||||||
|
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
case "remove": {
|
case "remove": {
|
||||||
// TODO
|
const orgMembershipId = extractScimValueFromPath(operation.path);
|
||||||
|
if (!orgMembershipId) throw new ScimRequestError({ detail: "Invalid path value", status: 400 });
|
||||||
|
const orgMembership = await orgMembershipDAL.findById(orgMembershipId);
|
||||||
|
if (!orgMembership) throw new ScimRequestError({ detail: "Org Membership Not Found", status: 400 });
|
||||||
|
await removeUsersFromGroupByUserIds({
|
||||||
|
group,
|
||||||
|
userIds: [orgMembership.userId as string],
|
||||||
|
userDAL,
|
||||||
|
userGroupMembershipDAL,
|
||||||
|
groupProjectDAL,
|
||||||
|
projectKeyDAL
|
||||||
|
});
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
default: {
|
default: {
|
||||||
@ -872,17 +936,15 @@ export const scimServiceFactory = ({
|
|||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (!group) {
|
const members = await userGroupMembershipDAL.findGroupMembershipsByGroupIdInOrg(group.id, orgId);
|
||||||
throw new ScimRequestError({
|
|
||||||
detail: "Group Not Found",
|
|
||||||
status: 404
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
return buildScimGroup({
|
return buildScimGroup({
|
||||||
groupId: group.id,
|
groupId: group.id,
|
||||||
name: group.name,
|
name: group.name,
|
||||||
members: []
|
members: members.map((member) => ({
|
||||||
|
value: member.orgMembershipId,
|
||||||
|
display: `${member.firstName ?? ""} ${member.lastName ?? ""}`
|
||||||
|
}))
|
||||||
});
|
});
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -125,10 +125,11 @@ type TRemoveOp = {
|
|||||||
|
|
||||||
type TAddOp = {
|
type TAddOp = {
|
||||||
op: "add";
|
op: "add";
|
||||||
|
path: string;
|
||||||
value: {
|
value: {
|
||||||
value: string;
|
value: string;
|
||||||
display?: string;
|
display?: string;
|
||||||
};
|
}[];
|
||||||
};
|
};
|
||||||
|
|
||||||
export type TDeleteScimGroupDTO = {
|
export type TDeleteScimGroupDTO = {
|
||||||
@ -157,7 +158,10 @@ export type TScimUser = {
|
|||||||
type: string;
|
type: string;
|
||||||
}[];
|
}[];
|
||||||
active: boolean;
|
active: boolean;
|
||||||
groups: string[];
|
groups: {
|
||||||
|
value: string;
|
||||||
|
display: string;
|
||||||
|
}[];
|
||||||
meta: {
|
meta: {
|
||||||
resourceType: string;
|
resourceType: string;
|
||||||
location: null;
|
location: null;
|
||||||
|
@ -45,12 +45,13 @@ export const secretApprovalPolicyServiceFactory = ({
|
|||||||
actorOrgId,
|
actorOrgId,
|
||||||
actorAuthMethod,
|
actorAuthMethod,
|
||||||
approvals,
|
approvals,
|
||||||
approverUserIds,
|
approvers,
|
||||||
projectId,
|
projectId,
|
||||||
secretPath,
|
secretPath,
|
||||||
environment
|
environment,
|
||||||
|
enforcementLevel
|
||||||
}: TCreateSapDTO) => {
|
}: TCreateSapDTO) => {
|
||||||
if (approvals > approverUserIds.length)
|
if (approvals > approvers.length)
|
||||||
throw new BadRequestError({ message: "Approvals cannot be greater than approvers" });
|
throw new BadRequestError({ message: "Approvals cannot be greater than approvers" });
|
||||||
|
|
||||||
const { permission } = await permissionService.getProjectPermission(
|
const { permission } = await permissionService.getProjectPermission(
|
||||||
@ -73,12 +74,13 @@ export const secretApprovalPolicyServiceFactory = ({
|
|||||||
envId: env.id,
|
envId: env.id,
|
||||||
approvals,
|
approvals,
|
||||||
secretPath,
|
secretPath,
|
||||||
name
|
name,
|
||||||
|
enforcementLevel
|
||||||
},
|
},
|
||||||
tx
|
tx
|
||||||
);
|
);
|
||||||
await secretApprovalPolicyApproverDAL.insertMany(
|
await secretApprovalPolicyApproverDAL.insertMany(
|
||||||
approverUserIds.map((approverUserId) => ({
|
approvers.map((approverUserId) => ({
|
||||||
approverUserId,
|
approverUserId,
|
||||||
policyId: doc.id
|
policyId: doc.id
|
||||||
})),
|
})),
|
||||||
@ -90,7 +92,7 @@ export const secretApprovalPolicyServiceFactory = ({
|
|||||||
};
|
};
|
||||||
|
|
||||||
const updateSecretApprovalPolicy = async ({
|
const updateSecretApprovalPolicy = async ({
|
||||||
approverUserIds,
|
approvers,
|
||||||
secretPath,
|
secretPath,
|
||||||
name,
|
name,
|
||||||
actorId,
|
actorId,
|
||||||
@ -98,7 +100,8 @@ export const secretApprovalPolicyServiceFactory = ({
|
|||||||
actorOrgId,
|
actorOrgId,
|
||||||
actorAuthMethod,
|
actorAuthMethod,
|
||||||
approvals,
|
approvals,
|
||||||
secretPolicyId
|
secretPolicyId,
|
||||||
|
enforcementLevel
|
||||||
}: TUpdateSapDTO) => {
|
}: TUpdateSapDTO) => {
|
||||||
const secretApprovalPolicy = await secretApprovalPolicyDAL.findById(secretPolicyId);
|
const secretApprovalPolicy = await secretApprovalPolicyDAL.findById(secretPolicyId);
|
||||||
if (!secretApprovalPolicy) throw new BadRequestError({ message: "Secret approval policy not found" });
|
if (!secretApprovalPolicy) throw new BadRequestError({ message: "Secret approval policy not found" });
|
||||||
@ -118,14 +121,15 @@ export const secretApprovalPolicyServiceFactory = ({
|
|||||||
{
|
{
|
||||||
approvals,
|
approvals,
|
||||||
secretPath,
|
secretPath,
|
||||||
name
|
name,
|
||||||
|
enforcementLevel
|
||||||
},
|
},
|
||||||
tx
|
tx
|
||||||
);
|
);
|
||||||
if (approverUserIds) {
|
if (approvers) {
|
||||||
await secretApprovalPolicyApproverDAL.delete({ policyId: doc.id }, tx);
|
await secretApprovalPolicyApproverDAL.delete({ policyId: doc.id }, tx);
|
||||||
await secretApprovalPolicyApproverDAL.insertMany(
|
await secretApprovalPolicyApproverDAL.insertMany(
|
||||||
approverUserIds.map((approverUserId) => ({
|
approvers.map((approverUserId) => ({
|
||||||
approverUserId,
|
approverUserId,
|
||||||
policyId: doc.id
|
policyId: doc.id
|
||||||
})),
|
})),
|
||||||
|
@ -1,20 +1,22 @@
|
|||||||
import { TProjectPermission } from "@app/lib/types";
|
import { EnforcementLevel, TProjectPermission } from "@app/lib/types";
|
||||||
|
|
||||||
export type TCreateSapDTO = {
|
export type TCreateSapDTO = {
|
||||||
approvals: number;
|
approvals: number;
|
||||||
secretPath?: string | null;
|
secretPath?: string | null;
|
||||||
environment: string;
|
environment: string;
|
||||||
approverUserIds: string[];
|
approvers: string[];
|
||||||
projectId: string;
|
projectId: string;
|
||||||
name: string;
|
name: string;
|
||||||
|
enforcementLevel: EnforcementLevel;
|
||||||
} & Omit<TProjectPermission, "projectId">;
|
} & Omit<TProjectPermission, "projectId">;
|
||||||
|
|
||||||
export type TUpdateSapDTO = {
|
export type TUpdateSapDTO = {
|
||||||
secretPolicyId: string;
|
secretPolicyId: string;
|
||||||
approvals?: number;
|
approvals?: number;
|
||||||
secretPath?: string | null;
|
secretPath?: string | null;
|
||||||
approverUserIds: string[];
|
approvers: string[];
|
||||||
name?: string;
|
name?: string;
|
||||||
|
enforcementLevel?: EnforcementLevel;
|
||||||
} & Omit<TProjectPermission, "projectId">;
|
} & Omit<TProjectPermission, "projectId">;
|
||||||
|
|
||||||
export type TDeleteSapDTO = {
|
export type TDeleteSapDTO = {
|
||||||
|
@ -94,6 +94,8 @@ export const secretApprovalRequestDALFactory = (db: TDbClient) => {
|
|||||||
tx.ref("projectId").withSchema(TableName.Environment),
|
tx.ref("projectId").withSchema(TableName.Environment),
|
||||||
tx.ref("slug").withSchema(TableName.Environment).as("environment"),
|
tx.ref("slug").withSchema(TableName.Environment).as("environment"),
|
||||||
tx.ref("secretPath").withSchema(TableName.SecretApprovalPolicy).as("policySecretPath"),
|
tx.ref("secretPath").withSchema(TableName.SecretApprovalPolicy).as("policySecretPath"),
|
||||||
|
tx.ref("envId").withSchema(TableName.SecretApprovalPolicy).as("policyEnvId"),
|
||||||
|
tx.ref("enforcementLevel").withSchema(TableName.SecretApprovalPolicy).as("policyEnforcementLevel"),
|
||||||
tx.ref("approvals").withSchema(TableName.SecretApprovalPolicy).as("policyApprovals")
|
tx.ref("approvals").withSchema(TableName.SecretApprovalPolicy).as("policyApprovals")
|
||||||
);
|
);
|
||||||
|
|
||||||
@ -128,7 +130,9 @@ export const secretApprovalRequestDALFactory = (db: TDbClient) => {
|
|||||||
id: el.policyId,
|
id: el.policyId,
|
||||||
name: el.policyName,
|
name: el.policyName,
|
||||||
approvals: el.policyApprovals,
|
approvals: el.policyApprovals,
|
||||||
secretPath: el.policySecretPath
|
secretPath: el.policySecretPath,
|
||||||
|
enforcementLevel: el.policyEnforcementLevel,
|
||||||
|
envId: el.policyEnvId
|
||||||
}
|
}
|
||||||
}),
|
}),
|
||||||
childrenMapper: [
|
childrenMapper: [
|
||||||
@ -282,6 +286,7 @@ export const secretApprovalRequestDALFactory = (db: TDbClient) => {
|
|||||||
`DENSE_RANK() OVER (partition by ${TableName.Environment}."projectId" ORDER BY ${TableName.SecretApprovalRequest}."id" DESC) as rank`
|
`DENSE_RANK() OVER (partition by ${TableName.Environment}."projectId" ORDER BY ${TableName.SecretApprovalRequest}."id" DESC) as rank`
|
||||||
),
|
),
|
||||||
db.ref("secretPath").withSchema(TableName.SecretApprovalPolicy).as("policySecretPath"),
|
db.ref("secretPath").withSchema(TableName.SecretApprovalPolicy).as("policySecretPath"),
|
||||||
|
db.ref("enforcementLevel").withSchema(TableName.SecretApprovalPolicy).as("policyEnforcementLevel"),
|
||||||
db.ref("approvals").withSchema(TableName.SecretApprovalPolicy).as("policyApprovals"),
|
db.ref("approvals").withSchema(TableName.SecretApprovalPolicy).as("policyApprovals"),
|
||||||
db.ref("approverUserId").withSchema(TableName.SecretApprovalPolicyApprover),
|
db.ref("approverUserId").withSchema(TableName.SecretApprovalPolicyApprover),
|
||||||
db.ref("email").withSchema("committerUser").as("committerUserEmail"),
|
db.ref("email").withSchema("committerUser").as("committerUserEmail"),
|
||||||
@ -308,7 +313,8 @@ export const secretApprovalRequestDALFactory = (db: TDbClient) => {
|
|||||||
id: el.policyId,
|
id: el.policyId,
|
||||||
name: el.policyName,
|
name: el.policyName,
|
||||||
approvals: el.policyApprovals,
|
approvals: el.policyApprovals,
|
||||||
secretPath: el.policySecretPath
|
secretPath: el.policySecretPath,
|
||||||
|
enforcementLevel: el.policyEnforcementLevel
|
||||||
},
|
},
|
||||||
committerUser: {
|
committerUser: {
|
||||||
userId: el.committerUserId,
|
userId: el.committerUserId,
|
||||||
|
@ -7,13 +7,16 @@ import {
|
|||||||
SecretType,
|
SecretType,
|
||||||
TSecretApprovalRequestsSecretsInsert
|
TSecretApprovalRequestsSecretsInsert
|
||||||
} from "@app/db/schemas";
|
} from "@app/db/schemas";
|
||||||
|
import { getConfig } from "@app/lib/config/env";
|
||||||
import { decryptSymmetric128BitHexKeyUTF8 } from "@app/lib/crypto";
|
import { decryptSymmetric128BitHexKeyUTF8 } from "@app/lib/crypto";
|
||||||
import { BadRequestError, UnauthorizedError } from "@app/lib/errors";
|
import { BadRequestError, UnauthorizedError } from "@app/lib/errors";
|
||||||
import { groupBy, pick, unique } from "@app/lib/fn";
|
import { groupBy, pick, unique } from "@app/lib/fn";
|
||||||
import { alphaNumericNanoId } from "@app/lib/nanoid";
|
import { alphaNumericNanoId } from "@app/lib/nanoid";
|
||||||
|
import { EnforcementLevel } from "@app/lib/types";
|
||||||
import { ActorType } from "@app/services/auth/auth-type";
|
import { ActorType } from "@app/services/auth/auth-type";
|
||||||
import { TProjectDALFactory } from "@app/services/project/project-dal";
|
import { TProjectDALFactory } from "@app/services/project/project-dal";
|
||||||
import { TProjectBotServiceFactory } from "@app/services/project-bot/project-bot-service";
|
import { TProjectBotServiceFactory } from "@app/services/project-bot/project-bot-service";
|
||||||
|
import { TProjectEnvDALFactory } from "@app/services/project-env/project-env-dal";
|
||||||
import { TSecretDALFactory } from "@app/services/secret/secret-dal";
|
import { TSecretDALFactory } from "@app/services/secret/secret-dal";
|
||||||
import {
|
import {
|
||||||
fnSecretBlindIndexCheck,
|
fnSecretBlindIndexCheck,
|
||||||
@ -30,6 +33,8 @@ import { TSecretVersionTagDALFactory } from "@app/services/secret/secret-version
|
|||||||
import { TSecretBlindIndexDALFactory } from "@app/services/secret-blind-index/secret-blind-index-dal";
|
import { TSecretBlindIndexDALFactory } from "@app/services/secret-blind-index/secret-blind-index-dal";
|
||||||
import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";
|
import { TSecretFolderDALFactory } from "@app/services/secret-folder/secret-folder-dal";
|
||||||
import { TSecretTagDALFactory } from "@app/services/secret-tag/secret-tag-dal";
|
import { TSecretTagDALFactory } from "@app/services/secret-tag/secret-tag-dal";
|
||||||
|
import { SmtpTemplates, TSmtpService } from "@app/services/smtp/smtp-service";
|
||||||
|
import { TUserDALFactory } from "@app/services/user/user-dal";
|
||||||
|
|
||||||
import { TPermissionServiceFactory } from "../permission/permission-service";
|
import { TPermissionServiceFactory } from "../permission/permission-service";
|
||||||
import { ProjectPermissionActions, ProjectPermissionSub } from "../permission/project-permission";
|
import { ProjectPermissionActions, ProjectPermissionSub } from "../permission/project-permission";
|
||||||
@ -62,8 +67,11 @@ type TSecretApprovalRequestServiceFactoryDep = {
|
|||||||
snapshotService: Pick<TSecretSnapshotServiceFactory, "performSnapshot">;
|
snapshotService: Pick<TSecretSnapshotServiceFactory, "performSnapshot">;
|
||||||
secretVersionDAL: Pick<TSecretVersionDALFactory, "findLatestVersionMany" | "insertMany">;
|
secretVersionDAL: Pick<TSecretVersionDALFactory, "findLatestVersionMany" | "insertMany">;
|
||||||
secretVersionTagDAL: Pick<TSecretVersionTagDALFactory, "insertMany">;
|
secretVersionTagDAL: Pick<TSecretVersionTagDALFactory, "insertMany">;
|
||||||
projectDAL: Pick<TProjectDALFactory, "checkProjectUpgradeStatus">;
|
projectDAL: Pick<TProjectDALFactory, "checkProjectUpgradeStatus" | "findProjectById">;
|
||||||
secretQueueService: Pick<TSecretQueueFactory, "syncSecrets" | "removeSecretReminder">;
|
secretQueueService: Pick<TSecretQueueFactory, "syncSecrets" | "removeSecretReminder">;
|
||||||
|
smtpService: Pick<TSmtpService, "sendMail">;
|
||||||
|
userDAL: Pick<TUserDALFactory, "find" | "findOne">;
|
||||||
|
projectEnvDAL: Pick<TProjectEnvDALFactory, "findOne">;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type TSecretApprovalRequestServiceFactory = ReturnType<typeof secretApprovalRequestServiceFactory>;
|
export type TSecretApprovalRequestServiceFactory = ReturnType<typeof secretApprovalRequestServiceFactory>;
|
||||||
@ -82,7 +90,10 @@ export const secretApprovalRequestServiceFactory = ({
|
|||||||
snapshotService,
|
snapshotService,
|
||||||
secretVersionDAL,
|
secretVersionDAL,
|
||||||
secretQueueService,
|
secretQueueService,
|
||||||
projectBotService
|
projectBotService,
|
||||||
|
smtpService,
|
||||||
|
userDAL,
|
||||||
|
projectEnvDAL
|
||||||
}: TSecretApprovalRequestServiceFactoryDep) => {
|
}: TSecretApprovalRequestServiceFactoryDep) => {
|
||||||
const requestCount = async ({ projectId, actor, actorId, actorOrgId, actorAuthMethod }: TApprovalRequestCountDTO) => {
|
const requestCount = async ({ projectId, actor, actorId, actorOrgId, actorAuthMethod }: TApprovalRequestCountDTO) => {
|
||||||
if (actor === ActorType.SERVICE) throw new BadRequestError({ message: "Cannot use service token" });
|
if (actor === ActorType.SERVICE) throw new BadRequestError({ message: "Cannot use service token" });
|
||||||
@ -257,7 +268,8 @@ export const secretApprovalRequestServiceFactory = ({
|
|||||||
actor,
|
actor,
|
||||||
actorId,
|
actorId,
|
||||||
actorOrgId,
|
actorOrgId,
|
||||||
actorAuthMethod
|
actorAuthMethod,
|
||||||
|
bypassReason
|
||||||
}: TMergeSecretApprovalRequestDTO) => {
|
}: TMergeSecretApprovalRequestDTO) => {
|
||||||
const secretApprovalRequest = await secretApprovalRequestDAL.findById(approvalId);
|
const secretApprovalRequest = await secretApprovalRequestDAL.findById(approvalId);
|
||||||
if (!secretApprovalRequest) throw new BadRequestError({ message: "Secret approval request not found" });
|
if (!secretApprovalRequest) throw new BadRequestError({ message: "Secret approval request not found" });
|
||||||
@ -289,7 +301,10 @@ export const secretApprovalRequestServiceFactory = ({
|
|||||||
({ userId: approverId }) => reviewers[approverId.toString()] === ApprovalStatus.APPROVED
|
({ userId: approverId }) => reviewers[approverId.toString()] === ApprovalStatus.APPROVED
|
||||||
).length;
|
).length;
|
||||||
|
|
||||||
if (!hasMinApproval) throw new BadRequestError({ message: "Doesn't have minimum approvals needed" });
|
const isSoftEnforcement = secretApprovalRequest.policy.enforcementLevel === EnforcementLevel.Soft;
|
||||||
|
|
||||||
|
if (!hasMinApproval && !isSoftEnforcement)
|
||||||
|
throw new BadRequestError({ message: "Doesn't have minimum approvals needed" });
|
||||||
const secretApprovalSecrets = await secretApprovalRequestSecretDAL.findByRequestId(secretApprovalRequest.id);
|
const secretApprovalSecrets = await secretApprovalRequestSecretDAL.findByRequestId(secretApprovalRequest.id);
|
||||||
if (!secretApprovalSecrets) throw new BadRequestError({ message: "No secrets found" });
|
if (!secretApprovalSecrets) throw new BadRequestError({ message: "No secrets found" });
|
||||||
|
|
||||||
@ -466,7 +481,8 @@ export const secretApprovalRequestServiceFactory = ({
|
|||||||
conflicts: JSON.stringify(conflicts),
|
conflicts: JSON.stringify(conflicts),
|
||||||
hasMerged: true,
|
hasMerged: true,
|
||||||
status: RequestState.Closed,
|
status: RequestState.Closed,
|
||||||
statusChangedByUserId: actorId
|
statusChangedByUserId: actorId,
|
||||||
|
bypassReason
|
||||||
},
|
},
|
||||||
tx
|
tx
|
||||||
);
|
);
|
||||||
@ -485,6 +501,35 @@ export const secretApprovalRequestServiceFactory = ({
|
|||||||
actorId,
|
actorId,
|
||||||
actor
|
actor
|
||||||
});
|
});
|
||||||
|
|
||||||
|
if (isSoftEnforcement) {
|
||||||
|
const cfg = getConfig();
|
||||||
|
const project = await projectDAL.findProjectById(projectId);
|
||||||
|
const env = await projectEnvDAL.findOne({ id: policy.envId });
|
||||||
|
const requestedByUser = await userDAL.findOne({ id: actorId });
|
||||||
|
const approverUsers = await userDAL.find({
|
||||||
|
$in: {
|
||||||
|
id: policy.approvers.map((approver: { userId: string }) => approver.userId)
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
await smtpService.sendMail({
|
||||||
|
recipients: approverUsers.filter((approver) => approver.email).map((approver) => approver.email!),
|
||||||
|
subjectLine: "Infisical Secret Change Policy Bypassed",
|
||||||
|
|
||||||
|
substitutions: {
|
||||||
|
projectName: project.name,
|
||||||
|
requesterFullName: `${requestedByUser.firstName} ${requestedByUser.lastName}`,
|
||||||
|
requesterEmail: requestedByUser.email,
|
||||||
|
bypassReason,
|
||||||
|
secretPath: policy.secretPath,
|
||||||
|
environment: env.name,
|
||||||
|
approvalUrl: `${cfg.SITE_URL}/project/${project.id}/approval`
|
||||||
|
},
|
||||||
|
template: SmtpTemplates.AccessSecretRequestBypassed
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
return mergeStatus;
|
return mergeStatus;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -39,6 +39,7 @@ export type TGenerateSecretApprovalRequestDTO = {
|
|||||||
|
|
||||||
export type TMergeSecretApprovalRequestDTO = {
|
export type TMergeSecretApprovalRequestDTO = {
|
||||||
approvalId: string;
|
approvalId: string;
|
||||||
|
bypassReason?: string;
|
||||||
} & Omit<TProjectPermission, "projectId">;
|
} & Omit<TProjectPermission, "projectId">;
|
||||||
|
|
||||||
export type TStatusChangeDTO = {
|
export type TStatusChangeDTO = {
|
||||||
|
@ -348,10 +348,15 @@ export const ORGANIZATIONS = {
|
|||||||
LIST_USER_MEMBERSHIPS: {
|
LIST_USER_MEMBERSHIPS: {
|
||||||
organizationId: "The ID of the organization to get memberships from."
|
organizationId: "The ID of the organization to get memberships from."
|
||||||
},
|
},
|
||||||
|
GET_USER_MEMBERSHIP: {
|
||||||
|
organizationId: "The ID of the organization to get the membership for.",
|
||||||
|
membershipId: "The ID of the membership to get."
|
||||||
|
},
|
||||||
UPDATE_USER_MEMBERSHIP: {
|
UPDATE_USER_MEMBERSHIP: {
|
||||||
organizationId: "The ID of the organization to update the membership for.",
|
organizationId: "The ID of the organization to update the membership for.",
|
||||||
membershipId: "The ID of the membership to update.",
|
membershipId: "The ID of the membership to update.",
|
||||||
role: "The new role of the membership."
|
role: "The new role of the membership.",
|
||||||
|
isActive: "The active status of the membership"
|
||||||
},
|
},
|
||||||
DELETE_USER_MEMBERSHIP: {
|
DELETE_USER_MEMBERSHIP: {
|
||||||
organizationId: "The ID of the organization to delete the membership from.",
|
organizationId: "The ID of the organization to delete the membership from.",
|
||||||
@ -505,6 +510,10 @@ export const ENVIRONMENTS = {
|
|||||||
DELETE: {
|
DELETE: {
|
||||||
workspaceId: "The ID of the project to delete the environment from.",
|
workspaceId: "The ID of the project to delete the environment from.",
|
||||||
id: "The ID of the environment to delete."
|
id: "The ID of the environment to delete."
|
||||||
|
},
|
||||||
|
GET: {
|
||||||
|
workspaceId: "The ID of the project the environment belongs to.",
|
||||||
|
id: "The ID of the environment to fetch."
|
||||||
}
|
}
|
||||||
} as const;
|
} as const;
|
||||||
|
|
||||||
@ -515,6 +524,9 @@ export const FOLDERS = {
|
|||||||
path: "The path to list folders from.",
|
path: "The path to list folders from.",
|
||||||
directory: "The directory to list folders from. (Deprecated in favor of path)"
|
directory: "The directory to list folders from. (Deprecated in favor of path)"
|
||||||
},
|
},
|
||||||
|
GET_BY_ID: {
|
||||||
|
folderId: "The id of the folder to get details."
|
||||||
|
},
|
||||||
CREATE: {
|
CREATE: {
|
||||||
workspaceId: "The ID of the project to create the folder in.",
|
workspaceId: "The ID of the project to create the folder in.",
|
||||||
environment: "The slug of the environment to create the folder in.",
|
environment: "The slug of the environment to create the folder in.",
|
||||||
|
@ -42,3 +42,13 @@ export type RequiredKeys<T> = {
|
|||||||
}[keyof T];
|
}[keyof T];
|
||||||
|
|
||||||
export type PickRequired<T> = Pick<T, RequiredKeys<T>>;
|
export type PickRequired<T> = Pick<T, RequiredKeys<T>>;
|
||||||
|
|
||||||
|
export enum EnforcementLevel {
|
||||||
|
Hard = "hard",
|
||||||
|
Soft = "soft"
|
||||||
|
}
|
||||||
|
|
||||||
|
export enum SecretSharingAccessType {
|
||||||
|
Anyone = "anyone",
|
||||||
|
Organization = "organization"
|
||||||
|
}
|
||||||
|
@ -22,6 +22,8 @@ import { buildDynamicSecretProviders } from "@app/ee/services/dynamic-secret/pro
|
|||||||
import { dynamicSecretLeaseDALFactory } from "@app/ee/services/dynamic-secret-lease/dynamic-secret-lease-dal";
|
import { dynamicSecretLeaseDALFactory } from "@app/ee/services/dynamic-secret-lease/dynamic-secret-lease-dal";
|
||||||
import { dynamicSecretLeaseQueueServiceFactory } from "@app/ee/services/dynamic-secret-lease/dynamic-secret-lease-queue";
|
import { dynamicSecretLeaseQueueServiceFactory } from "@app/ee/services/dynamic-secret-lease/dynamic-secret-lease-queue";
|
||||||
import { dynamicSecretLeaseServiceFactory } from "@app/ee/services/dynamic-secret-lease/dynamic-secret-lease-service";
|
import { dynamicSecretLeaseServiceFactory } from "@app/ee/services/dynamic-secret-lease/dynamic-secret-lease-service";
|
||||||
|
import { externalKmsDALFactory } from "@app/ee/services/external-kms/external-kms-dal";
|
||||||
|
import { externalKmsServiceFactory } from "@app/ee/services/external-kms/external-kms-service";
|
||||||
import { groupDALFactory } from "@app/ee/services/group/group-dal";
|
import { groupDALFactory } from "@app/ee/services/group/group-dal";
|
||||||
import { groupServiceFactory } from "@app/ee/services/group/group-service";
|
import { groupServiceFactory } from "@app/ee/services/group/group-service";
|
||||||
import { userGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
|
import { userGroupMembershipDALFactory } from "@app/ee/services/group/user-group-membership-dal";
|
||||||
@ -116,7 +118,8 @@ import { integrationDALFactory } from "@app/services/integration/integration-dal
|
|||||||
import { integrationServiceFactory } from "@app/services/integration/integration-service";
|
import { integrationServiceFactory } from "@app/services/integration/integration-service";
|
||||||
import { integrationAuthDALFactory } from "@app/services/integration-auth/integration-auth-dal";
|
import { integrationAuthDALFactory } from "@app/services/integration-auth/integration-auth-dal";
|
||||||
import { integrationAuthServiceFactory } from "@app/services/integration-auth/integration-auth-service";
|
import { integrationAuthServiceFactory } from "@app/services/integration-auth/integration-auth-service";
|
||||||
import { kmsDALFactory } from "@app/services/kms/kms-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 { kmsRootConfigDALFactory } from "@app/services/kms/kms-root-config-dal";
|
||||||
import { kmsServiceFactory } from "@app/services/kms/kms-service";
|
import { kmsServiceFactory } from "@app/services/kms/kms-service";
|
||||||
import { incidentContactDALFactory } from "@app/services/org/incident-contacts-dal";
|
import { incidentContactDALFactory } from "@app/services/org/incident-contacts-dal";
|
||||||
@ -288,7 +291,9 @@ export const registerRoutes = async (
|
|||||||
const dynamicSecretDAL = dynamicSecretDALFactory(db);
|
const dynamicSecretDAL = dynamicSecretDALFactory(db);
|
||||||
const dynamicSecretLeaseDAL = dynamicSecretLeaseDALFactory(db);
|
const dynamicSecretLeaseDAL = dynamicSecretLeaseDALFactory(db);
|
||||||
|
|
||||||
const kmsDAL = kmsDALFactory(db);
|
const kmsDAL = kmskeyDALFactory(db);
|
||||||
|
const internalKmsDAL = internalKmsDALFactory(db);
|
||||||
|
const externalKmsDAL = externalKmsDALFactory(db);
|
||||||
const kmsRootConfigDAL = kmsRootConfigDALFactory(db);
|
const kmsRootConfigDAL = kmsRootConfigDALFactory(db);
|
||||||
|
|
||||||
const permissionService = permissionServiceFactory({
|
const permissionService = permissionServiceFactory({
|
||||||
@ -302,7 +307,16 @@ export const registerRoutes = async (
|
|||||||
const kmsService = kmsServiceFactory({
|
const kmsService = kmsServiceFactory({
|
||||||
kmsRootConfigDAL,
|
kmsRootConfigDAL,
|
||||||
keyStore,
|
keyStore,
|
||||||
kmsDAL
|
kmsDAL,
|
||||||
|
internalKmsDAL,
|
||||||
|
orgDAL,
|
||||||
|
projectDAL
|
||||||
|
});
|
||||||
|
const externalKmsService = externalKmsServiceFactory({
|
||||||
|
kmsDAL,
|
||||||
|
kmsService,
|
||||||
|
permissionService,
|
||||||
|
externalKmsDAL
|
||||||
});
|
});
|
||||||
|
|
||||||
const trustedIpService = trustedIpServiceFactory({
|
const trustedIpService = trustedIpServiceFactory({
|
||||||
@ -331,7 +345,7 @@ export const registerRoutes = async (
|
|||||||
permissionService,
|
permissionService,
|
||||||
secretApprovalPolicyDAL
|
secretApprovalPolicyDAL
|
||||||
});
|
});
|
||||||
const tokenService = tokenServiceFactory({ tokenDAL: authTokenDAL, userDAL });
|
const tokenService = tokenServiceFactory({ tokenDAL: authTokenDAL, userDAL, orgMembershipDAL });
|
||||||
|
|
||||||
const samlService = samlConfigServiceFactory({
|
const samlService = samlConfigServiceFactory({
|
||||||
permissionService,
|
permissionService,
|
||||||
@ -443,6 +457,7 @@ export const registerRoutes = async (
|
|||||||
tokenService,
|
tokenService,
|
||||||
projectDAL,
|
projectDAL,
|
||||||
projectMembershipDAL,
|
projectMembershipDAL,
|
||||||
|
orgMembershipDAL,
|
||||||
projectKeyDAL,
|
projectKeyDAL,
|
||||||
smtpService,
|
smtpService,
|
||||||
userDAL,
|
userDAL,
|
||||||
@ -469,7 +484,8 @@ export const registerRoutes = async (
|
|||||||
authService: loginService,
|
authService: loginService,
|
||||||
serverCfgDAL: superAdminDAL,
|
serverCfgDAL: superAdminDAL,
|
||||||
orgService,
|
orgService,
|
||||||
keyStore
|
keyStore,
|
||||||
|
licenseService
|
||||||
});
|
});
|
||||||
const rateLimitService = rateLimitServiceFactory({
|
const rateLimitService = rateLimitServiceFactory({
|
||||||
rateLimitDAL,
|
rateLimitDAL,
|
||||||
@ -644,7 +660,8 @@ export const registerRoutes = async (
|
|||||||
const webhookService = webhookServiceFactory({
|
const webhookService = webhookServiceFactory({
|
||||||
permissionService,
|
permissionService,
|
||||||
webhookDAL,
|
webhookDAL,
|
||||||
projectEnvDAL
|
projectEnvDAL,
|
||||||
|
projectDAL
|
||||||
});
|
});
|
||||||
|
|
||||||
const secretTagService = secretTagServiceFactory({ secretTagDAL, permissionService });
|
const secretTagService = secretTagServiceFactory({ secretTagDAL, permissionService });
|
||||||
@ -720,7 +737,8 @@ export const registerRoutes = async (
|
|||||||
|
|
||||||
const secretSharingService = secretSharingServiceFactory({
|
const secretSharingService = secretSharingServiceFactory({
|
||||||
permissionService,
|
permissionService,
|
||||||
secretSharingDAL
|
secretSharingDAL,
|
||||||
|
orgDAL
|
||||||
});
|
});
|
||||||
|
|
||||||
const secretApprovalRequestService = secretApprovalRequestServiceFactory({
|
const secretApprovalRequestService = secretApprovalRequestServiceFactory({
|
||||||
@ -737,7 +755,10 @@ export const registerRoutes = async (
|
|||||||
secretApprovalRequestDAL,
|
secretApprovalRequestDAL,
|
||||||
snapshotService,
|
snapshotService,
|
||||||
secretVersionTagDAL,
|
secretVersionTagDAL,
|
||||||
secretQueueService
|
secretQueueService,
|
||||||
|
smtpService,
|
||||||
|
userDAL,
|
||||||
|
projectEnvDAL
|
||||||
});
|
});
|
||||||
|
|
||||||
const accessApprovalPolicyService = accessApprovalPolicyServiceFactory({
|
const accessApprovalPolicyService = accessApprovalPolicyServiceFactory({
|
||||||
@ -1029,7 +1050,8 @@ export const registerRoutes = async (
|
|||||||
projectUserAdditionalPrivilege: projectUserAdditionalPrivilegeService,
|
projectUserAdditionalPrivilege: projectUserAdditionalPrivilegeService,
|
||||||
identityProjectAdditionalPrivilege: identityProjectAdditionalPrivilegeService,
|
identityProjectAdditionalPrivilege: identityProjectAdditionalPrivilegeService,
|
||||||
secretSharing: secretSharingService,
|
secretSharing: secretSharingService,
|
||||||
userEngagement: userEngagementService
|
userEngagement: userEngagementService,
|
||||||
|
externalKms: externalKmsService
|
||||||
});
|
});
|
||||||
|
|
||||||
const cronJobs: CronJob[] = [];
|
const cronJobs: CronJob[] = [];
|
||||||
|
@ -100,6 +100,7 @@ export const registerIdentityAwsAuthRouter = async (server: FastifyZodProvider)
|
|||||||
.number()
|
.number()
|
||||||
.int()
|
.int()
|
||||||
.min(1)
|
.min(1)
|
||||||
|
.max(315360000)
|
||||||
.refine((value) => value !== 0, {
|
.refine((value) => value !== 0, {
|
||||||
message: "accessTokenTTL must have a non zero number"
|
message: "accessTokenTTL must have a non zero number"
|
||||||
})
|
})
|
||||||
@ -108,6 +109,7 @@ export const registerIdentityAwsAuthRouter = async (server: FastifyZodProvider)
|
|||||||
accessTokenMaxTTL: z
|
accessTokenMaxTTL: z
|
||||||
.number()
|
.number()
|
||||||
.int()
|
.int()
|
||||||
|
.max(315360000)
|
||||||
.refine((value) => value !== 0, {
|
.refine((value) => value !== 0, {
|
||||||
message: "accessTokenMaxTTL must have a non zero number"
|
message: "accessTokenMaxTTL must have a non zero number"
|
||||||
})
|
})
|
||||||
@ -182,11 +184,12 @@ export const registerIdentityAwsAuthRouter = async (server: FastifyZodProvider)
|
|||||||
.min(1)
|
.min(1)
|
||||||
.optional()
|
.optional()
|
||||||
.describe(AWS_AUTH.UPDATE.accessTokenTrustedIps),
|
.describe(AWS_AUTH.UPDATE.accessTokenTrustedIps),
|
||||||
accessTokenTTL: z.number().int().min(0).optional().describe(AWS_AUTH.UPDATE.accessTokenTTL),
|
accessTokenTTL: z.number().int().min(0).max(315360000).optional().describe(AWS_AUTH.UPDATE.accessTokenTTL),
|
||||||
accessTokenNumUsesLimit: z.number().int().min(0).optional().describe(AWS_AUTH.UPDATE.accessTokenNumUsesLimit),
|
accessTokenNumUsesLimit: z.number().int().min(0).optional().describe(AWS_AUTH.UPDATE.accessTokenNumUsesLimit),
|
||||||
accessTokenMaxTTL: z
|
accessTokenMaxTTL: z
|
||||||
.number()
|
.number()
|
||||||
.int()
|
.int()
|
||||||
|
.max(315360000)
|
||||||
.refine((value) => value !== 0, {
|
.refine((value) => value !== 0, {
|
||||||
message: "accessTokenMaxTTL must have a non zero number"
|
message: "accessTokenMaxTTL must have a non zero number"
|
||||||
})
|
})
|
||||||
|
@ -90,6 +90,7 @@ export const registerIdentityAzureAuthRouter = async (server: FastifyZodProvider
|
|||||||
.number()
|
.number()
|
||||||
.int()
|
.int()
|
||||||
.min(1)
|
.min(1)
|
||||||
|
.max(315360000)
|
||||||
.refine((value) => value !== 0, {
|
.refine((value) => value !== 0, {
|
||||||
message: "accessTokenTTL must have a non zero number"
|
message: "accessTokenTTL must have a non zero number"
|
||||||
})
|
})
|
||||||
@ -98,6 +99,7 @@ export const registerIdentityAzureAuthRouter = async (server: FastifyZodProvider
|
|||||||
accessTokenMaxTTL: z
|
accessTokenMaxTTL: z
|
||||||
.number()
|
.number()
|
||||||
.int()
|
.int()
|
||||||
|
.max(315360000)
|
||||||
.refine((value) => value !== 0, {
|
.refine((value) => value !== 0, {
|
||||||
message: "accessTokenMaxTTL must have a non zero number"
|
message: "accessTokenMaxTTL must have a non zero number"
|
||||||
})
|
})
|
||||||
@ -173,11 +175,12 @@ export const registerIdentityAzureAuthRouter = async (server: FastifyZodProvider
|
|||||||
.min(1)
|
.min(1)
|
||||||
.optional()
|
.optional()
|
||||||
.describe(AZURE_AUTH.UPDATE.accessTokenTrustedIps),
|
.describe(AZURE_AUTH.UPDATE.accessTokenTrustedIps),
|
||||||
accessTokenTTL: z.number().int().min(0).optional().describe(AZURE_AUTH.UPDATE.accessTokenTTL),
|
accessTokenTTL: z.number().int().min(0).max(315360000).optional().describe(AZURE_AUTH.UPDATE.accessTokenTTL),
|
||||||
accessTokenNumUsesLimit: z.number().int().min(0).optional().describe(AZURE_AUTH.UPDATE.accessTokenNumUsesLimit),
|
accessTokenNumUsesLimit: z.number().int().min(0).optional().describe(AZURE_AUTH.UPDATE.accessTokenNumUsesLimit),
|
||||||
accessTokenMaxTTL: z
|
accessTokenMaxTTL: z
|
||||||
.number()
|
.number()
|
||||||
.int()
|
.int()
|
||||||
|
.max(315360000)
|
||||||
.refine((value) => value !== 0, {
|
.refine((value) => value !== 0, {
|
||||||
message: "accessTokenMaxTTL must have a non zero number"
|
message: "accessTokenMaxTTL must have a non zero number"
|
||||||
})
|
})
|
||||||
|
@ -91,6 +91,7 @@ export const registerIdentityGcpAuthRouter = async (server: FastifyZodProvider)
|
|||||||
.number()
|
.number()
|
||||||
.int()
|
.int()
|
||||||
.min(1)
|
.min(1)
|
||||||
|
.max(315360000)
|
||||||
.refine((value) => value !== 0, {
|
.refine((value) => value !== 0, {
|
||||||
message: "accessTokenTTL must have a non zero number"
|
message: "accessTokenTTL must have a non zero number"
|
||||||
})
|
})
|
||||||
@ -99,6 +100,7 @@ export const registerIdentityGcpAuthRouter = async (server: FastifyZodProvider)
|
|||||||
accessTokenMaxTTL: z
|
accessTokenMaxTTL: z
|
||||||
.number()
|
.number()
|
||||||
.int()
|
.int()
|
||||||
|
.max(315360000)
|
||||||
.refine((value) => value !== 0, {
|
.refine((value) => value !== 0, {
|
||||||
message: "accessTokenMaxTTL must have a non zero number"
|
message: "accessTokenMaxTTL must have a non zero number"
|
||||||
})
|
})
|
||||||
@ -175,11 +177,12 @@ export const registerIdentityGcpAuthRouter = async (server: FastifyZodProvider)
|
|||||||
.min(1)
|
.min(1)
|
||||||
.optional()
|
.optional()
|
||||||
.describe(GCP_AUTH.UPDATE.accessTokenTrustedIps),
|
.describe(GCP_AUTH.UPDATE.accessTokenTrustedIps),
|
||||||
accessTokenTTL: z.number().int().min(0).optional().describe(GCP_AUTH.UPDATE.accessTokenTTL),
|
accessTokenTTL: z.number().int().min(0).max(315360000).optional().describe(GCP_AUTH.UPDATE.accessTokenTTL),
|
||||||
accessTokenNumUsesLimit: z.number().int().min(0).optional().describe(GCP_AUTH.UPDATE.accessTokenNumUsesLimit),
|
accessTokenNumUsesLimit: z.number().int().min(0).optional().describe(GCP_AUTH.UPDATE.accessTokenNumUsesLimit),
|
||||||
accessTokenMaxTTL: z
|
accessTokenMaxTTL: z
|
||||||
.number()
|
.number()
|
||||||
.int()
|
.int()
|
||||||
|
.max(315360000)
|
||||||
.refine((value) => value !== 0, {
|
.refine((value) => value !== 0, {
|
||||||
message: "accessTokenMaxTTL must have a non zero number"
|
message: "accessTokenMaxTTL must have a non zero number"
|
||||||
})
|
})
|
||||||
|
@ -106,6 +106,7 @@ export const registerIdentityKubernetesRouter = async (server: FastifyZodProvide
|
|||||||
.number()
|
.number()
|
||||||
.int()
|
.int()
|
||||||
.min(1)
|
.min(1)
|
||||||
|
.max(315360000)
|
||||||
.refine((value) => value !== 0, {
|
.refine((value) => value !== 0, {
|
||||||
message: "accessTokenTTL must have a non zero number"
|
message: "accessTokenTTL must have a non zero number"
|
||||||
})
|
})
|
||||||
@ -114,6 +115,7 @@ export const registerIdentityKubernetesRouter = async (server: FastifyZodProvide
|
|||||||
accessTokenMaxTTL: z
|
accessTokenMaxTTL: z
|
||||||
.number()
|
.number()
|
||||||
.int()
|
.int()
|
||||||
|
.max(315360000)
|
||||||
.refine((value) => value !== 0, {
|
.refine((value) => value !== 0, {
|
||||||
message: "accessTokenMaxTTL must have a non zero number"
|
message: "accessTokenMaxTTL must have a non zero number"
|
||||||
})
|
})
|
||||||
@ -196,7 +198,13 @@ export const registerIdentityKubernetesRouter = async (server: FastifyZodProvide
|
|||||||
.min(1)
|
.min(1)
|
||||||
.optional()
|
.optional()
|
||||||
.describe(KUBERNETES_AUTH.UPDATE.accessTokenTrustedIps),
|
.describe(KUBERNETES_AUTH.UPDATE.accessTokenTrustedIps),
|
||||||
accessTokenTTL: z.number().int().min(0).optional().describe(KUBERNETES_AUTH.UPDATE.accessTokenTTL),
|
accessTokenTTL: z
|
||||||
|
.number()
|
||||||
|
.int()
|
||||||
|
.min(0)
|
||||||
|
.max(315360000)
|
||||||
|
.optional()
|
||||||
|
.describe(KUBERNETES_AUTH.UPDATE.accessTokenTTL),
|
||||||
accessTokenNumUsesLimit: z
|
accessTokenNumUsesLimit: z
|
||||||
.number()
|
.number()
|
||||||
.int()
|
.int()
|
||||||
@ -206,6 +214,7 @@ export const registerIdentityKubernetesRouter = async (server: FastifyZodProvide
|
|||||||
accessTokenMaxTTL: z
|
accessTokenMaxTTL: z
|
||||||
.number()
|
.number()
|
||||||
.int()
|
.int()
|
||||||
|
.max(315360000)
|
||||||
.refine((value) => value !== 0, {
|
.refine((value) => value !== 0, {
|
||||||
message: "accessTokenMaxTTL must have a non zero number"
|
message: "accessTokenMaxTTL must have a non zero number"
|
||||||
})
|
})
|
||||||
|
@ -106,6 +106,7 @@ export const registerIdentityOidcAuthRouter = async (server: FastifyZodProvider)
|
|||||||
.number()
|
.number()
|
||||||
.int()
|
.int()
|
||||||
.min(1)
|
.min(1)
|
||||||
|
.max(315360000)
|
||||||
.refine((value) => value !== 0, {
|
.refine((value) => value !== 0, {
|
||||||
message: "accessTokenTTL must have a non zero number"
|
message: "accessTokenTTL must have a non zero number"
|
||||||
})
|
})
|
||||||
@ -114,6 +115,7 @@ export const registerIdentityOidcAuthRouter = async (server: FastifyZodProvider)
|
|||||||
accessTokenMaxTTL: z
|
accessTokenMaxTTL: z
|
||||||
.number()
|
.number()
|
||||||
.int()
|
.int()
|
||||||
|
.max(315360000)
|
||||||
.refine((value) => value !== 0, {
|
.refine((value) => value !== 0, {
|
||||||
message: "accessTokenMaxTTL must have a non zero number"
|
message: "accessTokenMaxTTL must have a non zero number"
|
||||||
})
|
})
|
||||||
@ -201,6 +203,7 @@ export const registerIdentityOidcAuthRouter = async (server: FastifyZodProvider)
|
|||||||
.number()
|
.number()
|
||||||
.int()
|
.int()
|
||||||
.min(1)
|
.min(1)
|
||||||
|
.max(315360000)
|
||||||
.refine((value) => value !== 0, {
|
.refine((value) => value !== 0, {
|
||||||
message: "accessTokenTTL must have a non zero number"
|
message: "accessTokenTTL must have a non zero number"
|
||||||
})
|
})
|
||||||
@ -209,6 +212,7 @@ export const registerIdentityOidcAuthRouter = async (server: FastifyZodProvider)
|
|||||||
accessTokenMaxTTL: z
|
accessTokenMaxTTL: z
|
||||||
.number()
|
.number()
|
||||||
.int()
|
.int()
|
||||||
|
.max(315360000)
|
||||||
.refine((value) => value !== 0, {
|
.refine((value) => value !== 0, {
|
||||||
message: "accessTokenMaxTTL must have a non zero number"
|
message: "accessTokenMaxTTL must have a non zero number"
|
||||||
})
|
})
|
||||||
|
@ -39,6 +39,7 @@ export const registerIdentityTokenAuthRouter = async (server: FastifyZodProvider
|
|||||||
.number()
|
.number()
|
||||||
.int()
|
.int()
|
||||||
.min(1)
|
.min(1)
|
||||||
|
.max(315360000)
|
||||||
.refine((value) => value !== 0, {
|
.refine((value) => value !== 0, {
|
||||||
message: "accessTokenTTL must have a non zero number"
|
message: "accessTokenTTL must have a non zero number"
|
||||||
})
|
})
|
||||||
@ -47,6 +48,7 @@ export const registerIdentityTokenAuthRouter = async (server: FastifyZodProvider
|
|||||||
accessTokenMaxTTL: z
|
accessTokenMaxTTL: z
|
||||||
.number()
|
.number()
|
||||||
.int()
|
.int()
|
||||||
|
.max(315360000)
|
||||||
.refine((value) => value !== 0, {
|
.refine((value) => value !== 0, {
|
||||||
message: "accessTokenMaxTTL must have a non zero number"
|
message: "accessTokenMaxTTL must have a non zero number"
|
||||||
})
|
})
|
||||||
@ -117,11 +119,12 @@ export const registerIdentityTokenAuthRouter = async (server: FastifyZodProvider
|
|||||||
.min(1)
|
.min(1)
|
||||||
.optional()
|
.optional()
|
||||||
.describe(TOKEN_AUTH.UPDATE.accessTokenTrustedIps),
|
.describe(TOKEN_AUTH.UPDATE.accessTokenTrustedIps),
|
||||||
accessTokenTTL: z.number().int().min(0).optional().describe(TOKEN_AUTH.UPDATE.accessTokenTTL),
|
accessTokenTTL: z.number().int().min(0).max(315360000).optional().describe(TOKEN_AUTH.UPDATE.accessTokenTTL),
|
||||||
accessTokenNumUsesLimit: z.number().int().min(0).optional().describe(TOKEN_AUTH.UPDATE.accessTokenNumUsesLimit),
|
accessTokenNumUsesLimit: z.number().int().min(0).optional().describe(TOKEN_AUTH.UPDATE.accessTokenNumUsesLimit),
|
||||||
accessTokenMaxTTL: z
|
accessTokenMaxTTL: z
|
||||||
.number()
|
.number()
|
||||||
.int()
|
.int()
|
||||||
|
.max(315360000)
|
||||||
.refine((value) => value !== 0, {
|
.refine((value) => value !== 0, {
|
||||||
message: "accessTokenMaxTTL must have a non zero number"
|
message: "accessTokenMaxTTL must have a non zero number"
|
||||||
})
|
})
|
||||||
|
@ -107,6 +107,7 @@ export const registerIdentityUaRouter = async (server: FastifyZodProvider) => {
|
|||||||
.number()
|
.number()
|
||||||
.int()
|
.int()
|
||||||
.min(1)
|
.min(1)
|
||||||
|
.max(315360000)
|
||||||
.refine((value) => value !== 0, {
|
.refine((value) => value !== 0, {
|
||||||
message: "accessTokenTTL must have a non zero number"
|
message: "accessTokenTTL must have a non zero number"
|
||||||
})
|
})
|
||||||
@ -115,6 +116,7 @@ export const registerIdentityUaRouter = async (server: FastifyZodProvider) => {
|
|||||||
accessTokenMaxTTL: z
|
accessTokenMaxTTL: z
|
||||||
.number()
|
.number()
|
||||||
.int()
|
.int()
|
||||||
|
.max(315360000)
|
||||||
.refine((value) => value !== 0, {
|
.refine((value) => value !== 0, {
|
||||||
message: "accessTokenMaxTTL must have a non zero number"
|
message: "accessTokenMaxTTL must have a non zero number"
|
||||||
})
|
})
|
||||||
@ -196,7 +198,13 @@ export const registerIdentityUaRouter = async (server: FastifyZodProvider) => {
|
|||||||
.min(1)
|
.min(1)
|
||||||
.optional()
|
.optional()
|
||||||
.describe(UNIVERSAL_AUTH.UPDATE.accessTokenTrustedIps),
|
.describe(UNIVERSAL_AUTH.UPDATE.accessTokenTrustedIps),
|
||||||
accessTokenTTL: z.number().int().min(0).optional().describe(UNIVERSAL_AUTH.UPDATE.accessTokenTTL),
|
accessTokenTTL: z
|
||||||
|
.number()
|
||||||
|
.int()
|
||||||
|
.min(0)
|
||||||
|
.max(315360000)
|
||||||
|
.optional()
|
||||||
|
.describe(UNIVERSAL_AUTH.UPDATE.accessTokenTTL),
|
||||||
accessTokenNumUsesLimit: z
|
accessTokenNumUsesLimit: z
|
||||||
.number()
|
.number()
|
||||||
.int()
|
.int()
|
||||||
@ -206,6 +214,7 @@ export const registerIdentityUaRouter = async (server: FastifyZodProvider) => {
|
|||||||
accessTokenMaxTTL: z
|
accessTokenMaxTTL: z
|
||||||
.number()
|
.number()
|
||||||
.int()
|
.int()
|
||||||
|
.max(315360000)
|
||||||
.refine((value) => value !== 0, {
|
.refine((value) => value !== 0, {
|
||||||
message: "accessTokenMaxTTL must have a non zero number"
|
message: "accessTokenMaxTTL must have a non zero number"
|
||||||
})
|
})
|
||||||
@ -362,7 +371,7 @@ export const registerIdentityUaRouter = async (server: FastifyZodProvider) => {
|
|||||||
body: z.object({
|
body: z.object({
|
||||||
description: z.string().trim().default("").describe(UNIVERSAL_AUTH.CREATE_CLIENT_SECRET.description),
|
description: z.string().trim().default("").describe(UNIVERSAL_AUTH.CREATE_CLIENT_SECRET.description),
|
||||||
numUsesLimit: z.number().min(0).default(0).describe(UNIVERSAL_AUTH.CREATE_CLIENT_SECRET.numUsesLimit),
|
numUsesLimit: z.number().min(0).default(0).describe(UNIVERSAL_AUTH.CREATE_CLIENT_SECRET.numUsesLimit),
|
||||||
ttl: z.number().min(0).default(0).describe(UNIVERSAL_AUTH.CREATE_CLIENT_SECRET.ttl)
|
ttl: z.number().min(0).max(315360000).default(0).describe(UNIVERSAL_AUTH.CREATE_CLIENT_SECRET.ttl)
|
||||||
}),
|
}),
|
||||||
response: {
|
response: {
|
||||||
200: z.object({
|
200: z.object({
|
||||||
|
@ -9,6 +9,55 @@ import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
|||||||
import { AuthMode } from "@app/services/auth/auth-type";
|
import { AuthMode } from "@app/services/auth/auth-type";
|
||||||
|
|
||||||
export const registerProjectEnvRouter = async (server: FastifyZodProvider) => {
|
export const registerProjectEnvRouter = async (server: FastifyZodProvider) => {
|
||||||
|
server.route({
|
||||||
|
method: "GET",
|
||||||
|
url: "/:workspaceId/environments/:envId",
|
||||||
|
config: {
|
||||||
|
rateLimit: writeLimit
|
||||||
|
},
|
||||||
|
schema: {
|
||||||
|
description: "Get Environment",
|
||||||
|
security: [
|
||||||
|
{
|
||||||
|
bearerAuth: []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
params: z.object({
|
||||||
|
workspaceId: z.string().trim().describe(ENVIRONMENTS.GET.workspaceId),
|
||||||
|
envId: z.string().trim().describe(ENVIRONMENTS.GET.id)
|
||||||
|
}),
|
||||||
|
response: {
|
||||||
|
200: z.object({
|
||||||
|
environment: ProjectEnvironmentsSchema
|
||||||
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||||
|
handler: async (req) => {
|
||||||
|
const environment = await server.services.projectEnv.getEnvironmentById({
|
||||||
|
actorId: req.permission.id,
|
||||||
|
actor: req.permission.type,
|
||||||
|
actorOrgId: req.permission.orgId,
|
||||||
|
actorAuthMethod: req.permission.authMethod,
|
||||||
|
projectId: req.params.workspaceId,
|
||||||
|
id: req.params.envId
|
||||||
|
});
|
||||||
|
|
||||||
|
await server.services.auditLog.createAuditLog({
|
||||||
|
...req.auditLogInfo,
|
||||||
|
projectId: environment.projectId,
|
||||||
|
event: {
|
||||||
|
type: EventType.GET_ENVIRONMENT,
|
||||||
|
metadata: {
|
||||||
|
id: environment.id
|
||||||
|
}
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
return { environment };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
server.route({
|
server.route({
|
||||||
method: "POST",
|
method: "POST",
|
||||||
url: "/:workspaceId/environments",
|
url: "/:workspaceId/environments",
|
||||||
|
@ -78,6 +78,7 @@ export const registerProjectRouter = async (server: FastifyZodProvider) => {
|
|||||||
lastName: true,
|
lastName: true,
|
||||||
id: true
|
id: true
|
||||||
}).merge(UserEncryptionKeysSchema.pick({ publicKey: true })),
|
}).merge(UserEncryptionKeysSchema.pick({ publicKey: true })),
|
||||||
|
project: ProjectsSchema.pick({ name: true, id: true }),
|
||||||
roles: z.array(
|
roles: z.array(
|
||||||
z.object({
|
z.object({
|
||||||
id: z.string(),
|
id: z.string(),
|
||||||
|
@ -292,4 +292,39 @@ export const registerSecretFolderRouter = async (server: FastifyZodProvider) =>
|
|||||||
return { folders };
|
return { folders };
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
server.route({
|
||||||
|
method: "GET",
|
||||||
|
url: "/:id",
|
||||||
|
config: {
|
||||||
|
rateLimit: readLimit
|
||||||
|
},
|
||||||
|
schema: {
|
||||||
|
description: "Get folder by id",
|
||||||
|
security: [
|
||||||
|
{
|
||||||
|
bearerAuth: []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
params: z.object({
|
||||||
|
id: z.string().trim().describe(FOLDERS.GET_BY_ID.folderId)
|
||||||
|
}),
|
||||||
|
response: {
|
||||||
|
200: z.object({
|
||||||
|
folder: SecretFoldersSchema
|
||||||
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.SERVICE_TOKEN, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||||
|
handler: async (req) => {
|
||||||
|
const folder = await server.services.folder.getFolderById({
|
||||||
|
actorId: req.permission.id,
|
||||||
|
actor: req.permission.type,
|
||||||
|
actorAuthMethod: req.permission.authMethod,
|
||||||
|
actorOrgId: req.permission.orgId,
|
||||||
|
id: req.params.id
|
||||||
|
});
|
||||||
|
return { folder };
|
||||||
|
}
|
||||||
|
});
|
||||||
};
|
};
|
||||||
|
@ -1,6 +1,7 @@
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
import { SecretSharingSchema } from "@app/db/schemas";
|
import { SecretSharingSchema } from "@app/db/schemas";
|
||||||
|
import { SecretSharingAccessType } from "@app/lib/types";
|
||||||
import {
|
import {
|
||||||
publicEndpointLimit,
|
publicEndpointLimit,
|
||||||
publicSecretShareCreationLimit,
|
publicSecretShareCreationLimit,
|
||||||
@ -55,14 +56,18 @@ export const registerSecretSharingRouter = async (server: FastifyZodProvider) =>
|
|||||||
iv: true,
|
iv: true,
|
||||||
tag: true,
|
tag: true,
|
||||||
expiresAt: true,
|
expiresAt: true,
|
||||||
expiresAfterViews: true
|
expiresAfterViews: true,
|
||||||
|
accessType: true
|
||||||
|
}).extend({
|
||||||
|
orgName: z.string().optional()
|
||||||
})
|
})
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
handler: async (req) => {
|
handler: async (req) => {
|
||||||
const sharedSecret = await req.server.services.secretSharing.getActiveSharedSecretByIdAndHashedHex(
|
const sharedSecret = await req.server.services.secretSharing.getActiveSharedSecretByIdAndHashedHex(
|
||||||
req.params.id,
|
req.params.id,
|
||||||
req.query.hashedHex
|
req.query.hashedHex,
|
||||||
|
req.permission?.orgId
|
||||||
);
|
);
|
||||||
if (!sharedSecret) return undefined;
|
if (!sharedSecret) return undefined;
|
||||||
return {
|
return {
|
||||||
@ -70,7 +75,9 @@ export const registerSecretSharingRouter = async (server: FastifyZodProvider) =>
|
|||||||
iv: sharedSecret.iv,
|
iv: sharedSecret.iv,
|
||||||
tag: sharedSecret.tag,
|
tag: sharedSecret.tag,
|
||||||
expiresAt: sharedSecret.expiresAt,
|
expiresAt: sharedSecret.expiresAt,
|
||||||
expiresAfterViews: sharedSecret.expiresAfterViews
|
expiresAfterViews: sharedSecret.expiresAfterViews,
|
||||||
|
accessType: sharedSecret.accessType,
|
||||||
|
orgName: sharedSecret.orgName
|
||||||
};
|
};
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
@ -104,7 +111,8 @@ export const registerSecretSharingRouter = async (server: FastifyZodProvider) =>
|
|||||||
tag,
|
tag,
|
||||||
hashedHex,
|
hashedHex,
|
||||||
expiresAt: new Date(expiresAt),
|
expiresAt: new Date(expiresAt),
|
||||||
expiresAfterViews
|
expiresAfterViews,
|
||||||
|
accessType: SecretSharingAccessType.Anyone
|
||||||
});
|
});
|
||||||
return { id: sharedSecret.id };
|
return { id: sharedSecret.id };
|
||||||
}
|
}
|
||||||
@ -123,7 +131,8 @@ export const registerSecretSharingRouter = async (server: FastifyZodProvider) =>
|
|||||||
tag: z.string(),
|
tag: z.string(),
|
||||||
hashedHex: z.string(),
|
hashedHex: z.string(),
|
||||||
expiresAt: z.string(),
|
expiresAt: z.string(),
|
||||||
expiresAfterViews: z.number()
|
expiresAfterViews: z.number(),
|
||||||
|
accessType: z.nativeEnum(SecretSharingAccessType).default(SecretSharingAccessType.Organization)
|
||||||
}),
|
}),
|
||||||
response: {
|
response: {
|
||||||
200: z.object({
|
200: z.object({
|
||||||
@ -145,7 +154,8 @@ export const registerSecretSharingRouter = async (server: FastifyZodProvider) =>
|
|||||||
tag,
|
tag,
|
||||||
hashedHex,
|
hashedHex,
|
||||||
expiresAt: new Date(expiresAt),
|
expiresAt: new Date(expiresAt),
|
||||||
expiresAfterViews
|
expiresAfterViews,
|
||||||
|
accessType: req.body.accessType
|
||||||
});
|
});
|
||||||
return { id: sharedSecret.id };
|
return { id: sharedSecret.id };
|
||||||
}
|
}
|
||||||
|
@ -1,6 +1,13 @@
|
|||||||
import { z } from "zod";
|
import { z } from "zod";
|
||||||
|
|
||||||
import { OrganizationsSchema, OrgMembershipsSchema, UserEncryptionKeysSchema, UsersSchema } from "@app/db/schemas";
|
import {
|
||||||
|
OrganizationsSchema,
|
||||||
|
OrgMembershipsSchema,
|
||||||
|
ProjectMembershipsSchema,
|
||||||
|
ProjectsSchema,
|
||||||
|
UserEncryptionKeysSchema,
|
||||||
|
UsersSchema
|
||||||
|
} from "@app/db/schemas";
|
||||||
import { ORGANIZATIONS } from "@app/lib/api-docs";
|
import { ORGANIZATIONS } from "@app/lib/api-docs";
|
||||||
import { creationLimit, readLimit, writeLimit } from "@app/server/config/rateLimiter";
|
import { creationLimit, readLimit, writeLimit } from "@app/server/config/rateLimiter";
|
||||||
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
import { verifyAuth } from "@app/server/plugins/auth/verify-auth";
|
||||||
@ -30,6 +37,7 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {
|
|||||||
user: UsersSchema.pick({
|
user: UsersSchema.pick({
|
||||||
username: true,
|
username: true,
|
||||||
email: true,
|
email: true,
|
||||||
|
isEmailVerified: true,
|
||||||
firstName: true,
|
firstName: true,
|
||||||
lastName: true,
|
lastName: true,
|
||||||
id: true
|
id: true
|
||||||
@ -103,6 +111,54 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
server.route({
|
||||||
|
method: "GET",
|
||||||
|
url: "/:organizationId/memberships/:membershipId",
|
||||||
|
config: {
|
||||||
|
rateLimit: writeLimit
|
||||||
|
},
|
||||||
|
schema: {
|
||||||
|
description: "Get organization user membership",
|
||||||
|
security: [
|
||||||
|
{
|
||||||
|
bearerAuth: []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
params: z.object({
|
||||||
|
organizationId: z.string().trim().describe(ORGANIZATIONS.GET_USER_MEMBERSHIP.organizationId),
|
||||||
|
membershipId: z.string().trim().describe(ORGANIZATIONS.GET_USER_MEMBERSHIP.membershipId)
|
||||||
|
}),
|
||||||
|
response: {
|
||||||
|
200: z.object({
|
||||||
|
membership: OrgMembershipsSchema.merge(
|
||||||
|
z.object({
|
||||||
|
user: UsersSchema.pick({
|
||||||
|
username: true,
|
||||||
|
email: true,
|
||||||
|
isEmailVerified: true,
|
||||||
|
firstName: true,
|
||||||
|
lastName: true,
|
||||||
|
id: true
|
||||||
|
}).merge(z.object({ publicKey: z.string().nullable() }))
|
||||||
|
})
|
||||||
|
).omit({ createdAt: true, updatedAt: true })
|
||||||
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||||
|
handler: async (req) => {
|
||||||
|
const membership = await server.services.org.getOrgMembership({
|
||||||
|
actor: req.permission.type,
|
||||||
|
actorId: req.permission.id,
|
||||||
|
actorAuthMethod: req.permission.authMethod,
|
||||||
|
actorOrgId: req.permission.orgId,
|
||||||
|
orgId: req.params.organizationId,
|
||||||
|
membershipId: req.params.membershipId
|
||||||
|
});
|
||||||
|
return { membership };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
server.route({
|
server.route({
|
||||||
method: "PATCH",
|
method: "PATCH",
|
||||||
url: "/:organizationId/memberships/:membershipId",
|
url: "/:organizationId/memberships/:membershipId",
|
||||||
@ -121,7 +177,8 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {
|
|||||||
membershipId: z.string().trim().describe(ORGANIZATIONS.UPDATE_USER_MEMBERSHIP.membershipId)
|
membershipId: z.string().trim().describe(ORGANIZATIONS.UPDATE_USER_MEMBERSHIP.membershipId)
|
||||||
}),
|
}),
|
||||||
body: z.object({
|
body: z.object({
|
||||||
role: z.string().trim().describe(ORGANIZATIONS.UPDATE_USER_MEMBERSHIP.role)
|
role: z.string().trim().optional().describe(ORGANIZATIONS.UPDATE_USER_MEMBERSHIP.role),
|
||||||
|
isActive: z.boolean().optional().describe(ORGANIZATIONS.UPDATE_USER_MEMBERSHIP.isActive)
|
||||||
}),
|
}),
|
||||||
response: {
|
response: {
|
||||||
200: z.object({
|
200: z.object({
|
||||||
@ -129,17 +186,17 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {
|
|||||||
})
|
})
|
||||||
}
|
}
|
||||||
},
|
},
|
||||||
onRequest: verifyAuth([AuthMode.JWT, AuthMode.API_KEY, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||||
handler: async (req) => {
|
handler: async (req) => {
|
||||||
if (req.auth.actor !== ActorType.USER) return;
|
if (req.auth.actor !== ActorType.USER) return;
|
||||||
|
|
||||||
const membership = await server.services.org.updateOrgMembership({
|
const membership = await server.services.org.updateOrgMembership({
|
||||||
userId: req.permission.id,
|
userId: req.permission.id,
|
||||||
role: req.body.role,
|
|
||||||
actorAuthMethod: req.permission.authMethod,
|
actorAuthMethod: req.permission.authMethod,
|
||||||
orgId: req.params.organizationId,
|
orgId: req.params.organizationId,
|
||||||
membershipId: req.params.membershipId,
|
membershipId: req.params.membershipId,
|
||||||
actorOrgId: req.permission.orgId
|
actorOrgId: req.permission.orgId,
|
||||||
|
...req.body
|
||||||
});
|
});
|
||||||
return { membership };
|
return { membership };
|
||||||
}
|
}
|
||||||
@ -183,6 +240,69 @@ export const registerOrgRouter = async (server: FastifyZodProvider) => {
|
|||||||
}
|
}
|
||||||
});
|
});
|
||||||
|
|
||||||
|
server.route({
|
||||||
|
// TODO: re-think endpoint structure in future so users only need to pass in membershipId bc organizationId is redundant
|
||||||
|
method: "GET",
|
||||||
|
url: "/:organizationId/memberships/:membershipId/project-memberships",
|
||||||
|
config: {
|
||||||
|
rateLimit: writeLimit
|
||||||
|
},
|
||||||
|
schema: {
|
||||||
|
description: "Get project memberships given organization membership",
|
||||||
|
security: [
|
||||||
|
{
|
||||||
|
bearerAuth: []
|
||||||
|
}
|
||||||
|
],
|
||||||
|
params: z.object({
|
||||||
|
organizationId: z.string().trim().describe(ORGANIZATIONS.DELETE_USER_MEMBERSHIP.organizationId),
|
||||||
|
membershipId: z.string().trim().describe(ORGANIZATIONS.DELETE_USER_MEMBERSHIP.membershipId)
|
||||||
|
}),
|
||||||
|
response: {
|
||||||
|
200: z.object({
|
||||||
|
memberships: ProjectMembershipsSchema.extend({
|
||||||
|
user: UsersSchema.pick({
|
||||||
|
email: true,
|
||||||
|
username: true,
|
||||||
|
firstName: true,
|
||||||
|
lastName: true,
|
||||||
|
id: true
|
||||||
|
}).merge(UserEncryptionKeysSchema.pick({ publicKey: true })),
|
||||||
|
project: ProjectsSchema.pick({ name: true, id: true }),
|
||||||
|
roles: z.array(
|
||||||
|
z.object({
|
||||||
|
id: z.string(),
|
||||||
|
role: z.string(),
|
||||||
|
customRoleId: z.string().optional().nullable(),
|
||||||
|
customRoleName: z.string().optional().nullable(),
|
||||||
|
customRoleSlug: z.string().optional().nullable(),
|
||||||
|
isTemporary: z.boolean(),
|
||||||
|
temporaryMode: z.string().optional().nullable(),
|
||||||
|
temporaryRange: z.string().nullable().optional(),
|
||||||
|
temporaryAccessStartTime: z.date().nullable().optional(),
|
||||||
|
temporaryAccessEndTime: z.date().nullable().optional()
|
||||||
|
})
|
||||||
|
)
|
||||||
|
})
|
||||||
|
.omit({ createdAt: true, updatedAt: true })
|
||||||
|
.array()
|
||||||
|
})
|
||||||
|
}
|
||||||
|
},
|
||||||
|
onRequest: verifyAuth([AuthMode.JWT, AuthMode.IDENTITY_ACCESS_TOKEN]),
|
||||||
|
handler: async (req) => {
|
||||||
|
const memberships = await server.services.org.listProjectMembershipsByOrgMembershipId({
|
||||||
|
actor: req.permission.type,
|
||||||
|
actorId: req.permission.id,
|
||||||
|
actorAuthMethod: req.permission.authMethod,
|
||||||
|
actorOrgId: req.permission.orgId,
|
||||||
|
orgId: req.params.organizationId,
|
||||||
|
orgMembershipId: req.params.membershipId
|
||||||
|
});
|
||||||
|
return { memberships };
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
server.route({
|
server.route({
|
||||||
method: "POST",
|
method: "POST",
|
||||||
url: "/",
|
url: "/",
|
||||||
|
@ -4,7 +4,8 @@ import bcrypt from "bcrypt";
|
|||||||
|
|
||||||
import { TAuthTokens, TAuthTokenSessions } from "@app/db/schemas";
|
import { TAuthTokens, TAuthTokenSessions } from "@app/db/schemas";
|
||||||
import { getConfig } from "@app/lib/config/env";
|
import { getConfig } from "@app/lib/config/env";
|
||||||
import { UnauthorizedError } from "@app/lib/errors";
|
import { ForbiddenRequestError, UnauthorizedError } from "@app/lib/errors";
|
||||||
|
import { TOrgMembershipDALFactory } from "@app/services/org-membership/org-membership-dal";
|
||||||
|
|
||||||
import { AuthModeJwtTokenPayload } from "../auth/auth-type";
|
import { AuthModeJwtTokenPayload } from "../auth/auth-type";
|
||||||
import { TUserDALFactory } from "../user/user-dal";
|
import { TUserDALFactory } from "../user/user-dal";
|
||||||
@ -14,6 +15,7 @@ import { TCreateTokenForUserDTO, TIssueAuthTokenDTO, TokenType, TValidateTokenFo
|
|||||||
type TAuthTokenServiceFactoryDep = {
|
type TAuthTokenServiceFactoryDep = {
|
||||||
tokenDAL: TTokenDALFactory;
|
tokenDAL: TTokenDALFactory;
|
||||||
userDAL: Pick<TUserDALFactory, "findById" | "transaction">;
|
userDAL: Pick<TUserDALFactory, "findById" | "transaction">;
|
||||||
|
orgMembershipDAL: Pick<TOrgMembershipDALFactory, "findOne">;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type TAuthTokenServiceFactory = ReturnType<typeof tokenServiceFactory>;
|
export type TAuthTokenServiceFactory = ReturnType<typeof tokenServiceFactory>;
|
||||||
@ -67,7 +69,7 @@ export const getTokenConfig = (tokenType: TokenType) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
export const tokenServiceFactory = ({ tokenDAL, userDAL }: TAuthTokenServiceFactoryDep) => {
|
export const tokenServiceFactory = ({ tokenDAL, userDAL, orgMembershipDAL }: TAuthTokenServiceFactoryDep) => {
|
||||||
const createTokenForUser = async ({ type, userId, orgId }: TCreateTokenForUserDTO) => {
|
const createTokenForUser = async ({ type, userId, orgId }: TCreateTokenForUserDTO) => {
|
||||||
const { token, ...tkCfg } = getTokenConfig(type);
|
const { token, ...tkCfg } = getTokenConfig(type);
|
||||||
const appCfg = getConfig();
|
const appCfg = getConfig();
|
||||||
@ -154,6 +156,16 @@ export const tokenServiceFactory = ({ tokenDAL, userDAL }: TAuthTokenServiceFact
|
|||||||
const user = await userDAL.findById(session.userId);
|
const user = await userDAL.findById(session.userId);
|
||||||
if (!user || !user.isAccepted) throw new UnauthorizedError({ name: "Token user not found" });
|
if (!user || !user.isAccepted) throw new UnauthorizedError({ name: "Token user not found" });
|
||||||
|
|
||||||
|
if (token.organizationId) {
|
||||||
|
const orgMembership = await orgMembershipDAL.findOne({
|
||||||
|
userId: user.id,
|
||||||
|
orgId: token.organizationId
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!orgMembership) throw new ForbiddenRequestError({ message: "User not member of organization" });
|
||||||
|
if (!orgMembership.isActive) throw new ForbiddenRequestError({ message: "User not active in organization" });
|
||||||
|
}
|
||||||
|
|
||||||
return { user, tokenVersionId: token.tokenVersionId, orgId: token.organizationId };
|
return { user, tokenVersionId: token.tokenVersionId, orgId: token.organizationId };
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -75,8 +75,10 @@ export const getCaCredentials = async ({
|
|||||||
kmsService
|
kmsService
|
||||||
});
|
});
|
||||||
|
|
||||||
const decryptedPrivateKey = await kmsService.decrypt({
|
const kmsDecryptor = await kmsService.decryptWithKmsKey({
|
||||||
kmsId: keyId,
|
kmsId: keyId
|
||||||
|
});
|
||||||
|
const decryptedPrivateKey = kmsDecryptor({
|
||||||
cipherTextBlob: caSecret.encryptedPrivateKey
|
cipherTextBlob: caSecret.encryptedPrivateKey
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -123,15 +125,17 @@ export const getCaCertChain = async ({
|
|||||||
kmsService
|
kmsService
|
||||||
});
|
});
|
||||||
|
|
||||||
const decryptedCaCert = await kmsService.decrypt({
|
const kmsDecryptor = await kmsService.decryptWithKmsKey({
|
||||||
kmsId: keyId,
|
kmsId: keyId
|
||||||
|
});
|
||||||
|
|
||||||
|
const decryptedCaCert = kmsDecryptor({
|
||||||
cipherTextBlob: caCert.encryptedCertificate
|
cipherTextBlob: caCert.encryptedCertificate
|
||||||
});
|
});
|
||||||
|
|
||||||
const caCertObj = new x509.X509Certificate(decryptedCaCert);
|
const caCertObj = new x509.X509Certificate(decryptedCaCert);
|
||||||
|
|
||||||
const decryptedChain = await kmsService.decrypt({
|
const decryptedChain = kmsDecryptor({
|
||||||
kmsId: keyId,
|
|
||||||
cipherTextBlob: caCert.encryptedCertificateChain
|
cipherTextBlob: caCert.encryptedCertificateChain
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -168,8 +172,11 @@ export const rebuildCaCrl = async ({
|
|||||||
kmsService
|
kmsService
|
||||||
});
|
});
|
||||||
|
|
||||||
const privateKey = await kmsService.decrypt({
|
const kmsDecryptor = await kmsService.decryptWithKmsKey({
|
||||||
kmsId: keyId,
|
kmsId: keyId
|
||||||
|
});
|
||||||
|
|
||||||
|
const privateKey = kmsDecryptor({
|
||||||
cipherTextBlob: caSecret.encryptedPrivateKey
|
cipherTextBlob: caSecret.encryptedPrivateKey
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -200,8 +207,10 @@ export const rebuildCaCrl = async ({
|
|||||||
signingKey: sk
|
signingKey: sk
|
||||||
});
|
});
|
||||||
|
|
||||||
const { cipherTextBlob: encryptedCrl } = await kmsService.encrypt({
|
const kmsEncryptor = await kmsService.encryptWithKmsKey({
|
||||||
kmsId: keyId,
|
kmsId: keyId
|
||||||
|
});
|
||||||
|
const { cipherTextBlob: encryptedCrl } = kmsEncryptor({
|
||||||
plainText: Buffer.from(new Uint8Array(crl.rawData))
|
plainText: Buffer.from(new Uint8Array(crl.rawData))
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -25,7 +25,7 @@ type TCertificateAuthorityQueueFactoryDep = {
|
|||||||
certificateAuthoritySecretDAL: TCertificateAuthoritySecretDALFactory;
|
certificateAuthoritySecretDAL: TCertificateAuthoritySecretDALFactory;
|
||||||
certificateDAL: TCertificateDALFactory;
|
certificateDAL: TCertificateDALFactory;
|
||||||
projectDAL: Pick<TProjectDALFactory, "findProjectBySlug" | "findOne" | "updateById" | "findById" | "transaction">;
|
projectDAL: Pick<TProjectDALFactory, "findProjectBySlug" | "findOne" | "updateById" | "findById" | "transaction">;
|
||||||
kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "encrypt" | "decrypt">;
|
kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "encryptWithKmsKey" | "decryptWithKmsKey">;
|
||||||
queueService: TQueueServiceFactory;
|
queueService: TQueueServiceFactory;
|
||||||
};
|
};
|
||||||
export type TCertificateAuthorityQueueFactory = ReturnType<typeof certificateAuthorityQueueFactory>;
|
export type TCertificateAuthorityQueueFactory = ReturnType<typeof certificateAuthorityQueueFactory>;
|
||||||
@ -88,8 +88,10 @@ export const certificateAuthorityQueueFactory = ({
|
|||||||
kmsService
|
kmsService
|
||||||
});
|
});
|
||||||
|
|
||||||
const privateKey = await kmsService.decrypt({
|
const kmsDecryptor = await kmsService.decryptWithKmsKey({
|
||||||
kmsId: keyId,
|
kmsId: keyId
|
||||||
|
});
|
||||||
|
const privateKey = kmsDecryptor({
|
||||||
cipherTextBlob: caSecret.encryptedPrivateKey
|
cipherTextBlob: caSecret.encryptedPrivateKey
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -120,8 +122,10 @@ export const certificateAuthorityQueueFactory = ({
|
|||||||
signingKey: sk
|
signingKey: sk
|
||||||
});
|
});
|
||||||
|
|
||||||
const { cipherTextBlob: encryptedCrl } = await kmsService.encrypt({
|
const kmsEncryptor = await kmsService.encryptWithKmsKey({
|
||||||
kmsId: keyId,
|
kmsId: keyId
|
||||||
|
});
|
||||||
|
const { cipherTextBlob: encryptedCrl } = kmsEncryptor({
|
||||||
plainText: Buffer.from(new Uint8Array(crl.rawData))
|
plainText: Buffer.from(new Uint8Array(crl.rawData))
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -53,7 +53,7 @@ type TCertificateAuthorityServiceFactoryDep = {
|
|||||||
certificateDAL: Pick<TCertificateDALFactory, "transaction" | "create" | "find">;
|
certificateDAL: Pick<TCertificateDALFactory, "transaction" | "create" | "find">;
|
||||||
certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;
|
certificateBodyDAL: Pick<TCertificateBodyDALFactory, "create">;
|
||||||
projectDAL: Pick<TProjectDALFactory, "findProjectBySlug" | "findOne" | "updateById" | "findById" | "transaction">;
|
projectDAL: Pick<TProjectDALFactory, "findProjectBySlug" | "findOne" | "updateById" | "findById" | "transaction">;
|
||||||
kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "encrypt" | "decrypt">;
|
kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "encryptWithKmsKey" | "decryptWithKmsKey">;
|
||||||
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
|
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -154,11 +154,14 @@ export const certificateAuthorityServiceFactory = ({
|
|||||||
tx
|
tx
|
||||||
);
|
);
|
||||||
|
|
||||||
const keyId = await getProjectKmsCertificateKeyId({
|
const certificateManagerKmsId = await getProjectKmsCertificateKeyId({
|
||||||
projectId: project.id,
|
projectId: project.id,
|
||||||
projectDAL,
|
projectDAL,
|
||||||
kmsService
|
kmsService
|
||||||
});
|
});
|
||||||
|
const kmsEncryptor = await kmsService.encryptWithKmsKey({
|
||||||
|
kmsId: certificateManagerKmsId
|
||||||
|
});
|
||||||
|
|
||||||
if (type === CaType.ROOT) {
|
if (type === CaType.ROOT) {
|
||||||
// note: create self-signed cert only applicable for root CA
|
// note: create self-signed cert only applicable for root CA
|
||||||
@ -178,13 +181,11 @@ export const certificateAuthorityServiceFactory = ({
|
|||||||
]
|
]
|
||||||
});
|
});
|
||||||
|
|
||||||
const { cipherTextBlob: encryptedCertificate } = await kmsService.encrypt({
|
const { cipherTextBlob: encryptedCertificate } = kmsEncryptor({
|
||||||
kmsId: keyId,
|
|
||||||
plainText: Buffer.from(new Uint8Array(cert.rawData))
|
plainText: Buffer.from(new Uint8Array(cert.rawData))
|
||||||
});
|
});
|
||||||
|
|
||||||
const { cipherTextBlob: encryptedCertificateChain } = await kmsService.encrypt({
|
const { cipherTextBlob: encryptedCertificateChain } = kmsEncryptor({
|
||||||
kmsId: keyId,
|
|
||||||
plainText: Buffer.alloc(0)
|
plainText: Buffer.alloc(0)
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -208,8 +209,7 @@ export const certificateAuthorityServiceFactory = ({
|
|||||||
signingKey: keys.privateKey
|
signingKey: keys.privateKey
|
||||||
});
|
});
|
||||||
|
|
||||||
const { cipherTextBlob: encryptedCrl } = await kmsService.encrypt({
|
const { cipherTextBlob: encryptedCrl } = kmsEncryptor({
|
||||||
kmsId: keyId,
|
|
||||||
plainText: Buffer.from(new Uint8Array(crl.rawData))
|
plainText: Buffer.from(new Uint8Array(crl.rawData))
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -224,8 +224,7 @@ export const certificateAuthorityServiceFactory = ({
|
|||||||
// https://nodejs.org/api/crypto.html#static-method-keyobjectfromkey
|
// https://nodejs.org/api/crypto.html#static-method-keyobjectfromkey
|
||||||
const skObj = KeyObject.from(keys.privateKey);
|
const skObj = KeyObject.from(keys.privateKey);
|
||||||
|
|
||||||
const { cipherTextBlob: encryptedPrivateKey } = await kmsService.encrypt({
|
const { cipherTextBlob: encryptedPrivateKey } = kmsEncryptor({
|
||||||
kmsId: keyId,
|
|
||||||
plainText: skObj.export({
|
plainText: skObj.export({
|
||||||
type: "pkcs8",
|
type: "pkcs8",
|
||||||
format: "der"
|
format: "der"
|
||||||
@ -449,15 +448,17 @@ export const certificateAuthorityServiceFactory = ({
|
|||||||
|
|
||||||
const alg = keyAlgorithmToAlgCfg(ca.keyAlgorithm as CertKeyAlgorithm);
|
const alg = keyAlgorithmToAlgCfg(ca.keyAlgorithm as CertKeyAlgorithm);
|
||||||
|
|
||||||
const keyId = await getProjectKmsCertificateKeyId({
|
const certificateManagerKmsId = await getProjectKmsCertificateKeyId({
|
||||||
projectId: ca.projectId,
|
projectId: ca.projectId,
|
||||||
projectDAL,
|
projectDAL,
|
||||||
kmsService
|
kmsService
|
||||||
});
|
});
|
||||||
|
const kmsDecryptor = await kmsService.decryptWithKmsKey({
|
||||||
|
kmsId: certificateManagerKmsId
|
||||||
|
});
|
||||||
|
|
||||||
const caCert = await certificateAuthorityCertDAL.findOne({ caId: ca.id });
|
const caCert = await certificateAuthorityCertDAL.findOne({ caId: ca.id });
|
||||||
const decryptedCaCert = await kmsService.decrypt({
|
const decryptedCaCert = kmsDecryptor({
|
||||||
kmsId: keyId,
|
|
||||||
cipherTextBlob: caCert.encryptedCertificate
|
cipherTextBlob: caCert.encryptedCertificate
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -605,19 +606,20 @@ export const certificateAuthorityServiceFactory = ({
|
|||||||
dn: parentCertSubject
|
dn: parentCertSubject
|
||||||
});
|
});
|
||||||
|
|
||||||
const keyId = await getProjectKmsCertificateKeyId({
|
const certificateManagerKmsId = await getProjectKmsCertificateKeyId({
|
||||||
projectId: ca.projectId,
|
projectId: ca.projectId,
|
||||||
projectDAL,
|
projectDAL,
|
||||||
kmsService
|
kmsService
|
||||||
});
|
});
|
||||||
|
const kmsEncryptor = await kmsService.encryptWithKmsKey({
|
||||||
|
kmsId: certificateManagerKmsId
|
||||||
|
});
|
||||||
|
|
||||||
const { cipherTextBlob: encryptedCertificate } = await kmsService.encrypt({
|
const { cipherTextBlob: encryptedCertificate } = kmsEncryptor({
|
||||||
kmsId: keyId,
|
|
||||||
plainText: Buffer.from(new Uint8Array(certObj.rawData))
|
plainText: Buffer.from(new Uint8Array(certObj.rawData))
|
||||||
});
|
});
|
||||||
|
|
||||||
const { cipherTextBlob: encryptedCertificateChain } = await kmsService.encrypt({
|
const { cipherTextBlob: encryptedCertificateChain } = kmsEncryptor({
|
||||||
kmsId: keyId,
|
|
||||||
plainText: Buffer.from(certificateChain)
|
plainText: Buffer.from(certificateChain)
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -682,14 +684,16 @@ export const certificateAuthorityServiceFactory = ({
|
|||||||
const caCert = await certificateAuthorityCertDAL.findOne({ caId: ca.id });
|
const caCert = await certificateAuthorityCertDAL.findOne({ caId: ca.id });
|
||||||
if (!caCert) throw new BadRequestError({ message: "CA does not have a certificate installed" });
|
if (!caCert) throw new BadRequestError({ message: "CA does not have a certificate installed" });
|
||||||
|
|
||||||
const keyId = await getProjectKmsCertificateKeyId({
|
const certificateManagerKmsId = await getProjectKmsCertificateKeyId({
|
||||||
projectId: ca.projectId,
|
projectId: ca.projectId,
|
||||||
projectDAL,
|
projectDAL,
|
||||||
kmsService
|
kmsService
|
||||||
});
|
});
|
||||||
|
const kmsDecryptor = await kmsService.decryptWithKmsKey({
|
||||||
|
kmsId: certificateManagerKmsId
|
||||||
|
});
|
||||||
|
|
||||||
const decryptedCaCert = await kmsService.decrypt({
|
const decryptedCaCert = kmsDecryptor({
|
||||||
kmsId: keyId,
|
|
||||||
cipherTextBlob: caCert.encryptedCertificate
|
cipherTextBlob: caCert.encryptedCertificate
|
||||||
});
|
});
|
||||||
|
|
||||||
@ -796,8 +800,10 @@ export const certificateAuthorityServiceFactory = ({
|
|||||||
const skLeafObj = KeyObject.from(leafKeys.privateKey);
|
const skLeafObj = KeyObject.from(leafKeys.privateKey);
|
||||||
const skLeaf = skLeafObj.export({ format: "pem", type: "pkcs8" }) as string;
|
const skLeaf = skLeafObj.export({ format: "pem", type: "pkcs8" }) as string;
|
||||||
|
|
||||||
const { cipherTextBlob: encryptedCertificate } = await kmsService.encrypt({
|
const kmsEncryptor = await kmsService.encryptWithKmsKey({
|
||||||
kmsId: keyId,
|
kmsId: certificateManagerKmsId
|
||||||
|
});
|
||||||
|
const { cipherTextBlob: encryptedCertificate } = kmsEncryptor({
|
||||||
plainText: Buffer.from(new Uint8Array(leafCert.rawData))
|
plainText: Buffer.from(new Uint8Array(leafCert.rawData))
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -95,7 +95,7 @@ export type TGetCaCredentialsDTO = {
|
|||||||
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById">;
|
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById">;
|
||||||
certificateAuthoritySecretDAL: Pick<TCertificateAuthoritySecretDALFactory, "findOne">;
|
certificateAuthoritySecretDAL: Pick<TCertificateAuthoritySecretDALFactory, "findOne">;
|
||||||
projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;
|
projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;
|
||||||
kmsService: Pick<TKmsServiceFactory, "decrypt" | "generateKmsKey">;
|
kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "generateKmsKey">;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type TGetCaCertChainDTO = {
|
export type TGetCaCertChainDTO = {
|
||||||
@ -103,7 +103,7 @@ export type TGetCaCertChainDTO = {
|
|||||||
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById">;
|
certificateAuthorityDAL: Pick<TCertificateAuthorityDALFactory, "findById">;
|
||||||
certificateAuthorityCertDAL: Pick<TCertificateAuthorityCertDALFactory, "findOne">;
|
certificateAuthorityCertDAL: Pick<TCertificateAuthorityCertDALFactory, "findOne">;
|
||||||
projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;
|
projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;
|
||||||
kmsService: Pick<TKmsServiceFactory, "decrypt" | "generateKmsKey">;
|
kmsService: Pick<TKmsServiceFactory, "decryptWithKmsKey" | "generateKmsKey">;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type TRebuildCaCrlDTO = {
|
export type TRebuildCaCrlDTO = {
|
||||||
@ -113,7 +113,7 @@ export type TRebuildCaCrlDTO = {
|
|||||||
certificateAuthoritySecretDAL: Pick<TCertificateAuthoritySecretDALFactory, "findOne">;
|
certificateAuthoritySecretDAL: Pick<TCertificateAuthoritySecretDALFactory, "findOne">;
|
||||||
projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;
|
projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "transaction">;
|
||||||
certificateDAL: Pick<TCertificateDALFactory, "find">;
|
certificateDAL: Pick<TCertificateDALFactory, "find">;
|
||||||
kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "decrypt" | "encrypt">;
|
kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "decryptWithKmsKey" | "encryptWithKmsKey">;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type TRotateCaCrlTriggerDTO = {
|
export type TRotateCaCrlTriggerDTO = {
|
||||||
|
@ -25,7 +25,7 @@ type TCertificateServiceFactoryDep = {
|
|||||||
certificateAuthorityCrlDAL: Pick<TCertificateAuthorityCrlDALFactory, "update">;
|
certificateAuthorityCrlDAL: Pick<TCertificateAuthorityCrlDALFactory, "update">;
|
||||||
certificateAuthoritySecretDAL: Pick<TCertificateAuthoritySecretDALFactory, "findOne">;
|
certificateAuthoritySecretDAL: Pick<TCertificateAuthoritySecretDALFactory, "findOne">;
|
||||||
projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "findById" | "transaction">;
|
projectDAL: Pick<TProjectDALFactory, "findOne" | "updateById" | "findById" | "transaction">;
|
||||||
kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "encrypt" | "decrypt">;
|
kmsService: Pick<TKmsServiceFactory, "generateKmsKey" | "encryptWithKmsKey" | "decryptWithKmsKey">;
|
||||||
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
|
permissionService: Pick<TPermissionServiceFactory, "getProjectPermission">;
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -164,14 +164,16 @@ export const certificateServiceFactory = ({
|
|||||||
|
|
||||||
const certBody = await certificateBodyDAL.findOne({ certId: cert.id });
|
const certBody = await certificateBodyDAL.findOne({ certId: cert.id });
|
||||||
|
|
||||||
const keyId = await getProjectKmsCertificateKeyId({
|
const certificateManagerKeyId = await getProjectKmsCertificateKeyId({
|
||||||
projectId: ca.projectId,
|
projectId: ca.projectId,
|
||||||
projectDAL,
|
projectDAL,
|
||||||
kmsService
|
kmsService
|
||||||
});
|
});
|
||||||
|
|
||||||
const decryptedCert = await kmsService.decrypt({
|
const kmsDecryptor = await kmsService.decryptWithKmsKey({
|
||||||
kmsId: keyId,
|
kmsId: certificateManagerKeyId
|
||||||
|
});
|
||||||
|
const decryptedCert = kmsDecryptor({
|
||||||
cipherTextBlob: certBody.encryptedCertificate
|
cipherTextBlob: certBody.encryptedCertificate
|
||||||
});
|
});
|
||||||
|
|
||||||
|
@ -78,7 +78,10 @@ export const identityAwsAuthServiceFactory = ({
|
|||||||
.map((accountId) => accountId.trim())
|
.map((accountId) => accountId.trim())
|
||||||
.some((accountId) => accountId === Account);
|
.some((accountId) => accountId === Account);
|
||||||
|
|
||||||
if (!isAccountAllowed) throw new UnauthorizedError();
|
if (!isAccountAllowed)
|
||||||
|
throw new ForbiddenRequestError({
|
||||||
|
message: "Access denied: AWS account ID not allowed."
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (identityAwsAuth.allowedPrincipalArns) {
|
if (identityAwsAuth.allowedPrincipalArns) {
|
||||||
@ -94,7 +97,10 @@ export const identityAwsAuthServiceFactory = ({
|
|||||||
return regex.test(extractPrincipalArn(Arn));
|
return regex.test(extractPrincipalArn(Arn));
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!isArnAllowed) throw new UnauthorizedError();
|
if (!isArnAllowed)
|
||||||
|
throw new ForbiddenRequestError({
|
||||||
|
message: "Access denied: AWS principal ARN not allowed."
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const identityAccessToken = await identityAwsAuthDAL.transaction(async (tx) => {
|
const identityAccessToken = await identityAwsAuthDAL.transaction(async (tx) => {
|
||||||
|
@ -17,6 +17,7 @@ export const validateAzureIdentity = async ({
|
|||||||
const jwksUri = `https://login.microsoftonline.com/${tenantId}/discovery/keys`;
|
const jwksUri = `https://login.microsoftonline.com/${tenantId}/discovery/keys`;
|
||||||
|
|
||||||
const decodedJwt = jwt.decode(azureJwt, { complete: true }) as TDecodedAzureAuthJwt;
|
const decodedJwt = jwt.decode(azureJwt, { complete: true }) as TDecodedAzureAuthJwt;
|
||||||
|
|
||||||
const { kid } = decodedJwt.header;
|
const { kid } = decodedJwt.header;
|
||||||
|
|
||||||
const { data }: { data: TAzureJwksUriResponse } = await axios.get(jwksUri);
|
const { data }: { data: TAzureJwksUriResponse } = await axios.get(jwksUri);
|
||||||
@ -27,6 +28,13 @@ export const validateAzureIdentity = async ({
|
|||||||
|
|
||||||
const publicKey = `-----BEGIN CERTIFICATE-----\n${signingKey.x5c[0]}\n-----END CERTIFICATE-----`;
|
const publicKey = `-----BEGIN CERTIFICATE-----\n${signingKey.x5c[0]}\n-----END CERTIFICATE-----`;
|
||||||
|
|
||||||
|
// Case: This can happen when the user uses a custom resource (such as https://management.azure.com&client_id=value).
|
||||||
|
// In this case, the audience in the decoded JWT will not have a trailing slash, but the resource will.
|
||||||
|
if (!decodedJwt.payload.aud.endsWith("/") && resource.endsWith("/")) {
|
||||||
|
// eslint-disable-next-line no-param-reassign
|
||||||
|
resource = resource.slice(0, -1);
|
||||||
|
}
|
||||||
|
|
||||||
return jwt.verify(azureJwt, publicKey, {
|
return jwt.verify(azureJwt, publicKey, {
|
||||||
audience: resource,
|
audience: resource,
|
||||||
issuer: `https://sts.windows.net/${tenantId}/`
|
issuer: `https://sts.windows.net/${tenantId}/`
|
||||||
|
@ -81,7 +81,10 @@ export const identityGcpAuthServiceFactory = ({
|
|||||||
.map((serviceAccount) => serviceAccount.trim())
|
.map((serviceAccount) => serviceAccount.trim())
|
||||||
.some((serviceAccount) => serviceAccount === gcpIdentityDetails.email);
|
.some((serviceAccount) => serviceAccount === gcpIdentityDetails.email);
|
||||||
|
|
||||||
if (!isServiceAccountAllowed) throw new UnauthorizedError();
|
if (!isServiceAccountAllowed)
|
||||||
|
throw new ForbiddenRequestError({
|
||||||
|
message: "Access denied: GCP service account not allowed."
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (identityGcpAuth.type === "gce" && identityGcpAuth.allowedProjects && gcpIdentityDetails.computeEngineDetails) {
|
if (identityGcpAuth.type === "gce" && identityGcpAuth.allowedProjects && gcpIdentityDetails.computeEngineDetails) {
|
||||||
@ -92,7 +95,10 @@ export const identityGcpAuthServiceFactory = ({
|
|||||||
.map((project) => project.trim())
|
.map((project) => project.trim())
|
||||||
.some((project) => project === gcpIdentityDetails.computeEngineDetails?.project_id);
|
.some((project) => project === gcpIdentityDetails.computeEngineDetails?.project_id);
|
||||||
|
|
||||||
if (!isProjectAllowed) throw new UnauthorizedError();
|
if (!isProjectAllowed)
|
||||||
|
throw new ForbiddenRequestError({
|
||||||
|
message: "Access denied: GCP project not allowed."
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (identityGcpAuth.type === "gce" && identityGcpAuth.allowedZones && gcpIdentityDetails.computeEngineDetails) {
|
if (identityGcpAuth.type === "gce" && identityGcpAuth.allowedZones && gcpIdentityDetails.computeEngineDetails) {
|
||||||
@ -101,7 +107,10 @@ export const identityGcpAuthServiceFactory = ({
|
|||||||
.map((zone) => zone.trim())
|
.map((zone) => zone.trim())
|
||||||
.some((zone) => zone === gcpIdentityDetails.computeEngineDetails?.zone);
|
.some((zone) => zone === gcpIdentityDetails.computeEngineDetails?.zone);
|
||||||
|
|
||||||
if (!isZoneAllowed) throw new UnauthorizedError();
|
if (!isZoneAllowed)
|
||||||
|
throw new ForbiddenRequestError({
|
||||||
|
message: "Access denied: GCP zone not allowed."
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const identityAccessToken = await identityGcpAuthDAL.transaction(async (tx) => {
|
const identityAccessToken = await identityGcpAuthDAL.transaction(async (tx) => {
|
||||||
|
@ -139,7 +139,10 @@ export const identityKubernetesAuthServiceFactory = ({
|
|||||||
.map((namespace) => namespace.trim())
|
.map((namespace) => namespace.trim())
|
||||||
.some((namespace) => namespace === targetNamespace);
|
.some((namespace) => namespace === targetNamespace);
|
||||||
|
|
||||||
if (!isNamespaceAllowed) throw new UnauthorizedError();
|
if (!isNamespaceAllowed)
|
||||||
|
throw new ForbiddenRequestError({
|
||||||
|
message: "Access denied: K8s namespace not allowed."
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (identityKubernetesAuth.allowedNames) {
|
if (identityKubernetesAuth.allowedNames) {
|
||||||
@ -150,7 +153,10 @@ export const identityKubernetesAuthServiceFactory = ({
|
|||||||
.map((name) => name.trim())
|
.map((name) => name.trim())
|
||||||
.some((name) => name === targetName);
|
.some((name) => name === targetName);
|
||||||
|
|
||||||
if (!isNameAllowed) throw new UnauthorizedError();
|
if (!isNameAllowed)
|
||||||
|
throw new ForbiddenRequestError({
|
||||||
|
message: "Access denied: K8s name not allowed."
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
if (identityKubernetesAuth.allowedAudience) {
|
if (identityKubernetesAuth.allowedAudience) {
|
||||||
@ -159,7 +165,10 @@ export const identityKubernetesAuthServiceFactory = ({
|
|||||||
(audience) => audience === identityKubernetesAuth.allowedAudience
|
(audience) => audience === identityKubernetesAuth.allowedAudience
|
||||||
);
|
);
|
||||||
|
|
||||||
if (!isAudienceAllowed) throw new UnauthorizedError();
|
if (!isAudienceAllowed)
|
||||||
|
throw new ForbiddenRequestError({
|
||||||
|
message: "Access denied: K8s audience not allowed."
|
||||||
|
});
|
||||||
}
|
}
|
||||||
|
|
||||||
const identityAccessToken = await identityKubernetesAuthDAL.transaction(async (tx) => {
|
const identityAccessToken = await identityKubernetesAuthDAL.transaction(async (tx) => {
|
||||||
|
@ -124,13 +124,17 @@ export const identityOidcAuthServiceFactory = ({
|
|||||||
|
|
||||||
if (identityOidcAuth.boundSubject) {
|
if (identityOidcAuth.boundSubject) {
|
||||||
if (tokenData.sub !== identityOidcAuth.boundSubject) {
|
if (tokenData.sub !== identityOidcAuth.boundSubject) {
|
||||||
throw new UnauthorizedError();
|
throw new ForbiddenRequestError({
|
||||||
|
message: "Access denied: OIDC subject not allowed."
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
if (identityOidcAuth.boundAudiences) {
|
if (identityOidcAuth.boundAudiences) {
|
||||||
if (!identityOidcAuth.boundAudiences.split(", ").includes(tokenData.aud)) {
|
if (!identityOidcAuth.boundAudiences.split(", ").includes(tokenData.aud)) {
|
||||||
throw new UnauthorizedError();
|
throw new ForbiddenRequestError({
|
||||||
|
message: "Access denied: OIDC audience not allowed."
|
||||||
|
});
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -139,7 +143,9 @@ export const identityOidcAuthServiceFactory = ({
|
|||||||
const claimValue = (identityOidcAuth.boundClaims as Record<string, string>)[claimKey];
|
const claimValue = (identityOidcAuth.boundClaims as Record<string, string>)[claimKey];
|
||||||
// handle both single and multi-valued claims
|
// handle both single and multi-valued claims
|
||||||
if (!claimValue.split(", ").some((claimEntry) => tokenData[claimKey] === claimEntry)) {
|
if (!claimValue.split(", ").some((claimEntry) => tokenData[claimKey] === claimEntry)) {
|
||||||
throw new UnauthorizedError();
|
throw new ForbiddenRequestError({
|
||||||
|
message: "Access denied: OIDC claim not allowed."
|
||||||
|
});
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
}
|
}
|
||||||
|
@ -574,14 +574,14 @@ export const integrationAuthServiceFactory = ({
|
|||||||
const botKey = await projectBotService.getBotKey(integrationAuth.projectId);
|
const botKey = await projectBotService.getBotKey(integrationAuth.projectId);
|
||||||
const { accessId, accessToken } = await getIntegrationAccessToken(integrationAuth, botKey);
|
const { accessId, accessToken } = await getIntegrationAccessToken(integrationAuth, botKey);
|
||||||
|
|
||||||
AWS.config.update({
|
const kms = new AWS.KMS({
|
||||||
region,
|
region,
|
||||||
credentials: {
|
credentials: {
|
||||||
accessKeyId: String(accessId),
|
accessKeyId: String(accessId),
|
||||||
secretAccessKey: accessToken
|
secretAccessKey: accessToken
|
||||||
}
|
}
|
||||||
});
|
});
|
||||||
const kms = new AWS.KMS();
|
|
||||||
const aliases = await kms.listAliases({}).promise();
|
const aliases = await kms.listAliases({}).promise();
|
||||||
|
|
||||||
const keyAliases = aliases.Aliases!.filter((alias) => {
|
const keyAliases = aliases.Aliases!.filter((alias) => {
|
||||||
|
10
backend/src/services/kms/internal-kms-dal.ts
Normal file
10
backend/src/services/kms/internal-kms-dal.ts
Normal file
@ -0,0 +1,10 @@
|
|||||||
|
import { TDbClient } from "@app/db";
|
||||||
|
import { TableName } from "@app/db/schemas";
|
||||||
|
import { ormify } from "@app/lib/knex";
|
||||||
|
|
||||||
|
export type TInternalKmsDALFactory = ReturnType<typeof internalKmsDALFactory>;
|
||||||
|
|
||||||
|
export const internalKmsDALFactory = (db: TDbClient) => {
|
||||||
|
const internalKmsOrm = ormify(db, TableName.InternalKms);
|
||||||
|
return internalKmsOrm;
|
||||||
|
};
|
@ -1,10 +0,0 @@
|
|||||||
import { TDbClient } from "@app/db";
|
|
||||||
import { TableName } from "@app/db/schemas";
|
|
||||||
import { ormify } from "@app/lib/knex";
|
|
||||||
|
|
||||||
export type TKmsDALFactory = ReturnType<typeof kmsDALFactory>;
|
|
||||||
|
|
||||||
export const kmsDALFactory = (db: TDbClient) => {
|
|
||||||
const kmsOrm = ormify(db, TableName.KmsKey);
|
|
||||||
return kmsOrm;
|
|
||||||
};
|
|
64
backend/src/services/kms/kms-key-dal.ts
Normal file
64
backend/src/services/kms/kms-key-dal.ts
Normal file
@ -0,0 +1,64 @@
|
|||||||
|
import { Knex } from "knex";
|
||||||
|
|
||||||
|
import { TDbClient } from "@app/db";
|
||||||
|
import { KmsKeysSchema, TableName } from "@app/db/schemas";
|
||||||
|
import { DatabaseError } from "@app/lib/errors";
|
||||||
|
import { ormify, selectAllTableCols } from "@app/lib/knex";
|
||||||
|
|
||||||
|
export type TKmsKeyDALFactory = ReturnType<typeof kmskeyDALFactory>;
|
||||||
|
|
||||||
|
export const kmskeyDALFactory = (db: TDbClient) => {
|
||||||
|
const kmsOrm = ormify(db, TableName.KmsKey);
|
||||||
|
|
||||||
|
const findByIdWithAssociatedKms = async (id: string, tx?: Knex) => {
|
||||||
|
try {
|
||||||
|
const result = await (tx || db.replicaNode())(TableName.KmsKey)
|
||||||
|
.where({ [`${TableName.KmsKey}.id` as "id"]: id })
|
||||||
|
.leftJoin(TableName.InternalKms, `${TableName.KmsKey}.id`, `${TableName.InternalKms}.kmsKeyId`)
|
||||||
|
.leftJoin(TableName.ExternalKms, `${TableName.KmsKey}.id`, `${TableName.ExternalKms}.kmsKeyId`)
|
||||||
|
.first()
|
||||||
|
.select(selectAllTableCols(TableName.KmsKey))
|
||||||
|
.select(
|
||||||
|
db.ref("id").withSchema(TableName.InternalKms).as("internalKmsId"),
|
||||||
|
db.ref("encryptedKey").withSchema(TableName.InternalKms).as("internalKmsEncryptedKey"),
|
||||||
|
db.ref("encryptionAlgorithm").withSchema(TableName.InternalKms).as("internalKmsEncryptionAlgorithm"),
|
||||||
|
db.ref("version").withSchema(TableName.InternalKms).as("internalKmsVersion"),
|
||||||
|
db.ref("id").withSchema(TableName.InternalKms).as("internalKmsId")
|
||||||
|
)
|
||||||
|
.select(
|
||||||
|
db.ref("id").withSchema(TableName.ExternalKms).as("externalKmsId"),
|
||||||
|
db.ref("provider").withSchema(TableName.ExternalKms).as("externalKmsProvider"),
|
||||||
|
db.ref("encryptedProviderInputs").withSchema(TableName.ExternalKms).as("externalKmsEncryptedProviderInput"),
|
||||||
|
db.ref("status").withSchema(TableName.ExternalKms).as("externalKmsStatus"),
|
||||||
|
db.ref("statusDetails").withSchema(TableName.ExternalKms).as("externalKmsStatusDetails")
|
||||||
|
);
|
||||||
|
|
||||||
|
const data = {
|
||||||
|
...KmsKeysSchema.parse(result),
|
||||||
|
isExternal: Boolean(result?.externalKmsId),
|
||||||
|
externalKms: result?.externalKmsId
|
||||||
|
? {
|
||||||
|
id: result.externalKmsId,
|
||||||
|
provider: result.externalKmsProvider,
|
||||||
|
encryptedProviderInput: result.externalKmsEncryptedProviderInput,
|
||||||
|
status: result.externalKmsStatus,
|
||||||
|
statusDetails: result.externalKmsStatusDetails
|
||||||
|
}
|
||||||
|
: undefined,
|
||||||
|
internalKms: result?.internalKmsId
|
||||||
|
? {
|
||||||
|
id: result.internalKmsId,
|
||||||
|
encryptedKey: result.internalKmsEncryptedKey,
|
||||||
|
encryptionAlgorithm: result.internalKmsEncryptionAlgorithm,
|
||||||
|
version: result.internalKmsVersion
|
||||||
|
}
|
||||||
|
: undefined
|
||||||
|
};
|
||||||
|
return data;
|
||||||
|
} catch (error) {
|
||||||
|
throw new DatabaseError({ error, name: "Find by id" });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return { ...kmsOrm, findByIdWithAssociatedKms };
|
||||||
|
};
|
@ -1,18 +1,34 @@
|
|||||||
|
import slugify from "@sindresorhus/slugify";
|
||||||
|
import { Knex } from "knex";
|
||||||
|
|
||||||
import { TKeyStoreFactory } from "@app/keystore/keystore";
|
import { TKeyStoreFactory } from "@app/keystore/keystore";
|
||||||
import { getConfig } from "@app/lib/config/env";
|
import { getConfig } from "@app/lib/config/env";
|
||||||
import { randomSecureBytes } from "@app/lib/crypto";
|
import { randomSecureBytes } from "@app/lib/crypto";
|
||||||
import { symmetricCipherService, SymmetricEncryption } from "@app/lib/crypto/cipher";
|
import { symmetricCipherService, SymmetricEncryption } from "@app/lib/crypto/cipher";
|
||||||
import { BadRequestError } from "@app/lib/errors";
|
import { BadRequestError } from "@app/lib/errors";
|
||||||
import { logger } from "@app/lib/logger";
|
import { logger } from "@app/lib/logger";
|
||||||
|
import { alphaNumericNanoId } from "@app/lib/nanoid";
|
||||||
|
|
||||||
import { TKmsDALFactory } from "./kms-dal";
|
import { TOrgDALFactory } from "../org/org-dal";
|
||||||
|
import { TProjectDALFactory } from "../project/project-dal";
|
||||||
|
import { TInternalKmsDALFactory } from "./internal-kms-dal";
|
||||||
|
import { TKmsKeyDALFactory } from "./kms-key-dal";
|
||||||
import { TKmsRootConfigDALFactory } from "./kms-root-config-dal";
|
import { TKmsRootConfigDALFactory } from "./kms-root-config-dal";
|
||||||
import { TDecryptWithKmsDTO, TEncryptWithKmsDTO, TGenerateKMSDTO } from "./kms-types";
|
import {
|
||||||
|
TDecryptWithKeyDTO,
|
||||||
|
TDecryptWithKmsDTO,
|
||||||
|
TEncryptionWithKeyDTO,
|
||||||
|
TEncryptWithKmsDTO,
|
||||||
|
TGenerateKMSDTO
|
||||||
|
} from "./kms-types";
|
||||||
|
|
||||||
type TKmsServiceFactoryDep = {
|
type TKmsServiceFactoryDep = {
|
||||||
kmsDAL: TKmsDALFactory;
|
kmsDAL: TKmsKeyDALFactory;
|
||||||
|
projectDAL: Pick<TProjectDALFactory, "findById" | "updateById" | "transaction">;
|
||||||
|
orgDAL: Pick<TOrgDALFactory, "findById" | "updateById" | "transaction">;
|
||||||
kmsRootConfigDAL: Pick<TKmsRootConfigDALFactory, "findById" | "create">;
|
kmsRootConfigDAL: Pick<TKmsRootConfigDALFactory, "findById" | "create">;
|
||||||
keyStore: Pick<TKeyStoreFactory, "acquireLock" | "waitTillReady" | "setItemWithExpiry">;
|
keyStore: Pick<TKeyStoreFactory, "acquireLock" | "waitTillReady" | "setItemWithExpiry">;
|
||||||
|
internalKmsDAL: Pick<TInternalKmsDALFactory, "create">;
|
||||||
};
|
};
|
||||||
|
|
||||||
export type TKmsServiceFactory = ReturnType<typeof kmsServiceFactory>;
|
export type TKmsServiceFactory = ReturnType<typeof kmsServiceFactory>;
|
||||||
@ -25,36 +41,55 @@ const KMS_ROOT_CREATION_WAIT_TIME = 10;
|
|||||||
// akhilmhdh: Don't edit this value. This is measured for blob concatination in kms
|
// akhilmhdh: Don't edit this value. This is measured for blob concatination in kms
|
||||||
const KMS_VERSION = "v01";
|
const KMS_VERSION = "v01";
|
||||||
const KMS_VERSION_BLOB_LENGTH = 3;
|
const KMS_VERSION_BLOB_LENGTH = 3;
|
||||||
export const kmsServiceFactory = ({ kmsDAL, kmsRootConfigDAL, keyStore }: TKmsServiceFactoryDep) => {
|
export const kmsServiceFactory = ({
|
||||||
|
kmsDAL,
|
||||||
|
kmsRootConfigDAL,
|
||||||
|
keyStore,
|
||||||
|
internalKmsDAL,
|
||||||
|
orgDAL,
|
||||||
|
projectDAL
|
||||||
|
}: TKmsServiceFactoryDep) => {
|
||||||
let ROOT_ENCRYPTION_KEY = Buffer.alloc(0);
|
let ROOT_ENCRYPTION_KEY = Buffer.alloc(0);
|
||||||
|
|
||||||
// this is used symmetric encryption
|
// this is used symmetric encryption
|
||||||
const generateKmsKey = async ({ scopeId, scopeType, isReserved = true, tx }: TGenerateKMSDTO) => {
|
const generateKmsKey = async ({ orgId, isReserved = true, tx, slug }: TGenerateKMSDTO) => {
|
||||||
const cipher = symmetricCipherService(SymmetricEncryption.AES_GCM_256);
|
const cipher = symmetricCipherService(SymmetricEncryption.AES_GCM_256);
|
||||||
const kmsKeyMaterial = randomSecureBytes(32);
|
const kmsKeyMaterial = randomSecureBytes(32);
|
||||||
const encryptedKeyMaterial = cipher.encrypt(kmsKeyMaterial, ROOT_ENCRYPTION_KEY);
|
const encryptedKeyMaterial = cipher.encrypt(kmsKeyMaterial, ROOT_ENCRYPTION_KEY);
|
||||||
|
const sanitizedSlug = slug ? slugify(slug) : slugify(alphaNumericNanoId(8).toLowerCase());
|
||||||
|
const dbQuery = async (db: Knex) => {
|
||||||
|
const kmsDoc = await kmsDAL.create(
|
||||||
|
{
|
||||||
|
slug: sanitizedSlug,
|
||||||
|
orgId,
|
||||||
|
isReserved
|
||||||
|
},
|
||||||
|
db
|
||||||
|
);
|
||||||
|
|
||||||
const { encryptedKey, ...doc } = await kmsDAL.create(
|
await internalKmsDAL.create(
|
||||||
{
|
{
|
||||||
version: 1,
|
version: 1,
|
||||||
encryptedKey: encryptedKeyMaterial,
|
encryptedKey: encryptedKeyMaterial,
|
||||||
encryptionAlgorithm: SymmetricEncryption.AES_GCM_256,
|
encryptionAlgorithm: SymmetricEncryption.AES_GCM_256,
|
||||||
isReserved,
|
kmsKeyId: kmsDoc.id
|
||||||
orgId: scopeType === "org" ? scopeId : undefined,
|
|
||||||
projectId: scopeType === "project" ? scopeId : undefined
|
|
||||||
},
|
},
|
||||||
tx
|
db
|
||||||
);
|
);
|
||||||
|
return kmsDoc;
|
||||||
|
};
|
||||||
|
if (tx) return dbQuery(tx);
|
||||||
|
const doc = await kmsDAL.transaction(async (tx2) => dbQuery(tx2));
|
||||||
return doc;
|
return doc;
|
||||||
};
|
};
|
||||||
|
|
||||||
const encrypt = async ({ kmsId, plainText }: TEncryptWithKmsDTO) => {
|
const encryptWithKmsKey = async ({ kmsId }: Omit<TEncryptWithKmsDTO, "plainText">) => {
|
||||||
const kmsDoc = await kmsDAL.findById(kmsId);
|
const kmsDoc = await kmsDAL.findByIdWithAssociatedKms(kmsId);
|
||||||
if (!kmsDoc) throw new BadRequestError({ message: "KMS ID not found" });
|
if (!kmsDoc) throw new BadRequestError({ message: "KMS ID not found" });
|
||||||
// akhilmhdh: as more encryption are added do a check here on kmsDoc.encryptionAlgorithm
|
// akhilmhdh: as more encryption are added do a check here on kmsDoc.encryptionAlgorithm
|
||||||
const cipher = symmetricCipherService(SymmetricEncryption.AES_GCM_256);
|
const cipher = symmetricCipherService(SymmetricEncryption.AES_GCM_256);
|
||||||
|
return ({ plainText }: Pick<TEncryptWithKmsDTO, "plainText">) => {
|
||||||
const kmsKey = cipher.decrypt(kmsDoc.encryptedKey, ROOT_ENCRYPTION_KEY);
|
const kmsKey = cipher.decrypt(kmsDoc.internalKms?.encryptedKey as Buffer, ROOT_ENCRYPTION_KEY);
|
||||||
const encryptedPlainTextBlob = cipher.encrypt(plainText, kmsKey);
|
const encryptedPlainTextBlob = cipher.encrypt(plainText, kmsKey);
|
||||||
|
|
||||||
// Buffer#1 encrypted text + Buffer#2 version number
|
// Buffer#1 encrypted text + Buffer#2 version number
|
||||||
@ -62,18 +97,106 @@ export const kmsServiceFactory = ({ kmsDAL, kmsRootConfigDAL, keyStore }: TKmsSe
|
|||||||
const cipherTextBlob = Buffer.concat([encryptedPlainTextBlob, versionBlob]);
|
const cipherTextBlob = Buffer.concat([encryptedPlainTextBlob, versionBlob]);
|
||||||
return { cipherTextBlob };
|
return { cipherTextBlob };
|
||||||
};
|
};
|
||||||
|
};
|
||||||
|
|
||||||
const decrypt = async ({ cipherTextBlob: versionedCipherTextBlob, kmsId }: TDecryptWithKmsDTO) => {
|
const encryptWithInputKey = async ({ key }: Omit<TEncryptionWithKeyDTO, "plainText">) => {
|
||||||
const kmsDoc = await kmsDAL.findById(kmsId);
|
|
||||||
if (!kmsDoc) throw new BadRequestError({ message: "KMS ID not found" });
|
|
||||||
// akhilmhdh: as more encryption are added do a check here on kmsDoc.encryptionAlgorithm
|
// akhilmhdh: as more encryption are added do a check here on kmsDoc.encryptionAlgorithm
|
||||||
const cipher = symmetricCipherService(SymmetricEncryption.AES_GCM_256);
|
const cipher = symmetricCipherService(SymmetricEncryption.AES_GCM_256);
|
||||||
const kmsKey = cipher.decrypt(kmsDoc.encryptedKey, ROOT_ENCRYPTION_KEY);
|
return ({ plainText }: Pick<TEncryptWithKmsDTO, "plainText">) => {
|
||||||
|
const encryptedPlainTextBlob = cipher.encrypt(plainText, key);
|
||||||
|
// Buffer#1 encrypted text + Buffer#2 version number
|
||||||
|
const versionBlob = Buffer.from(KMS_VERSION, "utf8"); // length is 3
|
||||||
|
const cipherTextBlob = Buffer.concat([encryptedPlainTextBlob, versionBlob]);
|
||||||
|
return { cipherTextBlob };
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const decryptWithKmsKey = async ({ kmsId }: Omit<TDecryptWithKmsDTO, "cipherTextBlob">) => {
|
||||||
|
const kmsDoc = await kmsDAL.findByIdWithAssociatedKms(kmsId);
|
||||||
|
if (!kmsDoc) throw new BadRequestError({ message: "KMS ID not found" });
|
||||||
|
const cipher = symmetricCipherService(SymmetricEncryption.AES_GCM_256);
|
||||||
|
const kmsKey = cipher.decrypt(kmsDoc.internalKms?.encryptedKey as Buffer, ROOT_ENCRYPTION_KEY);
|
||||||
|
|
||||||
|
return ({ cipherTextBlob: versionedCipherTextBlob }: Pick<TDecryptWithKmsDTO, "cipherTextBlob">) => {
|
||||||
const cipherTextBlob = versionedCipherTextBlob.subarray(0, -KMS_VERSION_BLOB_LENGTH);
|
const cipherTextBlob = versionedCipherTextBlob.subarray(0, -KMS_VERSION_BLOB_LENGTH);
|
||||||
const decryptedBlob = cipher.decrypt(cipherTextBlob, kmsKey);
|
const decryptedBlob = cipher.decrypt(cipherTextBlob, kmsKey);
|
||||||
return decryptedBlob;
|
return decryptedBlob;
|
||||||
};
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const decryptWithInputKey = async ({ key }: Omit<TDecryptWithKeyDTO, "cipherTextBlob">) => {
|
||||||
|
const cipher = symmetricCipherService(SymmetricEncryption.AES_GCM_256);
|
||||||
|
|
||||||
|
return ({ cipherTextBlob: versionedCipherTextBlob }: Pick<TDecryptWithKeyDTO, "cipherTextBlob">) => {
|
||||||
|
const cipherTextBlob = versionedCipherTextBlob.subarray(0, -KMS_VERSION_BLOB_LENGTH);
|
||||||
|
const decryptedBlob = cipher.decrypt(cipherTextBlob, key);
|
||||||
|
return decryptedBlob;
|
||||||
|
};
|
||||||
|
};
|
||||||
|
|
||||||
|
const getOrgKmsKeyId = async (orgId: string) => {
|
||||||
|
const keyId = await orgDAL.transaction(async (tx) => {
|
||||||
|
const org = await orgDAL.findById(orgId, tx);
|
||||||
|
if (!org) {
|
||||||
|
throw new BadRequestError({ message: "Org not found" });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!org.kmsDefaultKeyId) {
|
||||||
|
// create default kms key for certificate service
|
||||||
|
const key = await generateKmsKey({
|
||||||
|
isReserved: true,
|
||||||
|
orgId: org.id,
|
||||||
|
tx
|
||||||
|
});
|
||||||
|
|
||||||
|
await orgDAL.updateById(
|
||||||
|
org.id,
|
||||||
|
{
|
||||||
|
kmsDefaultKeyId: key.id
|
||||||
|
},
|
||||||
|
tx
|
||||||
|
);
|
||||||
|
|
||||||
|
return key.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
return org.kmsDefaultKeyId;
|
||||||
|
});
|
||||||
|
|
||||||
|
return keyId;
|
||||||
|
};
|
||||||
|
|
||||||
|
const getProjectSecretManagerKmsKeyId = async (projectId: string) => {
|
||||||
|
const keyId = await projectDAL.transaction(async (tx) => {
|
||||||
|
const project = await projectDAL.findById(projectId, tx);
|
||||||
|
if (!project) {
|
||||||
|
throw new BadRequestError({ message: "Project not found" });
|
||||||
|
}
|
||||||
|
|
||||||
|
if (!project.kmsSecretManagerKeyId) {
|
||||||
|
// create default kms key for certificate service
|
||||||
|
const key = await generateKmsKey({
|
||||||
|
isReserved: true,
|
||||||
|
orgId: project.orgId,
|
||||||
|
tx
|
||||||
|
});
|
||||||
|
|
||||||
|
await projectDAL.updateById(
|
||||||
|
projectId,
|
||||||
|
{
|
||||||
|
kmsSecretManagerKeyId: key.id
|
||||||
|
},
|
||||||
|
tx
|
||||||
|
);
|
||||||
|
|
||||||
|
return key.id;
|
||||||
|
}
|
||||||
|
|
||||||
|
return project.kmsSecretManagerKeyId;
|
||||||
|
});
|
||||||
|
|
||||||
|
return keyId;
|
||||||
|
};
|
||||||
|
|
||||||
const startService = async () => {
|
const startService = async () => {
|
||||||
const appCfg = getConfig();
|
const appCfg = getConfig();
|
||||||
@ -123,7 +246,11 @@ export const kmsServiceFactory = ({ kmsDAL, kmsRootConfigDAL, keyStore }: TKmsSe
|
|||||||
return {
|
return {
|
||||||
startService,
|
startService,
|
||||||
generateKmsKey,
|
generateKmsKey,
|
||||||
encrypt,
|
encryptWithKmsKey,
|
||||||
decrypt
|
encryptWithInputKey,
|
||||||
|
decryptWithKmsKey,
|
||||||
|
decryptWithInputKey,
|
||||||
|
getOrgKmsKeyId,
|
||||||
|
getProjectSecretManagerKmsKeyId
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
@ -1,9 +1,9 @@
|
|||||||
import { Knex } from "knex";
|
import { Knex } from "knex";
|
||||||
|
|
||||||
export type TGenerateKMSDTO = {
|
export type TGenerateKMSDTO = {
|
||||||
scopeType: "project" | "org";
|
orgId: string;
|
||||||
scopeId: string;
|
|
||||||
isReserved?: boolean;
|
isReserved?: boolean;
|
||||||
|
slug?: string;
|
||||||
tx?: Knex;
|
tx?: Knex;
|
||||||
};
|
};
|
||||||
|
|
||||||
@ -12,7 +12,17 @@ export type TEncryptWithKmsDTO = {
|
|||||||
plainText: Buffer;
|
plainText: Buffer;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type TEncryptionWithKeyDTO = {
|
||||||
|
key: Buffer;
|
||||||
|
plainText: Buffer;
|
||||||
|
};
|
||||||
|
|
||||||
export type TDecryptWithKmsDTO = {
|
export type TDecryptWithKmsDTO = {
|
||||||
kmsId: string;
|
kmsId: string;
|
||||||
cipherTextBlob: Buffer;
|
cipherTextBlob: Buffer;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type TDecryptWithKeyDTO = {
|
||||||
|
key: Buffer;
|
||||||
|
cipherTextBlob: Buffer;
|
||||||
|
};
|
||||||
|
@ -1,5 +1,6 @@
|
|||||||
import { TDbClient } from "@app/db";
|
import { TDbClient } from "@app/db";
|
||||||
import { TableName } from "@app/db/schemas";
|
import { TableName, TUserEncryptionKeys } from "@app/db/schemas";
|
||||||
|
import { DatabaseError } from "@app/lib/errors";
|
||||||
import { ormify } from "@app/lib/knex";
|
import { ormify } from "@app/lib/knex";
|
||||||
|
|
||||||
export type TOrgMembershipDALFactory = ReturnType<typeof orgMembershipDALFactory>;
|
export type TOrgMembershipDALFactory = ReturnType<typeof orgMembershipDALFactory>;
|
||||||
@ -7,7 +8,51 @@ export type TOrgMembershipDALFactory = ReturnType<typeof orgMembershipDALFactory
|
|||||||
export const orgMembershipDALFactory = (db: TDbClient) => {
|
export const orgMembershipDALFactory = (db: TDbClient) => {
|
||||||
const orgMembershipOrm = ormify(db, TableName.OrgMembership);
|
const orgMembershipOrm = ormify(db, TableName.OrgMembership);
|
||||||
|
|
||||||
|
const findOrgMembershipById = async (membershipId: string) => {
|
||||||
|
try {
|
||||||
|
const member = await db
|
||||||
|
.replicaNode()(TableName.OrgMembership)
|
||||||
|
.where(`${TableName.OrgMembership}.id`, membershipId)
|
||||||
|
.join(TableName.Users, `${TableName.OrgMembership}.userId`, `${TableName.Users}.id`)
|
||||||
|
.leftJoin<TUserEncryptionKeys>(
|
||||||
|
TableName.UserEncryptionKey,
|
||||||
|
`${TableName.UserEncryptionKey}.userId`,
|
||||||
|
`${TableName.Users}.id`
|
||||||
|
)
|
||||||
|
.select(
|
||||||
|
db.ref("id").withSchema(TableName.OrgMembership),
|
||||||
|
db.ref("inviteEmail").withSchema(TableName.OrgMembership),
|
||||||
|
db.ref("orgId").withSchema(TableName.OrgMembership),
|
||||||
|
db.ref("role").withSchema(TableName.OrgMembership),
|
||||||
|
db.ref("roleId").withSchema(TableName.OrgMembership),
|
||||||
|
db.ref("status").withSchema(TableName.OrgMembership),
|
||||||
|
db.ref("isActive").withSchema(TableName.OrgMembership),
|
||||||
|
db.ref("email").withSchema(TableName.Users),
|
||||||
|
db.ref("username").withSchema(TableName.Users),
|
||||||
|
db.ref("firstName").withSchema(TableName.Users),
|
||||||
|
db.ref("lastName").withSchema(TableName.Users),
|
||||||
|
db.ref("isEmailVerified").withSchema(TableName.Users),
|
||||||
|
db.ref("id").withSchema(TableName.Users).as("userId"),
|
||||||
|
db.ref("publicKey").withSchema(TableName.UserEncryptionKey)
|
||||||
|
)
|
||||||
|
.where({ isGhost: false }) // MAKE SURE USER IS NOT A GHOST USER
|
||||||
|
.first();
|
||||||
|
|
||||||
|
if (!member) return undefined;
|
||||||
|
|
||||||
|
const { email, isEmailVerified, username, firstName, lastName, userId, publicKey, ...data } = member;
|
||||||
|
|
||||||
return {
|
return {
|
||||||
...orgMembershipOrm
|
...data,
|
||||||
|
user: { email, isEmailVerified, username, firstName, lastName, id: userId, publicKey }
|
||||||
|
};
|
||||||
|
} catch (error) {
|
||||||
|
throw new DatabaseError({ error, name: "Find org membership by id" });
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
return {
|
||||||
|
...orgMembershipOrm,
|
||||||
|
findOrgMembershipById
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
@ -74,7 +74,9 @@ export const orgDALFactory = (db: TDbClient) => {
|
|||||||
db.ref("role").withSchema(TableName.OrgMembership),
|
db.ref("role").withSchema(TableName.OrgMembership),
|
||||||
db.ref("roleId").withSchema(TableName.OrgMembership),
|
db.ref("roleId").withSchema(TableName.OrgMembership),
|
||||||
db.ref("status").withSchema(TableName.OrgMembership),
|
db.ref("status").withSchema(TableName.OrgMembership),
|
||||||
|
db.ref("isActive").withSchema(TableName.OrgMembership),
|
||||||
db.ref("email").withSchema(TableName.Users),
|
db.ref("email").withSchema(TableName.Users),
|
||||||
|
db.ref("isEmailVerified").withSchema(TableName.Users),
|
||||||
db.ref("username").withSchema(TableName.Users),
|
db.ref("username").withSchema(TableName.Users),
|
||||||
db.ref("firstName").withSchema(TableName.Users),
|
db.ref("firstName").withSchema(TableName.Users),
|
||||||
db.ref("lastName").withSchema(TableName.Users),
|
db.ref("lastName").withSchema(TableName.Users),
|
||||||
@ -83,9 +85,9 @@ export const orgDALFactory = (db: TDbClient) => {
|
|||||||
)
|
)
|
||||||
.where({ isGhost: false }); // MAKE SURE USER IS NOT A GHOST USER
|
.where({ isGhost: false }); // MAKE SURE USER IS NOT A GHOST USER
|
||||||
|
|
||||||
return members.map(({ email, username, firstName, lastName, userId, publicKey, ...data }) => ({
|
return members.map(({ email, isEmailVerified, username, firstName, lastName, userId, publicKey, ...data }) => ({
|
||||||
...data,
|
...data,
|
||||||
user: { email, username, firstName, lastName, id: userId, publicKey }
|
user: { email, isEmailVerified, username, firstName, lastName, id: userId, publicKey }
|
||||||
}));
|
}));
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new DatabaseError({ error, name: "Find all org members" });
|
throw new DatabaseError({ error, name: "Find all org members" });
|
||||||
@ -207,9 +209,9 @@ export const orgDALFactory = (db: TDbClient) => {
|
|||||||
}
|
}
|
||||||
};
|
};
|
||||||
|
|
||||||
const updateById = async (orgId: string, data: Partial<TOrganizations>) => {
|
const updateById = async (orgId: string, data: Partial<TOrganizations>, tx?: Knex) => {
|
||||||
try {
|
try {
|
||||||
const [org] = await db(TableName.Organization)
|
const [org] = await (tx || db)(TableName.Organization)
|
||||||
.where({ id: orgId })
|
.where({ id: orgId })
|
||||||
.update({ ...data })
|
.update({ ...data })
|
||||||
.returning("*");
|
.returning("*");
|
||||||
|
@ -42,6 +42,61 @@ export const orgRoleServiceFactory = ({ orgRoleDAL, permissionService }: TOrgRol
|
|||||||
return role;
|
return role;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const getRole = async (
|
||||||
|
userId: string,
|
||||||
|
orgId: string,
|
||||||
|
roleId: string,
|
||||||
|
actorAuthMethod: ActorAuthMethod,
|
||||||
|
actorOrgId: string | undefined
|
||||||
|
) => {
|
||||||
|
const { permission } = await permissionService.getUserOrgPermission(userId, orgId, actorAuthMethod, actorOrgId);
|
||||||
|
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.Role);
|
||||||
|
|
||||||
|
switch (roleId) {
|
||||||
|
case "b11b49a9-09a9-4443-916a-4246f9ff2c69": {
|
||||||
|
return {
|
||||||
|
id: roleId,
|
||||||
|
orgId,
|
||||||
|
name: "Admin",
|
||||||
|
slug: "admin",
|
||||||
|
description: "Complete administration access over the organization",
|
||||||
|
permissions: packRules(orgAdminPermissions.rules),
|
||||||
|
createdAt: new Date(),
|
||||||
|
updatedAt: new Date()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
case "b11b49a9-09a9-4443-916a-4246f9ff2c70": {
|
||||||
|
return {
|
||||||
|
id: roleId,
|
||||||
|
orgId,
|
||||||
|
name: "Member",
|
||||||
|
slug: "member",
|
||||||
|
description: "Non-administrative role in an organization",
|
||||||
|
permissions: packRules(orgMemberPermissions.rules),
|
||||||
|
createdAt: new Date(),
|
||||||
|
updatedAt: new Date()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
case "b10d49a9-09a9-4443-916a-4246f9ff2c72": {
|
||||||
|
return {
|
||||||
|
id: "b10d49a9-09a9-4443-916a-4246f9ff2c72", // dummy user for zod validation in response
|
||||||
|
orgId,
|
||||||
|
name: "No Access",
|
||||||
|
slug: "no-access",
|
||||||
|
description: "No access to any resources in the organization",
|
||||||
|
permissions: packRules(orgNoAccessPermissions.rules),
|
||||||
|
createdAt: new Date(),
|
||||||
|
updatedAt: new Date()
|
||||||
|
};
|
||||||
|
}
|
||||||
|
default: {
|
||||||
|
const role = await orgRoleDAL.findOne({ id: roleId, orgId });
|
||||||
|
if (!role) throw new BadRequestError({ message: "Role not found", name: "Get role" });
|
||||||
|
return role;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
const updateRole = async (
|
const updateRole = async (
|
||||||
userId: string,
|
userId: string,
|
||||||
orgId: string,
|
orgId: string,
|
||||||
@ -144,5 +199,5 @@ export const orgRoleServiceFactory = ({ orgRoleDAL, permissionService }: TOrgRol
|
|||||||
return { permissions: packRules(permission.rules), membership };
|
return { permissions: packRules(permission.rules), membership };
|
||||||
};
|
};
|
||||||
|
|
||||||
return { createRole, updateRole, deleteRole, listRoles, getUserPermission };
|
return { createRole, getRole, updateRole, deleteRole, listRoles, getUserPermission };
|
||||||
};
|
};
|
||||||
|
@ -15,9 +15,10 @@ import { getConfig } from "@app/lib/config/env";
|
|||||||
import { generateAsymmetricKeyPair } from "@app/lib/crypto";
|
import { generateAsymmetricKeyPair } from "@app/lib/crypto";
|
||||||
import { generateSymmetricKey, infisicalSymmetricEncypt } from "@app/lib/crypto/encryption";
|
import { generateSymmetricKey, infisicalSymmetricEncypt } from "@app/lib/crypto/encryption";
|
||||||
import { generateUserSrpKeys } from "@app/lib/crypto/srp";
|
import { generateUserSrpKeys } from "@app/lib/crypto/srp";
|
||||||
import { BadRequestError, UnauthorizedError } from "@app/lib/errors";
|
import { BadRequestError, NotFoundError, UnauthorizedError } from "@app/lib/errors";
|
||||||
import { alphaNumericNanoId } from "@app/lib/nanoid";
|
import { alphaNumericNanoId } from "@app/lib/nanoid";
|
||||||
import { isDisposableEmail } from "@app/lib/validator";
|
import { isDisposableEmail } from "@app/lib/validator";
|
||||||
|
import { TOrgMembershipDALFactory } from "@app/services/org-membership/org-membership-dal";
|
||||||
import { TUserAliasDALFactory } from "@app/services/user-alias/user-alias-dal";
|
import { TUserAliasDALFactory } from "@app/services/user-alias/user-alias-dal";
|
||||||
|
|
||||||
import { ActorAuthMethod, ActorType, AuthMethod, AuthTokenType } from "../auth/auth-type";
|
import { ActorAuthMethod, ActorType, AuthMethod, AuthTokenType } from "../auth/auth-type";
|
||||||
@ -38,7 +39,9 @@ import {
|
|||||||
TFindAllWorkspacesDTO,
|
TFindAllWorkspacesDTO,
|
||||||
TFindOrgMembersByEmailDTO,
|
TFindOrgMembersByEmailDTO,
|
||||||
TGetOrgGroupsDTO,
|
TGetOrgGroupsDTO,
|
||||||
|
TGetOrgMembershipDTO,
|
||||||
TInviteUserToOrgDTO,
|
TInviteUserToOrgDTO,
|
||||||
|
TListProjectMembershipsByOrgMembershipIdDTO,
|
||||||
TUpdateOrgDTO,
|
TUpdateOrgDTO,
|
||||||
TUpdateOrgMembershipDTO,
|
TUpdateOrgMembershipDTO,
|
||||||
TVerifyUserToOrgDTO
|
TVerifyUserToOrgDTO
|
||||||
@ -54,6 +57,7 @@ type TOrgServiceFactoryDep = {
|
|||||||
projectDAL: TProjectDALFactory;
|
projectDAL: TProjectDALFactory;
|
||||||
projectMembershipDAL: Pick<TProjectMembershipDALFactory, "findProjectMembershipsByUserId" | "delete">;
|
projectMembershipDAL: Pick<TProjectMembershipDALFactory, "findProjectMembershipsByUserId" | "delete">;
|
||||||
projectKeyDAL: Pick<TProjectKeyDALFactory, "find" | "delete">;
|
projectKeyDAL: Pick<TProjectKeyDALFactory, "find" | "delete">;
|
||||||
|
orgMembershipDAL: Pick<TOrgMembershipDALFactory, "findOrgMembershipById" | "findOne">;
|
||||||
incidentContactDAL: TIncidentContactsDALFactory;
|
incidentContactDAL: TIncidentContactsDALFactory;
|
||||||
samlConfigDAL: Pick<TSamlConfigDALFactory, "findOne" | "findEnforceableSamlCfg">;
|
samlConfigDAL: Pick<TSamlConfigDALFactory, "findOne" | "findEnforceableSamlCfg">;
|
||||||
smtpService: TSmtpService;
|
smtpService: TSmtpService;
|
||||||
@ -79,6 +83,7 @@ export const orgServiceFactory = ({
|
|||||||
projectDAL,
|
projectDAL,
|
||||||
projectMembershipDAL,
|
projectMembershipDAL,
|
||||||
projectKeyDAL,
|
projectKeyDAL,
|
||||||
|
orgMembershipDAL,
|
||||||
tokenService,
|
tokenService,
|
||||||
orgBotDAL,
|
orgBotDAL,
|
||||||
licenseService,
|
licenseService,
|
||||||
@ -144,10 +149,7 @@ export const orgServiceFactory = ({
|
|||||||
return members;
|
return members;
|
||||||
};
|
};
|
||||||
|
|
||||||
const findAllWorkspaces = async ({ actor, actorId, actorOrgId, actorAuthMethod, orgId }: TFindAllWorkspacesDTO) => {
|
const findAllWorkspaces = async ({ actor, actorId, orgId }: TFindAllWorkspacesDTO) => {
|
||||||
const { permission } = await permissionService.getOrgPermission(actor, actorId, orgId, actorAuthMethod, actorOrgId);
|
|
||||||
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.Workspace);
|
|
||||||
|
|
||||||
const organizationWorkspaceIds = new Set((await projectDAL.find({ orgId })).map((workspace) => workspace.id));
|
const organizationWorkspaceIds = new Set((await projectDAL.find({ orgId })).map((workspace) => workspace.id));
|
||||||
|
|
||||||
let workspaces: (TProjects & { organization: string } & {
|
let workspaces: (TProjects & { organization: string } & {
|
||||||
@ -207,7 +209,8 @@ export const orgServiceFactory = ({
|
|||||||
orgId,
|
orgId,
|
||||||
userId: user.id,
|
userId: user.id,
|
||||||
role: OrgMembershipRole.Admin,
|
role: OrgMembershipRole.Admin,
|
||||||
status: OrgMembershipStatus.Accepted
|
status: OrgMembershipStatus.Accepted,
|
||||||
|
isActive: true
|
||||||
};
|
};
|
||||||
|
|
||||||
await orgDAL.createMembership(createMembershipData, tx);
|
await orgDAL.createMembership(createMembershipData, tx);
|
||||||
@ -311,7 +314,8 @@ export const orgServiceFactory = ({
|
|||||||
userId,
|
userId,
|
||||||
orgId: org.id,
|
orgId: org.id,
|
||||||
role: OrgMembershipRole.Admin,
|
role: OrgMembershipRole.Admin,
|
||||||
status: OrgMembershipStatus.Accepted
|
status: OrgMembershipStatus.Accepted,
|
||||||
|
isActive: true
|
||||||
},
|
},
|
||||||
tx
|
tx
|
||||||
);
|
);
|
||||||
@ -365,6 +369,7 @@ export const orgServiceFactory = ({
|
|||||||
* */
|
* */
|
||||||
const updateOrgMembership = async ({
|
const updateOrgMembership = async ({
|
||||||
role,
|
role,
|
||||||
|
isActive,
|
||||||
orgId,
|
orgId,
|
||||||
userId,
|
userId,
|
||||||
membershipId,
|
membershipId,
|
||||||
@ -374,8 +379,16 @@ export const orgServiceFactory = ({
|
|||||||
const { permission } = await permissionService.getUserOrgPermission(userId, orgId, actorAuthMethod, actorOrgId);
|
const { permission } = await permissionService.getUserOrgPermission(userId, orgId, actorAuthMethod, actorOrgId);
|
||||||
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.Member);
|
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Edit, OrgPermissionSubjects.Member);
|
||||||
|
|
||||||
|
const foundMembership = await orgMembershipDAL.findOne({
|
||||||
|
id: membershipId,
|
||||||
|
orgId
|
||||||
|
});
|
||||||
|
if (!foundMembership) throw new NotFoundError({ message: "Failed to find organization membership" });
|
||||||
|
if (foundMembership.userId === userId)
|
||||||
|
throw new BadRequestError({ message: "Cannot update own organization membership" });
|
||||||
|
|
||||||
const isCustomRole = !Object.values(OrgMembershipRole).includes(role as OrgMembershipRole);
|
const isCustomRole = !Object.values(OrgMembershipRole).includes(role as OrgMembershipRole);
|
||||||
if (isCustomRole) {
|
if (role && isCustomRole) {
|
||||||
const customRole = await orgRoleDAL.findOne({ slug: role, orgId });
|
const customRole = await orgRoleDAL.findOne({ slug: role, orgId });
|
||||||
if (!customRole) throw new BadRequestError({ name: "Update membership", message: "Role not found" });
|
if (!customRole) throw new BadRequestError({ name: "Update membership", message: "Role not found" });
|
||||||
|
|
||||||
@ -395,7 +408,7 @@ export const orgServiceFactory = ({
|
|||||||
return membership;
|
return membership;
|
||||||
}
|
}
|
||||||
|
|
||||||
const [membership] = await orgDAL.updateMembership({ id: membershipId, orgId }, { role, roleId: null });
|
const [membership] = await orgDAL.updateMembership({ id: membershipId, orgId }, { role, roleId: null, isActive });
|
||||||
return membership;
|
return membership;
|
||||||
};
|
};
|
||||||
/*
|
/*
|
||||||
@ -460,7 +473,8 @@ export const orgServiceFactory = ({
|
|||||||
inviteEmail: inviteeEmail,
|
inviteEmail: inviteeEmail,
|
||||||
orgId,
|
orgId,
|
||||||
role: OrgMembershipRole.Member,
|
role: OrgMembershipRole.Member,
|
||||||
status: OrgMembershipStatus.Invited
|
status: OrgMembershipStatus.Invited,
|
||||||
|
isActive: true
|
||||||
},
|
},
|
||||||
tx
|
tx
|
||||||
);
|
);
|
||||||
@ -491,7 +505,8 @@ export const orgServiceFactory = ({
|
|||||||
orgId,
|
orgId,
|
||||||
userId: user.id,
|
userId: user.id,
|
||||||
role: OrgMembershipRole.Member,
|
role: OrgMembershipRole.Member,
|
||||||
status: OrgMembershipStatus.Invited
|
status: OrgMembershipStatus.Invited,
|
||||||
|
isActive: true
|
||||||
},
|
},
|
||||||
tx
|
tx
|
||||||
);
|
);
|
||||||
@ -584,6 +599,24 @@ export const orgServiceFactory = ({
|
|||||||
return { token, user };
|
return { token, user };
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const getOrgMembership = async ({
|
||||||
|
membershipId,
|
||||||
|
orgId,
|
||||||
|
actor,
|
||||||
|
actorId,
|
||||||
|
actorAuthMethod,
|
||||||
|
actorOrgId
|
||||||
|
}: TGetOrgMembershipDTO) => {
|
||||||
|
const { permission } = await permissionService.getOrgPermission(actor, actorId, orgId, actorAuthMethod, actorOrgId);
|
||||||
|
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.Member);
|
||||||
|
|
||||||
|
const membership = await orgMembershipDAL.findOrgMembershipById(membershipId);
|
||||||
|
if (!membership) throw new NotFoundError({ message: "Failed to find organization membership" });
|
||||||
|
if (membership.orgId !== orgId) throw new NotFoundError({ message: "Failed to find organization membership" });
|
||||||
|
|
||||||
|
return membership;
|
||||||
|
};
|
||||||
|
|
||||||
const deleteOrgMembership = async ({
|
const deleteOrgMembership = async ({
|
||||||
orgId,
|
orgId,
|
||||||
userId,
|
userId,
|
||||||
@ -607,6 +640,26 @@ export const orgServiceFactory = ({
|
|||||||
return deletedMembership;
|
return deletedMembership;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const listProjectMembershipsByOrgMembershipId = async ({
|
||||||
|
orgMembershipId,
|
||||||
|
orgId,
|
||||||
|
actor,
|
||||||
|
actorId,
|
||||||
|
actorAuthMethod,
|
||||||
|
actorOrgId
|
||||||
|
}: TListProjectMembershipsByOrgMembershipIdDTO) => {
|
||||||
|
const { permission } = await permissionService.getOrgPermission(actor, actorId, orgId, actorAuthMethod, actorOrgId);
|
||||||
|
ForbiddenError.from(permission).throwUnlessCan(OrgPermissionActions.Read, OrgPermissionSubjects.Member);
|
||||||
|
|
||||||
|
const membership = await orgMembershipDAL.findOrgMembershipById(orgMembershipId);
|
||||||
|
if (!membership) throw new NotFoundError({ message: "Failed to find organization membership" });
|
||||||
|
if (membership.orgId !== orgId) throw new NotFoundError({ message: "Failed to find organization membership" });
|
||||||
|
|
||||||
|
const projectMemberships = await projectMembershipDAL.findProjectMembershipsByUserId(orgId, membership.user.id);
|
||||||
|
|
||||||
|
return projectMemberships;
|
||||||
|
};
|
||||||
|
|
||||||
/*
|
/*
|
||||||
* CRUD operations of incident contacts
|
* CRUD operations of incident contacts
|
||||||
* */
|
* */
|
||||||
@ -667,6 +720,7 @@ export const orgServiceFactory = ({
|
|||||||
findOrgMembersByUsername,
|
findOrgMembersByUsername,
|
||||||
createOrganization,
|
createOrganization,
|
||||||
deleteOrganizationById,
|
deleteOrganizationById,
|
||||||
|
getOrgMembership,
|
||||||
deleteOrgMembership,
|
deleteOrgMembership,
|
||||||
findAllWorkspaces,
|
findAllWorkspaces,
|
||||||
addGhostUser,
|
addGhostUser,
|
||||||
@ -675,6 +729,7 @@ export const orgServiceFactory = ({
|
|||||||
findIncidentContacts,
|
findIncidentContacts,
|
||||||
createIncidentContact,
|
createIncidentContact,
|
||||||
deleteIncidentContact,
|
deleteIncidentContact,
|
||||||
getOrgGroups
|
getOrgGroups,
|
||||||
|
listProjectMembershipsByOrgMembershipId
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
@ -6,11 +6,16 @@ export type TUpdateOrgMembershipDTO = {
|
|||||||
userId: string;
|
userId: string;
|
||||||
orgId: string;
|
orgId: string;
|
||||||
membershipId: string;
|
membershipId: string;
|
||||||
role: string;
|
role?: string;
|
||||||
|
isActive?: boolean;
|
||||||
actorOrgId: string | undefined;
|
actorOrgId: string | undefined;
|
||||||
actorAuthMethod: ActorAuthMethod;
|
actorAuthMethod: ActorAuthMethod;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
export type TGetOrgMembershipDTO = {
|
||||||
|
membershipId: string;
|
||||||
|
} & TOrgPermission;
|
||||||
|
|
||||||
export type TDeleteOrgMembershipDTO = {
|
export type TDeleteOrgMembershipDTO = {
|
||||||
userId: string;
|
userId: string;
|
||||||
orgId: string;
|
orgId: string;
|
||||||
@ -55,3 +60,7 @@ export type TUpdateOrgDTO = {
|
|||||||
} & TOrgPermission;
|
} & TOrgPermission;
|
||||||
|
|
||||||
export type TGetOrgGroupsDTO = TOrgPermission;
|
export type TGetOrgGroupsDTO = TOrgPermission;
|
||||||
|
|
||||||
|
export type TListProjectMembershipsByOrgMembershipIdDTO = {
|
||||||
|
orgMembershipId: string;
|
||||||
|
} & TOrgPermission;
|
||||||
|
@ -24,10 +24,10 @@ export const getBotKeyFnFactory = (
|
|||||||
|
|
||||||
const bot = await projectBotDAL.findOne({ projectId: project.id });
|
const bot = await projectBotDAL.findOne({ projectId: project.id });
|
||||||
|
|
||||||
if (!bot) throw new BadRequestError({ message: "Failed to find bot key" });
|
if (!bot) throw new BadRequestError({ message: "Failed to find bot key", name: "bot_not_found_error" });
|
||||||
if (!bot.isActive) throw new BadRequestError({ message: "Bot is not active" });
|
if (!bot.isActive) throw new BadRequestError({ message: "Bot is not active", name: "bot_not_found_error" });
|
||||||
if (!bot.encryptedProjectKeyNonce || !bot.encryptedProjectKey)
|
if (!bot.encryptedProjectKeyNonce || !bot.encryptedProjectKey)
|
||||||
throw new BadRequestError({ message: "Encryption key missing" });
|
throw new BadRequestError({ message: "Encryption key missing", name: "bot_not_found_error" });
|
||||||
|
|
||||||
const botPrivateKey = getBotPrivateKey({ bot });
|
const botPrivateKey = getBotPrivateKey({ bot });
|
||||||
|
|
||||||
|
@ -24,10 +24,15 @@ export const projectEnvDALFactory = (db: TDbClient) => {
|
|||||||
// we are using postion based sorting as its a small list
|
// we are using postion based sorting as its a small list
|
||||||
// this will return the last value of the position in a folder with secret imports
|
// this will return the last value of the position in a folder with secret imports
|
||||||
const findLastEnvPosition = async (projectId: string, tx?: Knex) => {
|
const findLastEnvPosition = async (projectId: string, tx?: Knex) => {
|
||||||
|
// acquire update lock on project environments.
|
||||||
|
// this ensures that concurrent invocations will wait and execute sequentially
|
||||||
|
await (tx || db)(TableName.Environment).where({ projectId }).forUpdate();
|
||||||
|
|
||||||
const lastPos = await (tx || db)(TableName.Environment)
|
const lastPos = await (tx || db)(TableName.Environment)
|
||||||
.where({ projectId })
|
.where({ projectId })
|
||||||
.max("position", { as: "position" })
|
.max("position", { as: "position" })
|
||||||
.first();
|
.first();
|
||||||
|
|
||||||
return lastPos?.position || 0;
|
return lastPos?.position || 0;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
@ -3,12 +3,12 @@ import { ForbiddenError } from "@casl/ability";
|
|||||||
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
|
import { TLicenseServiceFactory } from "@app/ee/services/license/license-service";
|
||||||
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service";
|
import { TPermissionServiceFactory } from "@app/ee/services/permission/permission-service";
|
||||||
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
|
import { ProjectPermissionActions, ProjectPermissionSub } from "@app/ee/services/permission/project-permission";
|
||||||
import { BadRequestError } from "@app/lib/errors";
|
import { BadRequestError, NotFoundError } from "@app/lib/errors";
|
||||||
|
|
||||||
import { TProjectDALFactory } from "../project/project-dal";
|
import { TProjectDALFactory } from "../project/project-dal";
|
||||||
import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";
|
import { TSecretFolderDALFactory } from "../secret-folder/secret-folder-dal";
|
||||||
import { TProjectEnvDALFactory } from "./project-env-dal";
|
import { TProjectEnvDALFactory } from "./project-env-dal";
|
||||||
import { TCreateEnvDTO, TDeleteEnvDTO, TUpdateEnvDTO } from "./project-env-types";
|
import { TCreateEnvDTO, TDeleteEnvDTO, TGetEnvDTO, TUpdateEnvDTO } from "./project-env-types";
|
||||||
|
|
||||||
type TProjectEnvServiceFactoryDep = {
|
type TProjectEnvServiceFactoryDep = {
|
||||||
projectEnvDAL: TProjectEnvDALFactory;
|
projectEnvDAL: TProjectEnvDALFactory;
|
||||||
@ -139,9 +139,35 @@ export const projectEnvServiceFactory = ({
|
|||||||
return env;
|
return env;
|
||||||
};
|
};
|
||||||
|
|
||||||
|
const getEnvironmentById = async ({ projectId, actor, actorId, actorOrgId, actorAuthMethod, id }: TGetEnvDTO) => {
|
||||||
|
const { permission } = await permissionService.getProjectPermission(
|
||||||
|
actor,
|
||||||
|
actorId,
|
||||||
|
projectId,
|
||||||
|
actorAuthMethod,
|
||||||
|
actorOrgId
|
||||||
|
);
|
||||||
|
|
||||||
|
ForbiddenError.from(permission).throwUnlessCan(ProjectPermissionActions.Read, ProjectPermissionSub.Environments);
|
||||||
|
|
||||||
|
const [env] = await projectEnvDAL.find({
|
||||||
|
id,
|
||||||
|
projectId
|
||||||
|
});
|
||||||
|
|
||||||
|
if (!env) {
|
||||||
|
throw new NotFoundError({
|
||||||
|
message: "Environment does not exist"
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
return env;
|
||||||
|
};
|
||||||
|
|
||||||
return {
|
return {
|
||||||
createEnvironment,
|
createEnvironment,
|
||||||
updateEnvironment,
|
updateEnvironment,
|
||||||
deleteEnvironment
|
deleteEnvironment,
|
||||||
|
getEnvironmentById
|
||||||
};
|
};
|
||||||
};
|
};
|
||||||
|
@ -20,3 +20,7 @@ export type TReorderEnvDTO = {
|
|||||||
id: string;
|
id: string;
|
||||||
pos: number;
|
pos: number;
|
||||||
} & TProjectPermission;
|
} & TProjectPermission;
|
||||||
|
|
||||||
|
export type TGetEnvDTO = {
|
||||||
|
id: string;
|
||||||
|
} & TProjectPermission;
|
||||||
|
@ -16,6 +16,7 @@ export const projectMembershipDALFactory = (db: TDbClient) => {
|
|||||||
const docs = await db
|
const docs = await db
|
||||||
.replicaNode()(TableName.ProjectMembership)
|
.replicaNode()(TableName.ProjectMembership)
|
||||||
.where({ [`${TableName.ProjectMembership}.projectId` as "projectId"]: projectId })
|
.where({ [`${TableName.ProjectMembership}.projectId` as "projectId"]: projectId })
|
||||||
|
.join(TableName.Project, `${TableName.ProjectMembership}.projectId`, `${TableName.Project}.id`)
|
||||||
.join(TableName.Users, `${TableName.ProjectMembership}.userId`, `${TableName.Users}.id`)
|
.join(TableName.Users, `${TableName.ProjectMembership}.userId`, `${TableName.Users}.id`)
|
||||||
.where((qb) => {
|
.where((qb) => {
|
||||||
if (filter.usernames) {
|
if (filter.usernames) {
|
||||||
@ -58,17 +59,22 @@ export const projectMembershipDALFactory = (db: TDbClient) => {
|
|||||||
db.ref("isTemporary").withSchema(TableName.ProjectUserMembershipRole),
|
db.ref("isTemporary").withSchema(TableName.ProjectUserMembershipRole),
|
||||||
db.ref("temporaryRange").withSchema(TableName.ProjectUserMembershipRole),
|
db.ref("temporaryRange").withSchema(TableName.ProjectUserMembershipRole),
|
||||||
db.ref("temporaryAccessStartTime").withSchema(TableName.ProjectUserMembershipRole),
|
db.ref("temporaryAccessStartTime").withSchema(TableName.ProjectUserMembershipRole),
|
||||||
db.ref("temporaryAccessEndTime").withSchema(TableName.ProjectUserMembershipRole)
|
db.ref("temporaryAccessEndTime").withSchema(TableName.ProjectUserMembershipRole),
|
||||||
|
db.ref("name").as("projectName").withSchema(TableName.Project)
|
||||||
)
|
)
|
||||||
.where({ isGhost: false });
|
.where({ isGhost: false });
|
||||||
|
|
||||||
const members = sqlNestRelationships({
|
const members = sqlNestRelationships({
|
||||||
data: docs,
|
data: docs,
|
||||||
parentMapper: ({ email, firstName, username, lastName, publicKey, isGhost, id, userId }) => ({
|
parentMapper: ({ email, firstName, username, lastName, publicKey, isGhost, id, userId, projectName }) => ({
|
||||||
id,
|
id,
|
||||||
userId,
|
userId,
|
||||||
projectId,
|
projectId,
|
||||||
user: { email, username, firstName, lastName, id: userId, publicKey, isGhost }
|
user: { email, username, firstName, lastName, id: userId, publicKey, isGhost },
|
||||||
|
project: {
|
||||||
|
id: projectId,
|
||||||
|
name: projectName
|
||||||
|
}
|
||||||
}),
|
}),
|
||||||
key: "id",
|
key: "id",
|
||||||
childrenMapper: [
|
childrenMapper: [
|
||||||
@ -151,14 +157,95 @@ export const projectMembershipDALFactory = (db: TDbClient) => {
|
|||||||
|
|
||||||
const findProjectMembershipsByUserId = async (orgId: string, userId: string) => {
|
const findProjectMembershipsByUserId = async (orgId: string, userId: string) => {
|
||||||
try {
|
try {
|
||||||
const memberships = await db
|
const docs = await db
|
||||||
.replicaNode()(TableName.ProjectMembership)
|
.replicaNode()(TableName.ProjectMembership)
|
||||||
.where({ userId })
|
|
||||||
.join(TableName.Project, `${TableName.ProjectMembership}.projectId`, `${TableName.Project}.id`)
|
.join(TableName.Project, `${TableName.ProjectMembership}.projectId`, `${TableName.Project}.id`)
|
||||||
.where({ [`${TableName.Project}.orgId` as "orgId"]: orgId })
|
.join(TableName.Users, `${TableName.ProjectMembership}.userId`, `${TableName.Users}.id`)
|
||||||
.select(selectAllTableCols(TableName.ProjectMembership));
|
.where(`${TableName.Users}.id`, userId)
|
||||||
|
.where(`${TableName.Project}.orgId`, orgId)
|
||||||
|
.join<TUserEncryptionKeys>(
|
||||||
|
TableName.UserEncryptionKey,
|
||||||
|
`${TableName.UserEncryptionKey}.userId`,
|
||||||
|
`${TableName.Users}.id`
|
||||||
|
)
|
||||||
|
.join(
|
||||||
|
TableName.ProjectUserMembershipRole,
|
||||||
|
`${TableName.ProjectUserMembershipRole}.projectMembershipId`,
|
||||||
|
`${TableName.ProjectMembership}.id`
|
||||||
|
)
|
||||||
|
.leftJoin(
|
||||||
|
TableName.ProjectRoles,
|
||||||
|
`${TableName.ProjectUserMembershipRole}.customRoleId`,
|
||||||
|
`${TableName.ProjectRoles}.id`
|
||||||
|
)
|
||||||
|
.select(
|
||||||
|
db.ref("id").withSchema(TableName.ProjectMembership),
|
||||||
|
db.ref("isGhost").withSchema(TableName.Users),
|
||||||
|
db.ref("username").withSchema(TableName.Users),
|
||||||
|
db.ref("email").withSchema(TableName.Users),
|
||||||
|
db.ref("publicKey").withSchema(TableName.UserEncryptionKey),
|
||||||
|
db.ref("firstName").withSchema(TableName.Users),
|
||||||
|
db.ref("lastName").withSchema(TableName.Users),
|
||||||
|
db.ref("id").withSchema(TableName.Users).as("userId"),
|
||||||
|
db.ref("role").withSchema(TableName.ProjectUserMembershipRole),
|
||||||
|
db.ref("id").withSchema(TableName.ProjectUserMembershipRole).as("membershipRoleId"),
|
||||||
|
db.ref("customRoleId").withSchema(TableName.ProjectUserMembershipRole),
|
||||||
|
db.ref("name").withSchema(TableName.ProjectRoles).as("customRoleName"),
|
||||||
|
db.ref("slug").withSchema(TableName.ProjectRoles).as("customRoleSlug"),
|
||||||
|
db.ref("temporaryMode").withSchema(TableName.ProjectUserMembershipRole),
|
||||||
|
db.ref("isTemporary").withSchema(TableName.ProjectUserMembershipRole),
|
||||||
|
db.ref("temporaryRange").withSchema(TableName.ProjectUserMembershipRole),
|
||||||
|
db.ref("temporaryAccessStartTime").withSchema(TableName.ProjectUserMembershipRole),
|
||||||
|
db.ref("temporaryAccessEndTime").withSchema(TableName.ProjectUserMembershipRole),
|
||||||
|
db.ref("name").as("projectName").withSchema(TableName.Project),
|
||||||
|
db.ref("id").as("projectId").withSchema(TableName.Project)
|
||||||
|
)
|
||||||
|
.where({ isGhost: false });
|
||||||
|
|
||||||
return memberships;
|
const members = sqlNestRelationships({
|
||||||
|
data: docs,
|
||||||
|
parentMapper: ({ email, firstName, username, lastName, publicKey, isGhost, id, projectId, projectName }) => ({
|
||||||
|
id,
|
||||||
|
userId,
|
||||||
|
projectId,
|
||||||
|
user: { email, username, firstName, lastName, id: userId, publicKey, isGhost },
|
||||||
|
project: {
|
||||||
|
id: projectId,
|
||||||
|
name: projectName
|
||||||
|
}
|
||||||
|
}),
|
||||||
|
key: "id",
|
||||||
|
childrenMapper: [
|
||||||
|
{
|
||||||
|
label: "roles" as const,
|
||||||
|
key: "membershipRoleId",
|
||||||
|
mapper: ({
|
||||||
|
role,
|
||||||
|
customRoleId,
|
||||||
|
customRoleName,
|
||||||
|
customRoleSlug,
|
||||||
|
membershipRoleId,
|
||||||
|
temporaryRange,
|
||||||
|
temporaryMode,
|
||||||
|
temporaryAccessEndTime,
|
||||||
|
temporaryAccessStartTime,
|
||||||
|
isTemporary
|
||||||
|
}) => ({
|
||||||
|
id: membershipRoleId,
|
||||||
|
role,
|
||||||
|
customRoleId,
|
||||||
|
customRoleName,
|
||||||
|
customRoleSlug,
|
||||||
|
temporaryRange,
|
||||||
|
temporaryMode,
|
||||||
|
temporaryAccessEndTime,
|
||||||
|
temporaryAccessStartTime,
|
||||||
|
isTemporary
|
||||||
|
})
|
||||||
|
}
|
||||||
|
]
|
||||||
|
});
|
||||||
|
return members;
|
||||||
} catch (error) {
|
} catch (error) {
|
||||||
throw new DatabaseError({ error, name: "Find project memberships by user id" });
|
throw new DatabaseError({ error, name: "Find project memberships by user id" });
|
||||||
}
|
}
|
||||||
|
@ -71,9 +71,8 @@ export const getProjectKmsCertificateKeyId = async ({
|
|||||||
if (!project.kmsCertificateKeyId) {
|
if (!project.kmsCertificateKeyId) {
|
||||||
// create default kms key for certificate service
|
// create default kms key for certificate service
|
||||||
const key = await kmsService.generateKmsKey({
|
const key = await kmsService.generateKmsKey({
|
||||||
scopeId: projectId,
|
|
||||||
scopeType: "project",
|
|
||||||
isReserved: true,
|
isReserved: true,
|
||||||
|
orgId: project.orgId,
|
||||||
tx
|
tx
|
||||||
});
|
});
|
||||||
|
|
||||||
|
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user